{ "RECORDS": [ { "_id": "6367676d1a6d9265ec018229", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static String[] trimArrayElements(String[] array){\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result=new String[array.length];\n for (int i=0; i < array.length; i++) {\n String element=array[i];\n result[i]=(element != null ? element.trim() : null);\n }\n return result;\n}\n", "docstring": "/** \n * Trim the elements of the given String array, calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n", "end_lineno": "842", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *
\n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
\n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Trim each element in the given string array and return the resulting array.", "level": "self_contained", "lineno": "826", "name": "trimArrayElements", "oracle_context": "{ \"apis\" : \"[isEmpty, trim]\", \"classes\" : \"[String[], String]\", \"vars\" : \"[length]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "6367670b1a6d9265ec017a00", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static boolean isSameLength(final byte[] array1,final byte[] array2){\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n}\n", "docstring": "/** \n *

Checks whether two arrays are the same length, treating null arrays as length 0.

\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treatingnull as an empty array\n */\n", "end_lineno": "1130", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

\n *\n *

This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

\n *\n *

#ThreadSafe#

\n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

\n *\n *

This method can be used to initialize:

\n *
\n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
\n *\n *

This method returns null for a null input array.

\n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

Shallow clones an array returning a typecast result and handling\n * null.

\n *\n *

The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

Produces a new array containing the elements between\n * the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n *

The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

\n *\n *
\n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new long array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new int array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new short array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new char array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new byte array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new double array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new float array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new boolean array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

Any multi-dimensional aspects of the arrays are ignored.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

\n *\n *

If the input array is null, 0 is returned.

\n *\n *
\n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
\n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

\n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

Reverses the order of the given array.

\n *\n *

There is no special handling for multi-dimensional arrays.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given object in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

Finds the index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given object within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the object is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

\n *\n *

The method returns false if a null array\n * is passed in.

\n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Characters to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Character to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive chars to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Longs to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Long to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive longs to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Integers to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Integer to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive ints to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Shorts to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Short to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive shorts to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Bytes to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Bytes to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive bytes to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Doubles to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Doubles to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive doubles to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Floats to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Floats to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive floats to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Booleans to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Booleans to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive booleans to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive longs is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive ints is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive chars is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive floats is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive longs is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive ints is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive chars is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive floats is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

\n *\n *
\n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Check whether the length of the given two byte arrays is the same.", "level": "self_contained", "lineno": "1116", "name": "isSameLength", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[length]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636766a91a6d9265ec0175c2", "all_context": "{ \"class_level\" : \"int SAME_FRAME;\\nint SAME_LOCALS_1_STACK_ITEM_FRAME;\\nint SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED;\\nint CHOP_FRAME;\\nint SAME_FRAME_EXTENDED;\\nint APPEND_FRAME;\\nint FULL_FRAME;\\nint ITEM_TOP;\\nint ITEM_INTEGER;\\nint ITEM_FLOAT;\\nint ITEM_DOUBLE;\\nint ITEM_LONG;\\nint ITEM_NULL;\\nint ITEM_UNINITIALIZED_THIS;\\nint ITEM_OBJECT;\\nint ITEM_UNINITIALIZED;\\nint ITEM_ASM_BOOLEAN;\\nint ITEM_ASM_BYTE;\\nint ITEM_ASM_CHAR;\\nint ITEM_ASM_SHORT;\\nint DIM_SIZE;\\nint KIND_SIZE;\\nint FLAGS_SIZE;\\nint VALUE_SIZE;\\nint DIM_SHIFT;\\nint KIND_SHIFT;\\nint FLAGS_SHIFT;\\nint DIM_MASK;\\nint KIND_MASK;\\nint VALUE_MASK;\\nint ARRAY_OF;\\nint ELEMENT_OF;\\nint CONSTANT_KIND;\\nint REFERENCE_KIND;\\nint UNINITIALIZED_KIND;\\nint LOCAL_KIND;\\nint STACK_KIND;\\nint TOP_IF_LONG_OR_DOUBLE_FLAG;\\nint TOP;\\nint BOOLEAN;\\nint BYTE;\\nint CHAR;\\nint SHORT;\\nint INTEGER;\\nint FLOAT;\\nint LONG;\\nint DOUBLE;\\nint NULL;\\nint UNINITIALIZED_THIS;\\nLabel owner;\\nint[] inputLocals;\\nint[] inputStack;\\nint[] outputLocals;\\nint[] outputStack;\\nshort outputStackStart;\\nshort outputStackTop;\\nint initializationCount;\\nint[] initializations;\\nFrame(Label owner);\\ngetAbstractTypeFromDescriptor(SymbolTable symbolTable,String buffer,int offset);\\nsetInputFrameFromDescriptor(SymbolTable symbolTable,int access,String descriptor,int maxLocals);\\ngetLocal(int localIndex);\\nsetLocal(int localIndex,int abstractType);\\npush(SymbolTable symbolTable,String descriptor);\\npop();\\npop(int elements);\\npop(String descriptor);\\naddInitializedType(int abstractType);\\ngetInitializedType(SymbolTable symbolTable,int abstractType);\\nexecute(int opcode,int arg,Symbol argSymbol,SymbolTable symbolTable);\\ngetConcreteOutputType(int abstractOutputType,int numStack);\\nmerge(SymbolTable symbolTable,Frame dstFrame);\\nmerge(SymbolTable symbolTable,int sourceType,int[] dstTypes,int dstIndex);\\naccept(MethodWriter methodWriter);\\npush(int abstractType);\\n\", \"repo_level\" : \"\" }", "class_name": "Frame", "code": "private int pop(){\n if (outputStackTop > 0) {\n return outputStack[--outputStackTop];\n }\n else {\n return STACK_KIND | -(--outputStackStart);\n }\n}\n", "docstring": "/** \n * Pops an abstract type from the output frame stack and returns its value.\n * @return the abstract type that has been popped from the output frame stack.\n */\n", "end_lineno": "629", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage com.alibaba.fastjson2.internal.asm;\n\n/**\n * @author Eric Bruneton\n */\nclass Frame {\n // Constants used in the StackMapTable attribute.\n // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.4.\n\n static final int SAME_FRAME = 0;\n static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64;\n// static final int RESERVED = 128;\n static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247;\n static final int CHOP_FRAME = 248;\n static final int SAME_FRAME_EXTENDED = 251;\n static final int APPEND_FRAME = 252;\n static final int FULL_FRAME = 255;\n\n static final int ITEM_TOP = 0;\n static final int ITEM_INTEGER = 1;\n static final int ITEM_FLOAT = 2;\n static final int ITEM_DOUBLE = 3;\n static final int ITEM_LONG = 4;\n static final int ITEM_NULL = 5;\n static final int ITEM_UNINITIALIZED_THIS = 6;\n static final int ITEM_OBJECT = 7;\n static final int ITEM_UNINITIALIZED = 8;\n // Additional, ASM specific constants used in abstract types below.\n static final int ITEM_ASM_BOOLEAN = 9;\n static final int ITEM_ASM_BYTE = 10;\n static final int ITEM_ASM_CHAR = 11;\n static final int ITEM_ASM_SHORT = 12;\n\n // The size and offset in bits of each field of an abstract type.\n\n static final int DIM_SIZE = 6;\n static final int KIND_SIZE = 4;\n static final int FLAGS_SIZE = 2;\n static final int VALUE_SIZE = 32 - DIM_SIZE - KIND_SIZE - FLAGS_SIZE;\n\n static final int DIM_SHIFT = KIND_SIZE + FLAGS_SIZE + VALUE_SIZE;\n static final int KIND_SHIFT = FLAGS_SIZE + VALUE_SIZE;\n static final int FLAGS_SHIFT = VALUE_SIZE;\n\n // Bitmasks to get each field of an abstract type.\n\n static final int DIM_MASK = ((1 << DIM_SIZE) - 1) << DIM_SHIFT;\n static final int KIND_MASK = ((1 << KIND_SIZE) - 1) << KIND_SHIFT;\n static final int VALUE_MASK = (1 << VALUE_SIZE) - 1;\n\n // Constants to manipulate the DIM field of an abstract type.\n\n /**\n * The constant to be added to an abstract type to get one with one more array dimension.\n */\n static final int ARRAY_OF = +1 << DIM_SHIFT;\n\n /**\n * The constant to be added to an abstract type to get one with one less array dimension.\n */\n static final int ELEMENT_OF = -1 << DIM_SHIFT;\n\n // Possible values for the KIND field of an abstract type.\n\n static final int CONSTANT_KIND = 1 << KIND_SHIFT;\n static final int REFERENCE_KIND = 2 << KIND_SHIFT;\n static final int UNINITIALIZED_KIND = 3 << KIND_SHIFT;\n static final int LOCAL_KIND = 4 << KIND_SHIFT;\n static final int STACK_KIND = 5 << KIND_SHIFT;\n\n // Possible flags for the FLAGS field of an abstract type.\n\n /**\n * A flag used for LOCAL_KIND and STACK_KIND abstract types, indicating that if the resolved,\n * concrete type is LONG or DOUBLE, TOP should be used instead (because the value has been\n * partially overridden with an xSTORE instruction).\n */\n private static final int TOP_IF_LONG_OR_DOUBLE_FLAG = 1 << FLAGS_SHIFT;\n\n // Useful predefined abstract types (all the possible CONSTANT_KIND types).\n\n private static final int TOP = CONSTANT_KIND | ITEM_TOP;\n private static final int BOOLEAN = CONSTANT_KIND | ITEM_ASM_BOOLEAN;\n private static final int BYTE = CONSTANT_KIND | ITEM_ASM_BYTE;\n private static final int CHAR = CONSTANT_KIND | ITEM_ASM_CHAR;\n private static final int SHORT = CONSTANT_KIND | ITEM_ASM_SHORT;\n private static final int INTEGER = CONSTANT_KIND | ITEM_INTEGER;\n private static final int FLOAT = CONSTANT_KIND | ITEM_FLOAT;\n private static final int LONG = CONSTANT_KIND | ITEM_LONG;\n private static final int DOUBLE = CONSTANT_KIND | ITEM_DOUBLE;\n private static final int NULL = CONSTANT_KIND | ITEM_NULL;\n private static final int UNINITIALIZED_THIS = CONSTANT_KIND | ITEM_UNINITIALIZED_THIS;\n\n // -----------------------------------------------------------------------------------------------\n // Instance fields\n // -----------------------------------------------------------------------------------------------\n\n /**\n * The basic block to which these input and output stack map frames correspond.\n */\n Label owner;\n\n /**\n * The input stack map frame locals. This is an array of abstract types.\n */\n private int[] inputLocals;\n\n /**\n * The input stack map frame stack. This is an array of abstract types.\n */\n int[] inputStack;\n\n /**\n * The output stack map frame locals. This is an array of abstract types.\n */\n private int[] outputLocals;\n\n /**\n * The output stack map frame stack. This is an array of abstract types.\n */\n private int[] outputStack;\n\n /**\n * The start of the output stack, relatively to the input stack. This offset is always negative or\n * null. A null offset means that the output stack must be appended to the input stack. A -n\n * offset means that the first n output stack elements must replace the top n input stack\n * elements, and that the other elements must be appended to the input stack.\n */\n private short outputStackStart;\n\n /**\n * The index of the top stack element in {@link #outputStack}.\n */\n private short outputStackTop;\n\n /**\n * The number of types that are initialized in the basic block. See {@link #initializations}.\n */\n private int initializationCount;\n\n /**\n * The abstract types that are initialized in the basic block. A constructor invocation on an\n * UNINITIALIZED or UNINITIALIZED_THIS abstract type must replace every occurrence of this\n * type in the local variables and in the operand stack. This cannot be done during the first step\n * of the algorithm since, during this step, the local variables and the operand stack types are\n * still abstract. It is therefore necessary to store the abstract types of the constructors which\n * are invoked in the basic block, in order to do this replacement during the second step of the\n * algorithm, where the frames are fully computed. Note that this array can contain abstract types\n * that are relative to the input locals or to the input stack.\n */\n private int[] initializations;\n\n // -----------------------------------------------------------------------------------------------\n // Constructor\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Constructs a new Frame.\n *\n * @param owner the basic block to which these input and output stack map frames correspond.\n */\n Frame(final Label owner) {\n this.owner = owner;\n }\n//\n// /**\n// * Returns the abstract type corresponding to the internal name of a class.\n// *\n// * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n// * @param internalName the internal name of a class. This must not be an array type\n// * descriptor.\n// * @return the abstract type value corresponding to the given internal name.\n// */\n// static int getAbstractTypeFromInternalName(\n// final SymbolTable symbolTable, final String internalName) {\n// return REFERENCE_KIND | symbolTable.addType(internalName);\n// }\n\n /**\n * Returns the abstract type corresponding to the given type descriptor.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param buffer a string ending with a type descriptor.\n * @param offset the start offset of the type descriptor in buffer.\n * @return the abstract type corresponding to the given type descriptor.\n */\n private static int getAbstractTypeFromDescriptor(\n final SymbolTable symbolTable, final String buffer, final int offset) {\n String internalName = null;\n switch (buffer.charAt(offset)) {\n case 'V':\n return 0;\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n return INTEGER;\n case 'F':\n return FLOAT;\n case 'J':\n return LONG;\n case 'D':\n return DOUBLE;\n case 'L':\n if (offset == 0) {\n switch (buffer) {\n case \"Ljava/lang/Object;\":\n internalName = \"java/lang/Object\";\n break;\n case \"Ljava/lang/Class;\":\n internalName = \"java/lang/Class\";\n break;\n case \"Ljava/lang/String;\":\n internalName = \"java/lang/String\";\n break;\n case \"Ljava/util/List;\":\n internalName = \"java/util/List\";\n break;\n case \"Ljava/lang/reflect/Type;\":\n internalName = \"java/lang/reflect/Type\";\n break;\n case \"Ljava/util/function/Supplier;\":\n internalName = \"java/util/function/Supplier\";\n break;\n case \"Lsun/misc/Unsafe;\":\n internalName = \"sun/misc/Unsafe\";\n break;\n case \"Lcom/alibaba/fastjson2/JSONReader;\":\n internalName = \"com/alibaba/fastjson2/JSONReader\";\n break;\n case \"Lcom/alibaba/fastjson2/reader/FieldReader;\":\n internalName = \"com/alibaba/fastjson2/reader/FieldReader\";\n break;\n case \"Lcom/alibaba/fastjson2/reader/ObjectReader;\":\n internalName = \"com/alibaba/fastjson2/reader/ObjectReader\";\n break;\n case \"Lcom/alibaba/fastjson2/JSONWriter;\":\n internalName = \"com/alibaba/fastjson2/JSONWriter\";\n break;\n case \"Lcom/alibaba/fastjson2/writer/FieldWriter;\":\n internalName = \"com/alibaba/fastjson2/writer/FieldWriter\";\n break;\n default:\n break;\n }\n } else if (offset == 2) {\n switch (buffer) {\n case \"()Ljava/lang/Class;\":\n internalName = \"java/lang/Class\";\n break;\n case \"()Ljava/lang/String;\":\n internalName = \"java/lang/String\";\n break;\n default:\n break;\n }\n } else if (offset == 3) {\n switch (buffer) {\n case \"(J)Lcom/alibaba/fastjson2/reader/FieldReader;\":\n internalName = \"com/alibaba/fastjson2/reader/FieldReader\";\n break;\n case \"(I)Ljava/lang/Object;\":\n internalName = \"java/lang/Object\";\n break;\n case \"(I)Ljava/lang/Integer;\":\n internalName = \"java/lang/Integer\";\n break;\n default:\n break;\n }\n } else if (offset == 36) {\n switch (buffer) {\n case \"(Lcom/alibaba/fastjson2/JSONReader;)Lcom/alibaba/fastjson2/reader/ObjectReader;\":\n internalName = \"com/alibaba/fastjson2/reader/ObjectReader\";\n break;\n case \"(Lcom/alibaba/fastjson2/JSONReader;)Ljava/lang/Object;\":\n internalName = \"java/lang/Object\";\n break;\n default:\n break;\n }\n } else if (offset == 54) {\n switch (buffer) {\n case \"(Lcom/alibaba/fastjson2/JSONReader;Ljava/lang/Class;J)Lcom/alibaba/fastjson2/reader/ObjectReader;\":\n internalName = \"com/alibaba/fastjson2/reader/ObjectReader\";\n break;\n case \"(Lcom/alibaba/fastjson2/JSONReader;Ljava/lang/Class;J)Ljava/lang/Object;\":\n internalName = \"java/lang/Object\";\n break;\n default:\n break;\n }\n } else {\n switch (buffer) {\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/Class;)Lcom/alibaba/fastjson2/writer/ObjectWriter;\":\n if (offset == 53) {\n internalName = \"com/alibaba/fastjson2/writer/ObjectWriter\";\n }\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/reflect/Type;)Lcom/alibaba/fastjson2/writer/ObjectWriter;\":\n if (offset == 60) {\n internalName = \"com/alibaba/fastjson2/writer/ObjectWriter\";\n }\n break;\n case \"(Lcom/alibaba/fastjson2/writer/FieldWriter;Ljava/lang/Object;)Ljava/lang/String;\":\n if (offset == 62) {\n internalName = \"java/lang/String\";\n }\n break;\n case \"(Lcom/alibaba/fastjson2/JSONReader;Ljava/lang/reflect/Type;Ljava/lang/Object;J)Ljava/lang/Object;\":\n if (offset == 79) {\n internalName = \"java/lang/Object\";\n }\n break;\n default:\n break;\n }\n }\n\n if (internalName == null) {\n internalName = buffer.substring(offset + 1, buffer.length() - 1);\n }\n return REFERENCE_KIND | symbolTable.addType(internalName);\n case '[':\n int elementDescriptorOffset = offset + 1;\n while (buffer.charAt(elementDescriptorOffset) == '[') {\n ++elementDescriptorOffset;\n }\n int typeValue;\n switch (buffer.charAt(elementDescriptorOffset)) {\n case 'Z':\n typeValue = BOOLEAN;\n break;\n case 'C':\n typeValue = CHAR;\n break;\n case 'B':\n typeValue = BYTE;\n break;\n case 'S':\n typeValue = SHORT;\n break;\n case 'I':\n typeValue = INTEGER;\n break;\n case 'F':\n typeValue = FLOAT;\n break;\n case 'J':\n typeValue = LONG;\n break;\n case 'D':\n typeValue = DOUBLE;\n break;\n case 'L':\n if (offset == 0) {\n switch (buffer) {\n case \"[Lcom/alibaba/fastjson2/writer/FieldWriter;\":\n internalName = \"com/alibaba/fastjson2/reader/FieldReader\";\n break;\n case \"[Lcom/alibaba/fastjson2/reader/FieldReader;\":\n internalName = \"Lcom/alibaba/fastjson2/reader/FieldReader\";\n break;\n default:\n break;\n }\n }\n if (internalName == null) {\n internalName = buffer.substring(elementDescriptorOffset + 1, buffer.length() - 1);\n }\n typeValue = REFERENCE_KIND | symbolTable.addType(internalName);\n break;\n default:\n throw new IllegalArgumentException();\n }\n return ((elementDescriptorOffset - offset) << DIM_SHIFT) | typeValue;\n default:\n throw new IllegalArgumentException();\n }\n }\n\n // -----------------------------------------------------------------------------------------------\n // Methods related to the input frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Sets the input frame from the given method description. This method is used to initialize the\n * first frame of a method, which is implicit (i.e. not stored explicitly in the StackMapTable\n * attribute).\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param access the method's access flags.\n * @param descriptor the method descriptor.\n * @param maxLocals the maximum number of local variables of the method.\n */\n final void setInputFrameFromDescriptor(\n final SymbolTable symbolTable,\n final int access,\n final String descriptor,\n final int maxLocals) {\n inputLocals = new int[maxLocals];\n inputStack = new int[0];\n int inputLocalIndex = 0;\n if ((access & Opcodes.ACC_STATIC) == 0) {\n if ((access & Constants.ACC_CONSTRUCTOR) == 0) {\n inputLocals[inputLocalIndex++] =\n REFERENCE_KIND | symbolTable.addType(symbolTable.className);\n } else {\n inputLocals[inputLocalIndex++] = UNINITIALIZED_THIS;\n }\n }\n for (Type argumentType : Type.getArgumentTypes(descriptor)) {\n int abstractType =\n getAbstractTypeFromDescriptor(symbolTable, argumentType.getDescriptor(), 0);\n inputLocals[inputLocalIndex++] = abstractType;\n if (abstractType == LONG || abstractType == DOUBLE) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n }\n while (inputLocalIndex < maxLocals) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n }\n\n // -----------------------------------------------------------------------------------------------\n // Methods related to the output frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the abstract type stored at the given local variable index in the output frame.\n *\n * @param localIndex the index of the local variable whose value must be returned.\n * @return the abstract type stored at the given local variable index in the output frame.\n */\n private int getLocal(final int localIndex) {\n if (outputLocals == null || localIndex >= outputLocals.length) {\n // If this local has never been assigned in this basic block, it is still equal to its value\n // in the input frame.\n return LOCAL_KIND | localIndex;\n } else {\n int abstractType = outputLocals[localIndex];\n if (abstractType == 0) {\n // If this local has never been assigned in this basic block, so it is still equal to its\n // value in the input frame.\n abstractType = outputLocals[localIndex] = LOCAL_KIND | localIndex;\n }\n return abstractType;\n }\n }\n\n /**\n * Replaces the abstract type stored at the given local variable index in the output frame.\n *\n * @param localIndex the index of the output frame local variable that must be set.\n * @param abstractType the value that must be set.\n */\n private void setLocal(final int localIndex, final int abstractType) {\n // Create and/or resize the output local variables array if necessary.\n if (outputLocals == null) {\n outputLocals = new int[10];\n }\n int outputLocalsLength = outputLocals.length;\n if (localIndex >= outputLocalsLength) {\n int[] newOutputLocals = new int[Math.max(localIndex + 1, 2 * outputLocalsLength)];\n System.arraycopy(outputLocals, 0, newOutputLocals, 0, outputLocalsLength);\n outputLocals = newOutputLocals;\n }\n // Set the local variable.\n outputLocals[localIndex] = abstractType;\n }\n\n /**\n * Pushes the given abstract type on the output frame stack.\n *\n * @param abstractType an abstract type.\n */\n private void push(final int abstractType) {\n // Create and/or resize the output stack array if necessary.\n if (outputStack == null) {\n outputStack = new int[10];\n }\n int outputStackLength = outputStack.length;\n if (outputStackTop >= outputStackLength) {\n int[] newOutputStack = new int[Math.max(outputStackTop + 1, 2 * outputStackLength)];\n System.arraycopy(outputStack, 0, newOutputStack, 0, outputStackLength);\n outputStack = newOutputStack;\n }\n // Pushes the abstract type on the output stack.\n outputStack[outputStackTop++] = abstractType;\n // Updates the maximum size reached by the output stack, if needed (note that this size is\n // relative to the input stack size, which is not known yet).\n short outputStackSize = (short) (outputStackStart + outputStackTop);\n if (outputStackSize > owner.outputStackMax) {\n owner.outputStackMax = outputStackSize;\n }\n }\n\n /**\n * Pushes the abstract type corresponding to the given descriptor on the output frame stack.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param descriptor a type or method descriptor (in which case its return type is pushed).\n */\n private void push(final SymbolTable symbolTable, final String descriptor) {\n final int typeDescriptorOffset;\n switch (descriptor) {\n case \"()J\":\n case \"()V\":\n case \"()Z\":\n case \"()I\":\n case \"()Ljava/lang/Class;\":\n typeDescriptorOffset = 2;\n break;\n case \"(I)V\":\n case \"(J)V\":\n case \"(J)Z\":\n case \"(I)Ljava/lang/Object;\":\n case \"(I)Ljava/lang/Integer;\":\n typeDescriptorOffset = 3;\n break;\n case \"(Ljava/lang/Enum;)V\":\n typeDescriptorOffset = 18;\n break;\n case \"(Ljava/lang/Object;)Z\":\n case \"(Ljava/lang/String;)V\":\n case \"(Ljava/lang/Object;)V\":\n typeDescriptorOffset = 20;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;)V\":\n case \"(Lcom/alibaba/fastjson2/JSONWriter;)Z\":\n typeDescriptorOffset = 36;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;I)V\":\n case \"(Lcom/alibaba/fastjson2/JSONWriter;J)V\":\n typeDescriptorOffset = 37;\n break;\n case \"(Ljava/lang/Object;Ljava/lang/reflect/Type;)Z\":\n typeDescriptorOffset = 44;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/Enum;)V\":\n typeDescriptorOffset = 52;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/Class;)Lcom/alibaba/fastjson2/writer/ObjectWriter;\":\n case \"(Lcom/alibaba/fastjson2/JSONWriter;ZLjava/util/List;)V\":\n typeDescriptorOffset = 53;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/reflect/Type;)Lcom/alibaba/fastjson2/writer/ObjectWriter;\":\n typeDescriptorOffset = 60;\n break;\n case \"(Lcom/alibaba/fastjson2/writer/FieldWriter;Ljava/lang/Object;)Ljava/lang/String;\":\n typeDescriptorOffset = 62;\n break;\n case \"(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;JLjava/util/List;)V\":\n typeDescriptorOffset = 72;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;J)V\":\n typeDescriptorOffset = 97;\n break;\n default:\n if (descriptor.charAt(0) == '(') {\n int currentOffset = 1;\n // Skip the argument types, one at a each loop iteration.\n while (descriptor.charAt(currentOffset) != ')') {\n while (descriptor.charAt(currentOffset) == '[') {\n currentOffset++;\n }\n if (descriptor.charAt(currentOffset++) == 'L') {\n // Skip the argument descriptor content.\n int semiColumnOffset = descriptor.indexOf(';', currentOffset);\n currentOffset = Math.max(currentOffset, semiColumnOffset + 1);\n }\n }\n typeDescriptorOffset = currentOffset + 1;\n } else {\n typeDescriptorOffset = 0;\n }\n break;\n }\n\n int abstractType = getAbstractTypeFromDescriptor(symbolTable, descriptor, typeDescriptorOffset);\n if (abstractType != 0) {\n push(abstractType);\n if (abstractType == LONG || abstractType == DOUBLE) {\n push(TOP);\n }\n }\n }\n\n /**\n * Pops an abstract type from the output frame stack and returns its value.\n *\n * @return the abstract type that has been popped from the output frame stack.\n */\n private int pop() {\n if (outputStackTop > 0) {\n return outputStack[--outputStackTop];\n } else {\n // If the output frame stack is empty, pop from the input stack.\n return STACK_KIND | -(--outputStackStart);\n }\n }\n\n /**\n * Pops the given number of abstract types from the output frame stack.\n *\n * @param elements the number of abstract types that must be popped.\n */\n private void pop(final int elements) {\n if (outputStackTop >= elements) {\n outputStackTop -= elements;\n } else {\n // If the number of elements to be popped is greater than the number of elements in the output\n // stack, clear it, and pop the remaining elements from the input stack.\n outputStackStart -= elements - outputStackTop;\n outputStackTop = 0;\n }\n }\n\n /**\n * Pops as many abstract types from the output frame stack as described by the given descriptor.\n *\n * @param descriptor a type or method descriptor (in which case its argument types are popped).\n */\n private void pop(final String descriptor) {\n char firstDescriptorChar = descriptor.charAt(0);\n if (firstDescriptorChar == '(') {\n pop((Type.getArgumentsAndReturnSizes(descriptor) >> 2) - 1);\n } else if (firstDescriptorChar == 'J' || firstDescriptorChar == 'D') {\n pop(2);\n } else {\n pop(1);\n }\n }\n\n // -----------------------------------------------------------------------------------------------\n // Methods to handle uninitialized types\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Adds an abstract type to the list of types on which a constructor is invoked in the basic\n * block.\n *\n * @param abstractType an abstract type on a which a constructor is invoked.\n */\n private void addInitializedType(final int abstractType) {\n // Create and/or resize the initializations array if necessary.\n if (initializations == null) {\n initializations = new int[2];\n }\n int initializationsLength = initializations.length;\n if (initializationCount >= initializationsLength) {\n int[] newInitializations =\n new int[Math.max(initializationCount + 1, 2 * initializationsLength)];\n System.arraycopy(initializations, 0, newInitializations, 0, initializationsLength);\n initializations = newInitializations;\n }\n // Store the abstract type.\n initializations[initializationCount++] = abstractType;\n }\n\n /**\n * Returns the \"initialized\" abstract type corresponding to the given abstract type.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param abstractType an abstract type.\n * @return the REFERENCE_KIND abstract type corresponding to abstractType if it is\n * UNINITIALIZED_THIS or an UNINITIALIZED_KIND abstract type for one of the types on which a\n * constructor is invoked in the basic block. Otherwise returns abstractType.\n */\n private int getInitializedType(final SymbolTable symbolTable, final int abstractType) {\n if (abstractType == UNINITIALIZED_THIS\n || (abstractType & (DIM_MASK | KIND_MASK)) == UNINITIALIZED_KIND) {\n for (int i = 0; i < initializationCount; ++i) {\n int initializedType = initializations[i];\n int dim = initializedType & DIM_MASK;\n int kind = initializedType & KIND_MASK;\n int value = initializedType & VALUE_MASK;\n if (kind == LOCAL_KIND) {\n initializedType = dim + inputLocals[value];\n } else if (kind == STACK_KIND) {\n initializedType = dim + inputStack[inputStack.length - value];\n }\n if (abstractType == initializedType) {\n if (abstractType == UNINITIALIZED_THIS) {\n return REFERENCE_KIND | symbolTable.addType(symbolTable.className);\n } else {\n return REFERENCE_KIND\n | symbolTable.addType(symbolTable.typeTable[abstractType & VALUE_MASK].value);\n }\n }\n }\n }\n return abstractType;\n }\n\n // -----------------------------------------------------------------------------------------------\n // Main method, to simulate the execution of each instruction on the output frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Simulates the action of the given instruction on the output stack frame.\n *\n * @param opcode the opcode of the instruction.\n * @param arg the numeric operand of the instruction, if any.\n * @param argSymbol the Symbol operand of the instruction, if any.\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n */\n void execute(\n final int opcode, final int arg, final Symbol argSymbol, final SymbolTable symbolTable) {\n final int CONSTANT_INTEGER_TAG = 3;\n final int CONSTANT_FLOAT_TAG = 4;\n final int CONSTANT_LONG_TAG = 5;\n final int CONSTANT_DOUBLE_TAG = 6;\n final int CONSTANT_CLASS_TAG = 7;\n final int CONSTANT_STRING_TAG = 8;\n final int CONSTANT_METHOD_HANDLE_TAG = 15;\n final int CONSTANT_METHOD_TYPE_TAG = 16;\n final int CONSTANT_DYNAMIC_TAG = 17;\n\n // Abstract types popped from the stack or read from local variables.\n int abstractType1;\n int abstractType2;\n int abstractType3;\n int abstractType4;\n switch (opcode) {\n case Opcodes.NOP:\n case Opcodes.INEG:\n case Opcodes.LNEG:\n case Opcodes.FNEG:\n case Opcodes.DNEG:\n case Opcodes.I2B:\n case Opcodes.I2C:\n case Opcodes.I2S:\n case Opcodes.GOTO:\n case Opcodes.RETURN:\n break;\n case Opcodes.ACONST_NULL:\n push(NULL);\n break;\n case Opcodes.ICONST_M1:\n case Opcodes.ICONST_0:\n case Opcodes.ICONST_1:\n case Opcodes.ICONST_2:\n case Opcodes.ICONST_3:\n case Opcodes.ICONST_4:\n case Opcodes.ICONST_5:\n case Opcodes.BIPUSH:\n case Opcodes.SIPUSH:\n case Opcodes.ILOAD:\n push(INTEGER);\n break;\n case Opcodes.LCONST_0:\n case Opcodes.LCONST_1:\n case Opcodes.LLOAD:\n push(LONG);\n push(TOP);\n break;\n case Opcodes.FCONST_0:\n case Opcodes.FCONST_1:\n case Opcodes.FCONST_2:\n case Opcodes.FLOAD:\n push(FLOAT);\n break;\n case Opcodes.DCONST_0:\n case Opcodes.DCONST_1:\n case Opcodes.DLOAD:\n push(DOUBLE);\n push(TOP);\n break;\n case Opcodes.LDC:\n switch (argSymbol.tag) {\n case CONSTANT_INTEGER_TAG:\n push(INTEGER);\n break;\n case CONSTANT_LONG_TAG:\n push(LONG);\n push(TOP);\n break;\n case CONSTANT_FLOAT_TAG:\n push(FLOAT);\n break;\n case CONSTANT_DOUBLE_TAG:\n push(DOUBLE);\n push(TOP);\n break;\n case CONSTANT_CLASS_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/Class\"));\n break;\n case CONSTANT_STRING_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/String\"));\n break;\n case CONSTANT_METHOD_TYPE_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/invoke/MethodType\"));\n break;\n case CONSTANT_METHOD_HANDLE_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/invoke/MethodHandle\"));\n break;\n case CONSTANT_DYNAMIC_TAG:\n push(symbolTable, argSymbol.value);\n break;\n default:\n throw new AssertionError();\n }\n break;\n case Opcodes.ALOAD:\n push(getLocal(arg));\n break;\n case Opcodes.LALOAD:\n case Opcodes.D2L:\n pop(2);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.AALOAD:\n pop(1);\n abstractType1 = pop();\n push(abstractType1 == NULL ? abstractType1 : ELEMENT_OF + abstractType1);\n break;\n case Opcodes.ISTORE:\n case Opcodes.FSTORE:\n case Opcodes.ASTORE:\n abstractType1 = pop();\n setLocal(arg, abstractType1);\n if (arg > 0) {\n int previousLocalType = getLocal(arg - 1);\n if (previousLocalType == LONG || previousLocalType == DOUBLE) {\n setLocal(arg - 1, TOP);\n } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND\n || (previousLocalType & KIND_MASK) == STACK_KIND) {\n // The type of the previous local variable is not known yet, but if it later appears\n // to be LONG or DOUBLE, we should then use TOP instead.\n setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG);\n }\n }\n break;\n case Opcodes.LSTORE:\n case Opcodes.DSTORE:\n pop(1);\n abstractType1 = pop();\n setLocal(arg, abstractType1);\n setLocal(arg + 1, TOP);\n if (arg > 0) {\n int previousLocalType = getLocal(arg - 1);\n if (previousLocalType == LONG || previousLocalType == DOUBLE) {\n setLocal(arg - 1, TOP);\n } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND\n || (previousLocalType & KIND_MASK) == STACK_KIND) {\n // The type of the previous local variable is not known yet, but if it later appears\n // to be LONG or DOUBLE, we should then use TOP instead.\n setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG);\n }\n }\n break;\n case Opcodes.POP:\n case Opcodes.IFEQ:\n case Opcodes.IFNE:\n case Opcodes.IFLT:\n case Opcodes.IFGE:\n case Opcodes.IFGT:\n case Opcodes.IFLE:\n case Opcodes.IRETURN:\n case Opcodes.FRETURN:\n case Opcodes.ARETURN:\n case Opcodes.TABLESWITCH:\n case Opcodes.LOOKUPSWITCH:\n case Opcodes.ATHROW:\n case Opcodes.MONITORENTER:\n case Opcodes.MONITOREXIT:\n case Opcodes.IFNULL:\n case Opcodes.IFNONNULL:\n pop(1);\n break;\n case Opcodes.POP2:\n case Opcodes.IF_ICMPEQ:\n case Opcodes.IF_ICMPNE:\n case Opcodes.IF_ICMPLT:\n case Opcodes.IF_ICMPGE:\n case Opcodes.IF_ICMPGT:\n case Opcodes.IF_ICMPLE:\n case Opcodes.IF_ACMPEQ:\n case Opcodes.IF_ACMPNE:\n case Opcodes.LRETURN:\n case Opcodes.DRETURN:\n pop(2);\n break;\n case Opcodes.DUP:\n abstractType1 = pop();\n push(abstractType1);\n push(abstractType1);\n break;\n case Opcodes.DUP2:\n abstractType1 = pop();\n abstractType2 = pop();\n push(abstractType2);\n push(abstractType1);\n push(abstractType2);\n push(abstractType1);\n break;\n case Opcodes.SWAP:\n abstractType1 = pop();\n abstractType2 = pop();\n push(abstractType1);\n push(abstractType2);\n break;\n case Opcodes.IALOAD:\n case Opcodes.BALOAD:\n case Opcodes.CALOAD:\n case Opcodes.SALOAD:\n case Opcodes.IADD:\n case Opcodes.ISUB:\n case Opcodes.IMUL:\n case Opcodes.IDIV:\n case Opcodes.IREM:\n case Opcodes.IAND:\n case Opcodes.IOR:\n case Opcodes.IXOR:\n case Opcodes.ISHL:\n case Opcodes.ISHR:\n case Opcodes.IUSHR:\n case Opcodes.L2I:\n case Opcodes.D2I:\n case Opcodes.FCMPL:\n case Opcodes.FCMPG:\n pop(2);\n push(INTEGER);\n break;\n case Opcodes.LADD:\n case Opcodes.LSUB:\n case Opcodes.LMUL:\n case Opcodes.LDIV:\n case Opcodes.LREM:\n case Opcodes.LAND:\n case Opcodes.LOR:\n case Opcodes.LXOR:\n pop(4);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.LSHL:\n case Opcodes.LSHR:\n case Opcodes.LUSHR:\n pop(3);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.IINC:\n setLocal(arg, INTEGER);\n break;\n case Opcodes.F2I:\n case Opcodes.ARRAYLENGTH:\n case Opcodes.INSTANCEOF:\n pop(1);\n push(INTEGER);\n break;\n case Opcodes.LCMP:\n case Opcodes.DCMPL:\n case Opcodes.DCMPG:\n pop(4);\n push(INTEGER);\n break;\n case Opcodes.GETSTATIC:\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.PUTSTATIC:\n pop(argSymbol.value);\n break;\n case Opcodes.GETFIELD:\n pop(1);\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.PUTFIELD:\n pop(argSymbol.value);\n pop();\n break;\n case Opcodes.INVOKEVIRTUAL:\n case Opcodes.INVOKESPECIAL:\n case Opcodes.INVOKESTATIC:\n case Opcodes.INVOKEINTERFACE:\n pop(argSymbol.value);\n if (opcode != Opcodes.INVOKESTATIC) {\n abstractType1 = pop();\n if (opcode == Opcodes.INVOKESPECIAL && argSymbol.name.charAt(0) == '<') {\n addInitializedType(abstractType1);\n }\n }\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.NEW:\n push(UNINITIALIZED_KIND | symbolTable.addUninitializedType(argSymbol.value, arg));\n break;\n case Opcodes.CHECKCAST:\n String castType = argSymbol.value;\n pop();\n if (castType.charAt(0) == '[') {\n push(symbolTable, castType);\n } else {\n push(REFERENCE_KIND | symbolTable.addType(castType));\n }\n break;\n default:\n throw new IllegalArgumentException();\n }\n }\n\n // -----------------------------------------------------------------------------------------------\n // Frame merging methods, used in the second step of the stack map frame computation algorithm\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Computes the concrete output type corresponding to a given abstract output type.\n *\n * @param abstractOutputType an abstract output type.\n * @param numStack the size of the input stack, used to resolve abstract output types of\n * STACK_KIND kind.\n * @return the concrete output type corresponding to 'abstractOutputType'.\n */\n private int getConcreteOutputType(final int abstractOutputType, final int numStack) {\n int dim = abstractOutputType & DIM_MASK;\n int kind = abstractOutputType & KIND_MASK;\n if (kind == LOCAL_KIND) {\n // By definition, a LOCAL_KIND type designates the concrete type of a local variable at\n // the beginning of the basic block corresponding to this frame (which is known when\n // this method is called, but was not when the abstract type was computed).\n int concreteOutputType = dim + inputLocals[abstractOutputType & VALUE_MASK];\n if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0\n && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) {\n concreteOutputType = TOP;\n }\n return concreteOutputType;\n } else if (kind == STACK_KIND) {\n // By definition, a STACK_KIND type designates the concrete type of a local variable at\n // the beginning of the basic block corresponding to this frame (which is known when\n // this method is called, but was not when the abstract type was computed).\n int concreteOutputType = dim + inputStack[numStack - (abstractOutputType & VALUE_MASK)];\n if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0\n && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) {\n concreteOutputType = TOP;\n }\n return concreteOutputType;\n } else {\n return abstractOutputType;\n }\n }\n\n final boolean merge(\n final SymbolTable symbolTable, final Frame dstFrame) {\n boolean frameChanged = false;\n\n // Compute the concrete types of the local variables at the end of the basic block corresponding\n // to this frame, by resolving its abstract output types, and merge these concrete types with\n // those of the local variables in the input frame of dstFrame.\n int numLocal = inputLocals.length;\n int numStack = inputStack.length;\n if (dstFrame.inputLocals == null) {\n dstFrame.inputLocals = new int[numLocal];\n frameChanged = true;\n }\n for (int i = 0; i < numLocal; ++i) {\n int concreteOutputType;\n if (outputLocals != null && i < outputLocals.length) {\n int abstractOutputType = outputLocals[i];\n if (abstractOutputType == 0) {\n // If the local variable has never been assigned in this basic block, it is equal to its\n // value at the beginning of the block.\n concreteOutputType = inputLocals[i];\n } else {\n concreteOutputType = getConcreteOutputType(abstractOutputType, numStack);\n }\n } else {\n // If the local variable has never been assigned in this basic block, it is equal to its\n // value at the beginning of the block.\n concreteOutputType = inputLocals[i];\n }\n // concreteOutputType might be an uninitialized type from the input locals or from the input\n // stack. However, if a constructor has been called for this class type in the basic block,\n // then this type is no longer uninitialized at the end of basic block.\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputLocals, i);\n }\n\n // Compute the concrete types of the stack operands at the end of the basic block corresponding\n // to this frame, by resolving its abstract output types, and merge these concrete types with\n // those of the stack operands in the input frame of dstFrame.\n int numInputStack = inputStack.length + outputStackStart;\n if (dstFrame.inputStack == null) {\n dstFrame.inputStack = new int[numInputStack + outputStackTop];\n frameChanged = true;\n }\n // First, do this for the stack operands that have not been popped in the basic block\n // corresponding to this frame, and which are therefore equal to their value in the input\n // frame (except for uninitialized types, which may have been initialized).\n for (int i = 0; i < numInputStack; ++i) {\n int concreteOutputType = inputStack[i];\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputStack, i);\n }\n // Then, do this for the stack operands that have pushed in the basic block (this code is the\n // same as the one above for local variables).\n for (int i = 0; i < outputStackTop; ++i) {\n int abstractOutputType = outputStack[i];\n int concreteOutputType = getConcreteOutputType(abstractOutputType, numStack);\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |=\n merge(symbolTable, concreteOutputType, dstFrame.inputStack, numInputStack + i);\n }\n return frameChanged;\n }\n\n /**\n * Merges the type at the given index in the given abstract type array with the given type.\n * Returns {@literal true} if the type array has been modified by this operation.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param sourceType the abstract type with which the abstract type array element must be merged.\n * This type should be of {@link #CONSTANT_KIND}, {@link #REFERENCE_KIND} or {@link\n * #UNINITIALIZED_KIND} kind, with positive or {@literal null} array dimensions.\n * @param dstTypes an array of abstract types. These types should be of {@link #CONSTANT_KIND},\n * {@link #REFERENCE_KIND} or {@link #UNINITIALIZED_KIND} kind, with positive or {@literal\n * null} array dimensions.\n * @param dstIndex the index of the type that must be merged in dstTypes.\n * @return {@literal true} if the type array has been modified by this operation.\n */\n private static boolean merge(\n final SymbolTable symbolTable,\n final int sourceType,\n final int[] dstTypes,\n final int dstIndex) {\n int dstType = dstTypes[dstIndex];\n if (dstType == sourceType) {\n // If the types are equal, merge(sourceType, dstType) = dstType, so there is no change.\n return false;\n }\n int srcType = sourceType;\n if ((sourceType & ~DIM_MASK) == NULL) {\n if (dstType == NULL) {\n return false;\n }\n srcType = NULL;\n }\n if (dstType == 0) {\n // If dstTypes[dstIndex] has never been assigned, merge(srcType, dstType) = srcType.\n dstTypes[dstIndex] = srcType;\n return true;\n }\n int mergedType;\n if ((dstType & DIM_MASK) != 0 || (dstType & KIND_MASK) == REFERENCE_KIND) {\n // If dstType is a reference type of any array dimension.\n if (srcType == NULL) {\n // If srcType is the NULL type, merge(srcType, dstType) = dstType, so there is no change.\n return false;\n } else if ((srcType & (DIM_MASK | KIND_MASK)) == (dstType & (DIM_MASK | KIND_MASK))) {\n // If srcType has the same array dimension and the same kind as dstType.\n if ((dstType & KIND_MASK) == REFERENCE_KIND) {\n // If srcType and dstType are reference types with the same array dimension,\n // merge(srcType, dstType) = dim(srcType) | common super class of srcType and dstType.\n mergedType =\n (srcType & DIM_MASK)\n | REFERENCE_KIND\n | symbolTable.addMergedType(srcType & VALUE_MASK, dstType & VALUE_MASK);\n } else {\n // If srcType and dstType are array types of equal dimension but different element types,\n // merge(srcType, dstType) = dim(srcType) - 1 | java/lang/Object.\n int mergedDim = ELEMENT_OF + (srcType & DIM_MASK);\n mergedType = mergedDim | REFERENCE_KIND | symbolTable.addType(\"java/lang/Object\");\n }\n } else if ((srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND) {\n // If srcType is any other reference or array type,\n // merge(srcType, dstType) = min(srcDdim, dstDim) | java/lang/Object\n // where srcDim is the array dimension of srcType, minus 1 if srcType is an array type\n // with a non reference element type (and similarly for dstDim).\n int srcDim = srcType & DIM_MASK;\n if (srcDim != 0 && (srcType & KIND_MASK) != REFERENCE_KIND) {\n srcDim = ELEMENT_OF + srcDim;\n }\n int dstDim = dstType & DIM_MASK;\n if (dstDim != 0 && (dstType & KIND_MASK) != REFERENCE_KIND) {\n dstDim = ELEMENT_OF + dstDim;\n }\n mergedType =\n Math.min(srcDim, dstDim) | REFERENCE_KIND | symbolTable.addType(\"java/lang/Object\");\n } else {\n // If srcType is any other type, merge(srcType, dstType) = TOP.\n mergedType = TOP;\n }\n } else if (dstType == NULL) {\n // If dstType is the NULL type, merge(srcType, dstType) = srcType, or TOP if srcType is not a\n // an array type or a reference type.\n mergedType =\n (srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND ? srcType : TOP;\n } else {\n // If dstType is any other type, merge(srcType, dstType) = TOP whatever srcType.\n mergedType = TOP;\n }\n if (mergedType != dstType) {\n dstTypes[dstIndex] = mergedType;\n return true;\n }\n return false;\n }\n\n // -----------------------------------------------------------------------------------------------\n // Frame output methods, to generate StackMapFrame attributes\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Makes the given {@link MethodWriter} visit the input frame of this {@link Frame}. The visit is\n * done with the {@link MethodWriter#visitFrameStart}, {@link MethodWriter#visitAbstractType} and\n * {@link MethodWriter#visitFrameEnd} methods.\n *\n * @param methodWriter the {@link MethodWriter} that should visit the input frame of this {@link\n * Frame}.\n */\n final void accept(final MethodWriter methodWriter) {\n // Compute the number of locals, ignoring TOP types that are just after a LONG or a DOUBLE, and\n // all trailing TOP types.\n int[] localTypes = inputLocals;\n int numLocal = 0;\n int numTrailingTop = 0;\n int i = 0;\n while (i < localTypes.length) {\n int localType = localTypes[i];\n i += (localType == LONG || localType == DOUBLE) ? 2 : 1;\n if (localType == TOP) {\n numTrailingTop++;\n } else {\n numLocal += numTrailingTop + 1;\n numTrailingTop = 0;\n }\n }\n // Compute the stack size, ignoring TOP types that are just after a LONG or a DOUBLE.\n int[] stackTypes = inputStack;\n int numStack = 0;\n i = 0;\n while (i < stackTypes.length) {\n int stackType = stackTypes[i];\n i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1;\n numStack++;\n }\n // Visit the frame and its content.\n int frameIndex = methodWriter.visitFrameStart(owner.bytecodeOffset, numLocal, numStack);\n i = 0;\n while (numLocal-- > 0) {\n int localType = localTypes[i];\n i += (localType == LONG || localType == DOUBLE) ? 2 : 1;\n methodWriter.visitAbstractType(frameIndex++, localType);\n }\n i = 0;\n while (numStack-- > 0) {\n int stackType = stackTypes[i];\n i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1;\n methodWriter.visitAbstractType(frameIndex++, stackType);\n }\n methodWriter.visitFrameEnd();\n }\n//\n// /**\n// * Put the given abstract type in the given ByteVector, using the JVMS verification_type_info\n// * format used in StackMapTable attributes.\n// *\n// * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n// * @param abstractType an abstract type, restricted to {@link Frame#CONSTANT_KIND}, {@link\n// * Frame#REFERENCE_KIND} or {@link Frame#UNINITIALIZED_KIND} types.\n// * @param output where the abstract type must be put.\n// * @see JVMS\n// * 4.7.4\n// */\n// static void putAbstractType(\n// final SymbolTable symbolTable, final int abstractType, final ByteVector output) {\n// int arrayDimensions = (abstractType & Frame.DIM_MASK) >> DIM_SHIFT;\n// if (arrayDimensions == 0) {\n// int typeValue = abstractType & VALUE_MASK;\n// switch (abstractType & KIND_MASK) {\n// case CONSTANT_KIND:\n// output.putByte(typeValue);\n// break;\n// case REFERENCE_KIND:\n// output\n// .putByte(ITEM_OBJECT)\n// .putShort(symbolTable.addConstantUtf8Reference(/*CONSTANT_CLASS_TAG*/ 7, symbolTable.typeTable[typeValue].value).index);\n// break;\n// case UNINITIALIZED_KIND:\n// output.putByte(ITEM_UNINITIALIZED).putShort((int) symbolTable.typeTable[typeValue].data);\n// break;\n// default:\n// throw new AssertionError();\n// }\n// } else {\n// // Case of an array type, we need to build its descriptor first.\n// StringBuilder typeDescriptor = new StringBuilder();\n// while (arrayDimensions-- > 0) {\n// typeDescriptor.append('[');\n// }\n// if ((abstractType & KIND_MASK) == REFERENCE_KIND) {\n// typeDescriptor\n// .append('L')\n// .append(symbolTable.typeTable[abstractType & VALUE_MASK].value)\n// .append(';');\n// } else {\n// switch (abstractType & VALUE_MASK) {\n// case Frame.ITEM_ASM_BOOLEAN:\n// typeDescriptor.append('Z');\n// break;\n// case Frame.ITEM_ASM_BYTE:\n// typeDescriptor.append('B');\n// break;\n// case Frame.ITEM_ASM_CHAR:\n// typeDescriptor.append('C');\n// break;\n// case Frame.ITEM_ASM_SHORT:\n// typeDescriptor.append('S');\n// break;\n// case Frame.ITEM_INTEGER:\n// typeDescriptor.append('I');\n// break;\n// case Frame.ITEM_FLOAT:\n// typeDescriptor.append('F');\n// break;\n// case Frame.ITEM_LONG:\n// typeDescriptor.append('J');\n// break;\n// case Frame.ITEM_DOUBLE:\n// typeDescriptor.append('D');\n// break;\n// default:\n// throw new AssertionError();\n// }\n// }\n// output\n// .putByte(ITEM_OBJECT)\n// .putShort(symbolTable.addConstantUtf8Reference(/*CONSTANT_CLASS_TAG*/ 7, typeDescriptor.toString()).index);\n// }\n// }\n}\n", "file_name": "Frame.java", "human_label": "Pop an abstract type from the output frame stack and return its value.", "level": "self_contained", "lineno": "617", "name": "pop", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[outputStackTop, outputStack, STACK_KIND, outputStackStart]\" }", "package": "com.alibaba.fastjson2.internal.asm", "project": "fastjson2-main" }, { "_id": "636767081a6d9265ec017989", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static boolean[] toPrimitive(final Boolean[] array){\n if (array == null) {\n return null;\n }\n else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result=new boolean[array.length];\n for (int i=0; i < array.length; i++) {\n result[i]=array[i].booleanValue();\n }\n return result;\n}\n", "docstring": "/** \n *

Converts an array of object Booleans to primitives.

This method returns null for a null input array.

\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n", "end_lineno": "3008", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

\n *\n *

This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

\n *\n *

#ThreadSafe#

\n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

\n *\n *

This method can be used to initialize:

\n *
\n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
\n *\n *

This method returns null for a null input array.

\n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

Shallow clones an array returning a typecast result and handling\n * null.

\n *\n *

The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

Produces a new array containing the elements between\n * the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n *

The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

\n *\n *
\n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new long array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new int array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new short array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new char array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new byte array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new double array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new float array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new boolean array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

Any multi-dimensional aspects of the arrays are ignored.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

\n *\n *

If the input array is null, 0 is returned.

\n *\n *
\n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
\n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

\n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

Reverses the order of the given array.

\n *\n *

There is no special handling for multi-dimensional arrays.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given object in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

Finds the index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given object within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the object is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

\n *\n *

The method returns false if a null array\n * is passed in.

\n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Characters to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Character to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive chars to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Longs to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Long to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive longs to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Integers to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Integer to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive ints to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Shorts to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Short to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive shorts to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Bytes to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Bytes to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive bytes to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Doubles to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Doubles to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive doubles to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Floats to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Floats to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive floats to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Booleans to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Booleans to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive booleans to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive longs is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive ints is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive chars is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive floats is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive longs is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive ints is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive chars is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive floats is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

\n *\n *
\n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Convert the given Boolean array to primitives. Return ArrayUtils.EMPTY_BOOLEAN_ARRAY for an empty array, return null for null array.", "level": "self_contained", "lineno": "2988", "name": "toPrimitive", "oracle_context": "{ \"apis\" : \"[booleanValue, ArrayUtils]\", \"classes\" : \"[boolean[], ArrayUtils]\", \"vars\" : \"[length, EMPTY_BOOLEAN_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "6367672d1a6d9265ec017c73", "all_context": "{ \"class_level\" : \"HashMap messages;\\nshouldPrintMessage(int timestamp,String message);\\nLogger();\\n\", \"repo_level\" : \"\" }", "class_name": "LoggerRateLimiter", "code": "public boolean shouldPrintMessage(int timestamp,String message){\n if (messages.containsKey(message)) {\n if (timestamp - messages.get(message) >= 10) {\n messages.put(message,timestamp);\n return true;\n }\n else {\n return false;\n }\n }\n else {\n messages.put(message,timestamp);\n return true;\n }\n}\n", "docstring": "/** \n * Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity. \n */\n", "end_lineno": "52", "file_content": "// Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds.\n\n// Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false.\n\n// It is possible that several messages arrive roughly at the same time.\n\n// Example:\n\n// Logger logger = new Logger();\n\n// // logging string \"foo\" at timestamp 1\n// logger.shouldPrintMessage(1, \"foo\"); returns true; \n\n// // logging string \"bar\" at timestamp 2\n// logger.shouldPrintMessage(2,\"bar\"); returns true;\n\n// // logging string \"foo\" at timestamp 3\n// logger.shouldPrintMessage(3,\"foo\"); returns false;\n\n// // logging string \"bar\" at timestamp 8\n// logger.shouldPrintMessage(8,\"bar\"); returns false;\n\n// // logging string \"foo\" at timestamp 10\n// logger.shouldPrintMessage(10,\"foo\"); returns false;\n\n// // logging string \"foo\" at timestamp 11\n// logger.shouldPrintMessage(11,\"foo\"); returns true;\n\npublic class LoggerRateLimiter {\n HashMap messages;\n\n /** Initialize your data structure here. */\n public Logger() {\n this.messages = new HashMap(); \n }\n \n /** Returns true if the message should be printed in the given timestamp, otherwise returns false.\n If this method returns false, the message will not be printed.\n The timestamp is in seconds granularity. */\n public boolean shouldPrintMessage(int timestamp, String message) {\n if(messages.containsKey(message)) {\n if(timestamp - messages.get(message) >= 10) {\n messages.put(message, timestamp);\n return true;\n } else {\n return false;\n }\n } else {\n messages.put(message, timestamp);\n return true;\n }\n }\n}\n\n/**\n * Your Logger object will be instantiated and called as such:\n * Logger obj = new Logger();\n * boolean param_1 = obj.shouldPrintMessage(timestamp,message);\n */\n", "file_name": "LoggerRateLimiter.java", "human_label": " If the message does not exist in the dict messages, or it exists but the timestamp (seconds) difference is bigger than 10, put the message and timestamp into messages and return true, otherwise return false.", "level": "self_contained", "lineno": "37", "name": "shouldPrintMessage", "oracle_context": "{ \"apis\" : \"[containsKey, get, put]\", \"classes\" : \"[]\", \"vars\" : \"[messages]\" }", "package": "", "project": "interviews-master" }, { "_id": "636766f81a6d9265ec01775c", "all_context": "{ \"class_level\" : \"import java.io.Serializable;\\nNull NULL;\\nlong serialVersionUID;\\nObjectUtils();\\nequals(Object object1,Object object2);\\nnotEqual(Object object1,Object object2);\\nhashCode(Object obj);\\nidentityToString(Object object);\\nidentityToString(StringBuffer buffer,Object object);\\ntoString(Object obj);\\ntoString(Object obj,String nullStr);\\nmin(Comparable c1,Comparable c2);\\nmax(Comparable c1,Comparable c2);\\ncompare(Comparable c1,Comparable c2);\\ncompare(Comparable c1,Comparable c2,boolean nullGreater);\\nNull();\\nreadResolve();\\ndefaultIfNull(Object object,Object defaultValue);\\n\", \"repo_level\" : \"\" }", "class_name": "ObjectUtils", "code": "public static String toString(Object obj){\n return obj == null ? \"\" : obj.toString();\n}\n", "docstring": "/** \n *

Gets the toString of an Object returning an empty string (\"\") if null input.

 ObjectUtils.toString(null)         = \"\" ObjectUtils.toString(\"\")           = \"\" ObjectUtils.toString(\"bat\")        = \"bat\" ObjectUtils.toString(Boolean.TRUE) = \"true\" 
\n * @see StringUtils#defaultString(String)\n * @see String#valueOf(Object)\n * @param obj the Object to toString, may be null\n * @return the passed in Object's toString, or nullStr if null input\n * @since 2.0\n */\n", "end_lineno": "231", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.io.Serializable;\n\n/**\n *

Operations on Object.

\n *\n *

This class tries to handle null input gracefully.\n * An exception will generally not be thrown for a null input.\n * Each method documents its behaviour in more detail.

\n *\n *

#ThreadSafe#

\n * @author Apache Software Foundation\n * @author Nissim Karpenstein\n * @author Janek Bogucki\n * @author Daniel L. Rall\n * @author Gary Gregory\n * @author Mario Winterer\n * @author David J. M. Karlsen\n * @since 1.0\n * @version $Id: ObjectUtils.java 1057434 2011-01-11 01:27:37Z niallp $\n */\npublic class ObjectUtils {\n /**\n *

Singleton used as a null placeholder where\n * null has another meaning.

\n *\n *

For example, in a HashMap the\n * {@link java.util.HashMap#get(Object)} method returns\n * null if the Map contains\n * null or if there is no matching key. The\n * Null placeholder can be used to distinguish between\n * these two cases.

\n *\n *

Another example is Hashtable, where null\n * cannot be stored.

\n *\n *

This instance is Serializable.

\n */\n public static final Null NULL = new Null();\n\n /**\n *

ObjectUtils instances should NOT be constructed in\n * standard programming. Instead, the class should be used as\n * ObjectUtils.defaultIfNull(\"a\",\"b\");.

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public ObjectUtils() {\n super();\n }\n // Defaulting\n //-----------------------------------------------------------------------\n\n /**\n *

Returns a default value if the object passed is\n * null.

\n *\n *
\n     * ObjectUtils.defaultIfNull(null, null)      = null\n     * ObjectUtils.defaultIfNull(null, \"\")        = \"\"\n     * ObjectUtils.defaultIfNull(null, \"zz\")      = \"zz\"\n     * ObjectUtils.defaultIfNull(\"abc\", *)        = \"abc\"\n     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE\n     * 
\n *\n * @param object the Object to test, may be null\n * @param defaultValue the default value to return, may be null\n * @return object if it is not null, defaultValue otherwise\n */\n public static Object defaultIfNull(Object object, Object defaultValue) {\n return object != null ? object : defaultValue;\n }\n\n /**\n *

Compares two objects for equality, where either one or both\n * objects may be null.

\n *\n *
\n     * ObjectUtils.equals(null, null)                  = true\n     * ObjectUtils.equals(null, \"\")                    = false\n     * ObjectUtils.equals(\"\", null)                    = false\n     * ObjectUtils.equals(\"\", \"\")                      = true\n     * ObjectUtils.equals(Boolean.TRUE, null)          = false\n     * ObjectUtils.equals(Boolean.TRUE, \"true\")        = false\n     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true\n     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false\n     * 
\n *\n * @param object1 the first object, may be null\n * @param object2 the second object, may be null\n * @return true if the values of both objects are the same\n */\n public static boolean equals(Object object1, Object object2) {\n if (object1 == object2) {\n return true;\n }\n if ((object1 == null) || (object2 == null)) {\n return false;\n }\n return object1.equals(object2);\n }\n\n /**\n *

Compares two objects for inequality, where either one or both\n * objects may be null.

\n *\n *
\n     * ObjectUtils.notEqual(null, null)                  = false\n     * ObjectUtils.notEqual(null, \"\")                    = true\n     * ObjectUtils.notEqual(\"\", null)                    = true\n     * ObjectUtils.notEqual(\"\", \"\")                      = false\n     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true\n     * ObjectUtils.notEqual(Boolean.TRUE, \"true\")        = true\n     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false\n     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true\n     * 
\n *\n * @param object1 the first object, may be null\n * @param object2 the second object, may be null\n * @return false if the values of both objects are the same\n * @since 2.6\n */\n public static boolean notEqual(Object object1, Object object2) {\n return ObjectUtils.equals(object1, object2) == false;\n }\n\n /**\n *

Gets the hash code of an object returning zero when the\n * object is null.

\n *\n *
\n     * ObjectUtils.hashCode(null)   = 0\n     * ObjectUtils.hashCode(obj)    = obj.hashCode()\n     * 
\n *\n * @param obj the object to obtain the hash code of, may be null\n * @return the hash code of the object, or zero if null\n * @since 2.1\n */\n public static int hashCode(Object obj) {\n return (obj == null) ? 0 : obj.hashCode();\n }\n // Identity ToString\n //-----------------------------------------------------------------------\n\n /**\n *

Gets the toString that would be produced by Object\n * if a class did not override toString itself. null\n * will return null.

\n *\n *
\n     * ObjectUtils.identityToString(null)         = null\n     * ObjectUtils.identityToString(\"\")           = \"java.lang.String@1e23\"\n     * ObjectUtils.identityToString(Boolean.TRUE) = \"java.lang.Boolean@7fa\"\n     * 
\n *\n * @param object the object to create a toString for, may be\n * null\n * @return the default toString text, or null if\n * null passed in\n */\n public static String identityToString(Object object) {\n if (object == null) {\n return null;\n }\n StringBuffer buffer = new StringBuffer();\n identityToString(buffer, object);\n return buffer.toString();\n }\n\n /**\n *

Appends the toString that would be produced by Object\n * if a class did not override toString itself. null\n * will throw a NullPointerException for either of the two parameters.

\n *\n *
\n     * ObjectUtils.identityToString(buf, \"\")            = buf.append(\"java.lang.String@1e23\"\n     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append(\"java.lang.Boolean@7fa\"\n     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append(\"java.lang.Boolean@7fa\")\n     * 
\n *\n * @param buffer the buffer to append to\n * @param object the object to create a toString for\n * @since 2.4\n */\n public static void identityToString(StringBuffer buffer, Object object) {\n if (object == null) {\n throw new NullPointerException(\"Cannot get the toString of a null identity\");\n }\n buffer.append(object.getClass().getName()).append('@').append(Integer.toHexString(System.identityHashCode(object)));\n }\n // ToString\n //-----------------------------------------------------------------------\n\n /**\n *

Gets the toString of an Object returning\n * an empty string (\"\") if null input.

\n *\n *
\n     * ObjectUtils.toString(null)         = \"\"\n     * ObjectUtils.toString(\"\")           = \"\"\n     * ObjectUtils.toString(\"bat\")        = \"bat\"\n     * ObjectUtils.toString(Boolean.TRUE) = \"true\"\n     * 
\n *\n * @see StringUtils#defaultString(String)\n * @see String#valueOf(Object)\n * @param obj the Object to toString, may be null\n * @return the passed in Object's toString, or nullStr if null input\n * @since 2.0\n */\n public static String toString(Object obj) {\n return obj == null ? \"\" : obj.toString();\n }\n\n /**\n *

Gets the toString of an Object returning\n * a specified text if null input.

\n *\n *
\n     * ObjectUtils.toString(null, null)           = null\n     * ObjectUtils.toString(null, \"null\")         = \"null\"\n     * ObjectUtils.toString(\"\", \"null\")           = \"\"\n     * ObjectUtils.toString(\"bat\", \"null\")        = \"bat\"\n     * ObjectUtils.toString(Boolean.TRUE, \"null\") = \"true\"\n     * 
\n *\n * @see StringUtils#defaultString(String, String)\n * @see String#valueOf(Object)\n * @param obj the Object to toString, may be null\n * @param nullStr the String to return if null input, may be null\n * @return the passed in Object's toString, or nullStr if null input\n * @since 2.0\n */\n public static String toString(Object obj, String nullStr) {\n return obj == null ? nullStr : obj.toString();\n }\n // Min/Max\n //-----------------------------------------------------------------------\n\n /**\n * Null safe comparison of Comparables.\n *\n * @param c1 the first comparable, may be null\n * @param c2 the second comparable, may be null\n * @return\n *
    \n *
  • If both objects are non-null and unequal, the lesser object.\n *
  • If both objects are non-null and equal, c1.\n *
  • If one of the comparables is null, the non-null object.\n *
  • If both the comparables are null, null is returned.\n *
\n */\n public static Object min(Comparable c1, Comparable c2) {\n return (compare(c1, c2, true) <= 0 ? c1 : c2);\n }\n\n /**\n * Null safe comparison of Comparables.\n *\n * @param c1 the first comparable, may be null\n * @param c2 the second comparable, may be null\n * @return\n *
    \n *
  • If both objects are non-null and unequal, the greater object.\n *
  • If both objects are non-null and equal, c1.\n *
  • If one of the comparables is null, the non-null object.\n *
  • If both the comparables are null, null is returned.\n *
\n */\n public static Object max(Comparable c1, Comparable c2) {\n return (compare(c1, c2, false) >= 0 ? c1 : c2);\n }\n\n /**\n * Null safe comparison of Comparables.\n * {@code null} is assumed to be less than a non-{@code null} value.\n *\n * @param c1 the first comparable, may be null\n * @param c2 the second comparable, may be null\n * @return a negative value if c1 < c2, zero if c1 = c2\n * and a positive value if c1 > c2\n * @since 2.6\n */\n public static int compare(Comparable c1, Comparable c2) {\n return compare(c1, c2, false);\n }\n\n /**\n * Null safe comparison of Comparables.\n *\n * @param c1 the first comparable, may be null\n * @param c2 the second comparable, may be null\n * @param nullGreater if true null is considered greater\n * than a Non-null value or if false null is\n * considered less than a Non-null value\n * @return a negative value if c1 < c2, zero if c1 = c2\n * and a positive value if c1 > c2\n * @see java.util.Comparator#compare(Object, Object)\n * @since 2.6\n */\n public static int compare(Comparable c1, Comparable c2, boolean nullGreater) {\n if (c1 == c2) {\n return 0;\n } else if (c1 == null) {\n return (nullGreater ? 1 : -1);\n } else if (c2 == null) {\n return (nullGreater ? -1 : 1);\n }\n return c1.compareTo(c2);\n }\n // Null\n //-----------------------------------------------------------------------\n\n /**\n *

Class used as a null placeholder where null\n * has another meaning.

\n *\n *

For example, in a HashMap the\n * {@link java.util.HashMap#get(Object)} method returns\n * null if the Map contains\n * null or if there is no matching key. The\n * Null placeholder can be used to distinguish between\n * these two cases.

\n *\n *

Another example is Hashtable, where null\n * cannot be stored.

\n */\n public static class Null implements Serializable {\n /**\n * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0\n *\n * @see Serializable\n */\n private static final long serialVersionUID = 7092611880189329093L;\n\n /**\n * Restricted constructor - singleton.\n */\n Null() {\n super();\n }\n\n /**\n *

Ensure singleton.

\n *\n * @return the singleton value\n */\n private Object readResolve() {\n return ObjectUtils.NULL;\n }\n }\n}\n", "file_name": "ObjectUtils.java", "human_label": "Return the string representation of the given object, return an empty string if the object is null.", "level": "self_contained", "lineno": "212", "name": "toString", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "6367667f1a6d9265ec017457", "all_context": "{ \"class_level\" : \"import java.io.UnsupportedEncodingException;\\nimport java.net.URI;\\nimport java.net.URLDecoder;\\nimport java.nio.Buffer;\\nimport java.nio.ByteBuffer;\\nimport java.nio.CharBuffer;\\nimport java.nio.charset.Charset;\\nimport java.nio.charset.StandardCharsets;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collections;\\nimport java.util.HashMap;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Map;\\nchar[] HEX_DIGITS;\\nString[] SCHEME;\\nString[] UNRESERVED;\\nString[] SUB_DELIMS;\\nboolean[][] ENCODING_TABLES;\\nCharset UTF_8_CHARSET;\\nPathSegmentImpl EMPTY_PATH_SEGMENT;\\nString path;\\nMap matrixParameters;\\nint[] HEX_TABLE;\\nUriComponent();\\nvalidate(String s,Type t,boolean template);\\nvalid(String s,Type t);\\nvalid(String s,Type t,boolean template);\\n_valid(String s,Type t,boolean template);\\ncontextualEncode(String s,Type t);\\ncontextualEncode(String s,Type t,boolean template);\\nencode(String s,Type t);\\nencode(String s,Type t,boolean template);\\nencodeTemplateNames(String s);\\n_encode(String s,Type t,boolean template,boolean contextualEncode);\\nappendPercentEncodedOctet(StringBuilder sb,int b);\\nappendUTF8EncodedCharacter(StringBuilder sb,char c);\\ncreatingEncodingTables();\\ncreatingEncodingTable(List allowed);\\ndecode(String s,Type t);\\ndecodeQuery(URI u,boolean decode);\\ndecodeQuery(String q,boolean decode);\\ndecodeQueryParam(Map params,String param,boolean decode);\\nPathSegmentImpl(String path,boolean decode);\\nPathSegmentImpl(String path,boolean decode,Map matrixParameters);\\ngetPath();\\ngetMatrixParameters();\\ndecodePath(URI u,boolean decode);\\ndecodePath(String path,boolean decode);\\ndecodePathSegment(List segments,String segment,boolean decode);\\ndecodeMatrix(String pathSegment,boolean decode);\\ndecodeMatrixParam(Map params,String param,boolean decode);\\ndecode(String s,int n);\\ndecodeQueryParam(String s,int n);\\ndecodeHost(String s,int n);\\ndecodePercentEncodedOctets(String s,int i,ByteBuffer bb);\\ndecodeOctets(int i,ByteBuffer bb,StringBuilder sb);\\ndecodeHex(String s,int i);\\ncreateHexTable();\\ndecodeHex(char c);\\nisHexCharacter(char c);\\nvalidate(String s,Type t);\\n\", \"repo_level\" : \"\" }", "class_name": "UriComponent", "code": "private static int decodeOctets(int i,ByteBuffer bb,StringBuilder sb){\n if (bb.limit() == 1 && (bb.get(0) & 0xFF) < 0x80) {\n sb.append((char)bb.get(0));\n return i + 2;\n }\n else {\n CharBuffer cb=UTF_8_CHARSET.decode(bb);\n sb.append(cb);\n return i + bb.limit() * 3 - 1;\n }\n}\n", "docstring": "/** \n * Decodes octets to characters using the UTF-8 decoding and appends the characters to a StringBuffer.\n * @return the index to the next unchecked character in the string to decode\n */\n", "end_lineno": "816", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * Copyright (c) 2010-2018 Oracle and/or its affiliates. All rights reserved.\n *\n * The contents of this file are subject to the terms of either the GNU\n * General Public License Version 2 only (\"GPL\") or the Common Development\n * and Distribution License(\"CDDL\") (collectively, the \"License\"). You\n * may not use this file except in compliance with the License. You can\n * obtain a copy of the License at\n * http://glassfish.java.net/public/CDDL+GPL_1_1.html\n * or packager/legal/LICENSE.txt. See the License for the specific\n * language governing permissions and limitations under the License.\n *\n * When distributing the software, include this License Header Notice in each\n * file and include the License file at packager/legal/LICENSE.txt.\n *\n * GPL Classpath Exception:\n * Oracle designates this particular file as subject to the \"Classpath\"\n * exception as provided by Oracle in the GPL Version 2 section of the License\n * file that accompanied this code.\n *\n * Modifications:\n * If applicable, add the following below the License Header, with the fields\n * enclosed by brackets [] replaced by your own identifying information:\n * \"Portions Copyright [year] [name of copyright owner]\"\n *\n * Contributor(s):\n * If you wish your version of this file to be governed by only the CDDL or\n * only the GPL Version 2, indicate your decision by adding \"[Contributor]\n * elects to include this software in this distribution under the [CDDL or GPL\n * Version 2] license.\" If you don't indicate a single choice of license, a\n * recipient has the option to distribute your version of this file under\n * either the CDDL, the GPL Version 2 or to extend the choice of license to\n * its licensees as provided above. However, if you add GPL Version 2 code\n * and therefore, elected the GPL Version 2 license, then the option applies\n * only if the new code is made subject to such option by the copyright\n * holder.\n */\npackage org.atmosphere.util.uri;\n\nimport java.io.UnsupportedEncodingException;\nimport java.net.URI;\nimport java.net.URLDecoder;\nimport java.nio.Buffer;\nimport java.nio.ByteBuffer;\nimport java.nio.CharBuffer;\nimport java.nio.charset.Charset;\nimport java.nio.charset.StandardCharsets;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Utility class for validating, encoding and decoding components\n * of a URI.\n *\n * @author Paul.Sandoz@Sun.Com\n */\npublic class UriComponent {\n\n // TODO rewrite to use masks and not lookup tables\n /**\n * The URI component type.\n */\n public enum Type {\n\n /**\n * ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\" characters\n */\n UNRESERVED,\n /**\n * The URI scheme component type.\n */\n SCHEME,\n /**\n * The URI authority component type.\n */\n AUTHORITY,\n /**\n * The URI user info component type.\n */\n USER_INFO,\n /**\n * The URI host component type.\n */\n HOST,\n /**\n * The URI port component type.\n */\n PORT,\n /**\n * The URI path component type.\n */\n PATH,\n /**\n * The URI path component type that is a path segment.\n */\n PATH_SEGMENT,\n /**\n * The URI path component type that is a matrix parameter.\n */\n MATRIX_PARAM,\n /**\n * The URI query component type.\n */\n QUERY,\n /**\n * The URI query component type that is a query parameter.\n */\n QUERY_PARAM,\n /**\n * The URI fragment component type.\n */\n FRAGMENT,\n }\n\n private UriComponent() {\n }\n\n /**\n * Validates the legal characters of a percent-encoded string that \n * represents a URI component type.\n *\n * @param s the encoded string.\n * @param t the URI compontent type identifying the legal characters.\n * @throws IllegalArgumentException if the encoded string contains illegal\n * characters.\n */\n public static void validate(String s, Type t) {\n validate(s, t, false);\n }\n\n /**\n * Validates the legal characters of a percent-encoded string that \n * represents a URI component type.\n *\n * @param s the encoded string.\n * @param t the URI compontent type identifying the legal characters.\n * @param template true if the encoded string contains URI template variables\n * @throws IllegalArgumentException if the encoded string contains illegal\n * characters.\n */\n public static void validate(String s, Type t, boolean template) {\n int i = _valid(s, t, template);\n if (i > -1) // TODO localize\n {\n throw new IllegalArgumentException(\"The string '\" + s +\n \"' for the URI component \" + t +\n \" contains an invalid character, '\" + s.charAt(i) + \"', at index \" + i);\n }\n }\n\n /**\n * Validates the legal characters of a percent-encoded string that \n * represents a URI component type.\n *\n * @param s the encoded string.\n * @param t the URI compontent type identifying the legal characters.\n * @return true if the encoded string is valid, otherwise false.\n */\n public static boolean valid(String s, Type t) {\n return valid(s, t, false);\n }\n\n /**\n * Validates the legal characters of a percent-encoded string that \n * represents a URI component type.\n *\n * @param s the encoded string.\n * @param t the URI compontent type identifying the legal characters.\n * @param template true if the encoded string contains URI template variables\n * @return true if the encoded string is valid, otherwise false.\n */\n public static boolean valid(String s, Type t, boolean template) {\n return _valid(s, t, template) == -1;\n }\n\n private static int _valid(String s, Type t, boolean template) {\n boolean[] table = ENCODING_TABLES[t.ordinal()];\n\n for (int i = 0; i < s.length(); i++) {\n final char c = s.charAt(i);\n if (c >= 0x80 || (c != '%' && !table[c])) {\n if (!template || (c != '{' && c != '}')) {\n return i;\n }\n }\n }\n return -1;\n }\n\n /**\n * Contextually encodes the characters of string that are either non-ASCII\n * characters or are ASCII characters that must be percent-encoded using the\n * UTF-8 encoding. Percent-encoded characters will be recognized and not\n * double encoded.\n *\n * @param s the string to be encoded.\n * @param t the URI compontent type identifying the ASCII characters that \n * must be percent-encoded.\n * @return the encoded string.\n */\n public static String contextualEncode(String s, Type t) {\n return _encode(s, t, false, true);\n }\n\n /**\n * Contextually encodes the characters of string that are either non-ASCII\n * characters or are ASCII characters that must be percent-encoded using the\n * UTF-8 encoding. Percent-encoded characters will be recognized and not\n * double encoded.\n *\n * @param s the string to be encoded.\n * @param t the URI compontent type identifying the ASCII characters that \n * must be percent-encoded.\n * @param template true if the encoded string contains URI template variables\n * @return the encoded string.\n */\n public static String contextualEncode(String s, Type t, boolean template) {\n return _encode(s, t, template, true);\n }\n\n /**\n * Encodes the characters of string that are either non-ASCII characters \n * or are ASCII characters that must be percent-encoded using the \n * UTF-8 encoding.\n *\n * @param s the string to be encoded.\n * @param t the URI compontent type identifying the ASCII characters that \n * must be percent-encoded.\n * @return the encoded string.\n */\n public static String encode(String s, Type t) {\n return _encode(s, t, false, false);\n }\n\n /**\n * Encodes the characters of string that are either non-ASCII characters \n * or are ASCII characters that must be percent-encoded using the \n * UTF-8 encoding.\n *\n * @param s the string to be encoded.\n * @param t the URI compontent type identifying the ASCII characters that \n * must be percent-encoded.\n * @param template true if the encoded string contains URI template variables\n * @return the encoded string.\n */\n public static String encode(String s, Type t, boolean template) {\n return _encode(s, t, template, false);\n }\n\n /**\n * Encodes a string with template parameters names present, specifically the\n * characters '{' and '}' will be percent-encoded.\n * \n * @param s the string with zero or more template parameters names\n * @return the string with encoded template parameters names.\n */\n public static String encodeTemplateNames(String s) {\n int i = s.indexOf('{');\n if (i != -1)\n s = s.replace(\"{\", \"%7B\");\n i = s.indexOf('}');\n if (i != -1)\n s = s.replace(\"}\", \"%7D\");\n\n return s;\n }\n\n private static String _encode(String s, Type t, boolean template, boolean contextualEncode) {\n final boolean[] table = ENCODING_TABLES[t.ordinal()];\n\n StringBuilder sb = null;\n for (int i = 0; i < s.length(); i++) {\n final char c = s.charAt(i);\n if (c < 0x80 && table[c]) {\n if (sb != null) sb.append(c);\n } else {\n if (template && (c == '{' || c == '}')) {\n if (sb != null) sb.append(c);\n continue;\n } else if (contextualEncode) {\n if (c == '%' && i + 2 < s.length()) {\n if (isHexCharacter(s.charAt(i + 1)) &&\n isHexCharacter(s.charAt(i + 2))) {\n if (sb != null)\n sb.append('%').append(s.charAt(i + 1)).append(s.charAt(i + 2));\n i += 2;\n continue;\n }\n }\n }\n\n if (sb == null) {\n sb = new StringBuilder();\n sb.append(s, 0, i);\n }\n\n if (c < 0x80) {\n if (c == ' ' && (t == Type.QUERY_PARAM)) {\n sb.append('+');\n } else {\n appendPercentEncodedOctet(sb, c);\n }\n } else {\n appendUTF8EncodedCharacter(sb, c);\n }\n }\n }\n\n return (sb == null) ? s : sb.toString();\n }\n private final static char[] HEX_DIGITS = {\n '0', '1', '2', '3', '4', '5', '6', '7',\n '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'\n };\n\n private static void appendPercentEncodedOctet(StringBuilder sb, int b) {\n sb.append('%');\n sb.append(HEX_DIGITS[b >> 4]);\n sb.append(HEX_DIGITS[b & 0x0F]);\n }\n\n private static void appendUTF8EncodedCharacter(StringBuilder sb, char c) {\n final ByteBuffer bb = UTF_8_CHARSET.encode(\"\" + c);\n\n while (bb.hasRemaining()) {\n appendPercentEncodedOctet(sb, bb.get() & 0xFF);\n }\n }\n private static final String[] SCHEME = {\"0-9\", \"A-Z\", \"a-z\", \"+\", \"-\", \".\"};\n private static final String[] UNRESERVED = {\"0-9\", \"A-Z\", \"a-z\", \"-\", \".\", \"_\", \"~\"};\n private static final String[] SUB_DELIMS = {\"!\", \"$\", \"&\", \"'\", \"(\", \")\", \"*\", \"+\", \",\", \";\", \"=\"};\n private static final boolean[][] ENCODING_TABLES = creatingEncodingTables();\n\n private static boolean[][] creatingEncodingTables() {\n boolean[][] tables = new boolean[Type.values().length][];\n\n List l = new ArrayList<>(Arrays.asList(SCHEME));\n tables[Type.SCHEME.ordinal()] = creatingEncodingTable(l);\n\n l.clear();\n\n l.addAll(Arrays.asList(UNRESERVED));\n tables[Type.UNRESERVED.ordinal()] = creatingEncodingTable(l);\n\n l.addAll(Arrays.asList(SUB_DELIMS));\n\n tables[Type.HOST.ordinal()] = creatingEncodingTable(l);\n\n tables[Type.PORT.ordinal()] = creatingEncodingTable(Collections.singletonList(\"0-9\"));\n\n l.add(\":\");\n\n tables[Type.USER_INFO.ordinal()] = creatingEncodingTable(l);\n\n l.add(\"@\");\n\n tables[Type.AUTHORITY.ordinal()] = creatingEncodingTable(l);\n\n tables[Type.PATH_SEGMENT.ordinal()] = creatingEncodingTable(l);\n tables[Type.PATH_SEGMENT.ordinal()][';'] = false;\n\n tables[Type.MATRIX_PARAM.ordinal()] = tables[Type.PATH_SEGMENT.ordinal()].clone();\n tables[Type.MATRIX_PARAM.ordinal()]['='] = false;\n\n l.add(\"/\");\n\n tables[Type.PATH.ordinal()] = creatingEncodingTable(l);\n\n l.add(\"?\");\n\n tables[Type.QUERY.ordinal()] = creatingEncodingTable(l);\n\n tables[Type.FRAGMENT.ordinal()] = tables[Type.QUERY.ordinal()];\n\n tables[Type.QUERY_PARAM.ordinal()] = creatingEncodingTable(l);\n tables[Type.QUERY_PARAM.ordinal()]['='] = false;\n tables[Type.QUERY_PARAM.ordinal()]['+'] = false;\n tables[Type.QUERY_PARAM.ordinal()]['&'] = false;\n\n return tables;\n }\n\n private static boolean[] creatingEncodingTable(List allowed) {\n boolean[] table = new boolean[0x80];\n for (String range : allowed) {\n if (range.length() == 1) {\n table[range.charAt(0)] = true;\n } else if (range.length() == 3 && range.charAt(1) == '-') {\n for (int i = range.charAt(0); i <= range.charAt(2); i++) {\n table[i] = true;\n }\n }\n }\n\n return table;\n }\n private static final Charset UTF_8_CHARSET = StandardCharsets.UTF_8;\n\n /**\n * Decodes characters of a string that are percent-encoded octets using \n * UTF-8 decoding (if needed).\n *

\n * It is assumed that the string is valid according to an (unspecified) URI \n * component type. If a sequence of contiguous percent-encoded octets is \n * not a valid UTF-8 character then the octets are replaced with '\\uFFFD'.\n *

\n * If the URI component is of type HOST then any \"%\" found between \"[]\" is \n * left alone. It is an IPv6 literal with a scope_id.\n *

\n * If the URI component is of type QUERY_PARAM then any \"+\" is decoded as\n * as ' '.\n *

\n * @param s the string to be decoded.\n * @param t the URI component type, may be null.\n * @return the decoded string.\n * @throws IllegalArgumentException if a malformed percent-encoded octet is\n * detected\n */\n public static String decode(String s, Type t) {\n if (s == null) {\n throw new IllegalArgumentException();\n }\n\n final int n = s.length();\n if (n == 0) {\n return s;\n }\n\n // If there are no percent-escaped octets\n if (s.indexOf('%') < 0) {\n // If there are no '+' characters for query param\n if (t == Type.QUERY_PARAM) {\n if (s.indexOf('+') < 0) {\n return s;\n }\n } else {\n return s;\n }\n } else {\n // Malformed percent-escaped octet at the end\n if (n < 2) // TODO localize\n {\n throw new IllegalArgumentException(\"Malformed percent-encoded octet at index 1\");\n }\n\n // Malformed percent-escaped octet at the end\n if (s.charAt(n - 2) == '%') // TODO localize\n {\n throw new IllegalArgumentException(\"Malformed percent-encoded octet at index \" + (n - 2));\n }\n }\n\n if (t == null)\n return decode(s, n);\n \n switch (t) {\n case HOST :\n return decodeHost(s, n);\n case QUERY_PARAM :\n return decodeQueryParam(s, n);\n default :\n return decode(s, n);\n }\n }\n\n /**\n * Decode the query component of a URI.\n * \n * @param u the URI.\n * @param decode true if the query parameters of the query component\n * should be in decoded form.\n * @return the multivalued map of query parameters.\n */\n public static Map decodeQuery(URI u, boolean decode) {\n return decodeQuery(u.getRawQuery(), decode);\n }\n\n /**\n * Decode the query component of a URI.\n * \n * @param q the query component in encoded form.\n * @param decode true of the query parameters of the query component\n * should be in decoded form.\n * @return the multivalued map of query parameters.\n */\n public static Map decodeQuery(String q, boolean decode) {\n Map queryParameters = new HashMap<>();\n\n if (q == null || q.length() == 0) {\n return queryParameters;\n }\n\n int s = 0, e;\n do {\n e = q.indexOf('&', s);\n\n if (e == -1) {\n decodeQueryParam(queryParameters, q.substring(s), decode);\n } else if (e > s) {\n decodeQueryParam(queryParameters, q.substring(s, e), decode);\n }\n s = e + 1;\n } while (s > 0 && s < q.length());\n\n return queryParameters;\n }\n\n private static void decodeQueryParam(Map params,\n String param, boolean decode) {\n try {\n int equals = param.indexOf('=');\n if (equals > 0) {\n params.put(\n URLDecoder.decode(param.substring(0, equals), \"UTF-8\"),\n (decode) ? URLDecoder.decode(param.substring(equals + 1), \"UTF-8\") : param.substring(equals + 1));\n } else if (equals == 0) {\n // no key declared, ignore\n } else if (param.length() > 0) {\n params.put(\n URLDecoder.decode(param, \"UTF-8\"),\n \"\");\n }\n } catch (UnsupportedEncodingException ex) {\n // This should never occur\n throw new IllegalArgumentException(ex);\n }\n }\n\n private static final class PathSegmentImpl {\n\n private static final PathSegmentImpl EMPTY_PATH_SEGMENT = new PathSegmentImpl(\"\", false);\n private final String path;\n private final Map matrixParameters;\n\n PathSegmentImpl(String path, boolean decode) {\n this(path, decode, new HashMap ());\n }\n\n PathSegmentImpl(String path, boolean decode, Map matrixParameters) {\n this.path = (decode) ? UriComponent.decode(path, UriComponent.Type.PATH_SEGMENT) : path;\n this.matrixParameters = matrixParameters;\n }\n\n public String getPath() {\n return path;\n }\n\n public Map getMatrixParameters() {\n return matrixParameters;\n }\n }\n\n /**\n * Decode the path component of a URI as path segments.\n *\n * @param u the URI. If the path component is an absolute path component\n * then the leading '/' is ignored and is not considered a delimiator\n * of a path segment.\n * @param decode true if the path segments of the path component\n * should be in decoded form.\n * @return the list of path segments.\n */\n public static List decodePath(URI u, boolean decode) {\n String rawPath = u.getRawPath();\n if (rawPath != null && rawPath.length() > 0 && rawPath.charAt(0) == '/') {\n rawPath = rawPath.substring(1);\n }\n return decodePath(rawPath, decode);\n }\n\n /**\n * Decode the path component of a URI as path segments.\n *

\n * Any '/' character in the path is considered to be a deliminator\n * between two path segments. Thus if the path is '/' then the path segment\n * list will contain two empty path segments. If the path is \"//\" then\n * the path segment list will contain three empty path segments. If the path\n * is \"/a/\" the path segment list will consist of the following path\n * segments in order: \"\", \"a\" and \"\".\n *\n * @param path the path component in encoded form.\n * @param decode true if the path segments of the path component\n * should be in decoded form.\n * @return the list of path segments.\n */\n public static List decodePath(String path, boolean decode) {\n List segments = new LinkedList<>();\n\n if (path == null) {\n return segments;\n }\n\n int s;\n int e = -1;\n do {\n s = e + 1;\n e = path.indexOf('/', s);\n\n if (e > s) {\n decodePathSegment(segments, path.substring(s, e), decode);\n } else if (e == s) {\n segments.add(PathSegmentImpl.EMPTY_PATH_SEGMENT);\n }\n } while (e != -1);\n if (s < path.length()) {\n decodePathSegment(segments, path.substring(s), decode);\n } else {\n segments.add(PathSegmentImpl.EMPTY_PATH_SEGMENT);\n }\n return segments;\n }\n\n public static void decodePathSegment(List segments, String segment, boolean decode) {\n int colon = segment.indexOf(';');\n if (colon != -1) {\n segments.add(new PathSegmentImpl(\n (colon == 0) ? \"\" : segment.substring(0, colon),\n decode,\n decodeMatrix(segment, decode)));\n } else {\n segments.add(new PathSegmentImpl(\n segment,\n decode));\n }\n }\n\n /**\n * Decode the matrix component of a URI path segment.\n *\n * @param pathSegment the path segment component in encoded form.\n * @param decode true if the matrix parameters of the path segment component\n * should be in decoded form.\n * @return the multivalued map of matrix parameters.\n */\n public static Map decodeMatrix(String pathSegment, boolean decode) {\n Map matrixMap = new HashMap<>();\n\n // Skip over path segment\n int s = pathSegment.indexOf(';') + 1;\n if (s == 0 || s == pathSegment.length()) {\n return matrixMap;\n }\n\n int e;\n do {\n e = pathSegment.indexOf(';', s);\n\n if (e == -1) {\n decodeMatrixParam(matrixMap, pathSegment.substring(s), decode);\n } else if (e > s) {\n decodeMatrixParam(matrixMap, pathSegment.substring(s, e), decode);\n }\n s = e + 1;\n } while (s > 0 && s < pathSegment.length());\n\n return matrixMap;\n }\n\n private static void decodeMatrixParam(Map params,\n String param, boolean decode) {\n int equals = param.indexOf('=');\n if (equals > 0) {\n params.put(\n UriComponent.decode(param.substring(0, equals), UriComponent.Type.MATRIX_PARAM),\n (decode) ? UriComponent.decode(param.substring(equals + 1), UriComponent.Type.MATRIX_PARAM) : param.substring(equals + 1));\n } else if (equals == 0) {\n // no key declared, ignore\n } else if (param.length() > 0) {\n params.put(\n UriComponent.decode(param, UriComponent.Type.MATRIX_PARAM),\n \"\");\n }\n }\n\n private static String decode(String s, int n) {\n final StringBuilder sb = new StringBuilder(n);\n ByteBuffer bb = null;\n\n for (int i = 0; i < n;) {\n final char c = s.charAt(i++);\n if (c != '%') {\n sb.append(c);\n } else {\n bb = decodePercentEncodedOctets(s, i, bb);\n i = decodeOctets(i, bb, sb);\n }\n }\n\n return sb.toString();\n }\n\n private static String decodeQueryParam(String s, int n) {\n final StringBuilder sb = new StringBuilder(n);\n ByteBuffer bb = null;\n\n for (int i = 0; i < n;) {\n final char c = s.charAt(i++);\n if (c != '%') {\n if (c != '+')\n sb.append(c);\n else\n sb.append(' ');\n } else {\n bb = decodePercentEncodedOctets(s, i, bb);\n i = decodeOctets(i, bb, sb);\n }\n }\n\n return sb.toString();\n }\n\n private static String decodeHost(String s, int n) {\n final StringBuilder sb = new StringBuilder(n);\n ByteBuffer bb = null;\n\n boolean betweenBrackets = false;\n for (int i = 0; i < n;) {\n final char c = s.charAt(i++);\n if (c == '[') {\n betweenBrackets = true;\n } else if (betweenBrackets && c == ']') {\n betweenBrackets = false;\n }\n\n if (c != '%' || betweenBrackets) {\n sb.append(c);\n } else {\n bb = decodePercentEncodedOctets(s, i, bb);\n i = decodeOctets(i, bb, sb);\n }\n }\n\n return sb.toString();\n }\n\n /**\n * Decode a contigious sequence of percent encoded octets.\n *

\n * Assumes the index, i, starts that the first hex digit of the first\n * percent-encoded octet.\n */\n private static ByteBuffer decodePercentEncodedOctets(String s, int i, ByteBuffer bb) {\n if (bb == null)\n bb = ByteBuffer.allocate(1);\n else\n ((Buffer)bb).clear();\n\n while (true) {\n // Decode the hex digits\n bb.put((byte) (decodeHex(s, i++) << 4 | decodeHex(s, i++)));\n\n // Finish if at the end of the string\n if (i == s.length()) {\n break;\n }\n\n // Finish if no more percent-encoded octets follow\n if (s.charAt(i++) != '%') {\n break;\n }\n\n // Check if the byte buffer needs to be increased in size\n if (bb.position() == bb.capacity()) {\n ((Buffer)bb).flip();\n // Create a new byte buffer with the maximum number of possible\n // octets, hence resize should only occur once\n ByteBuffer bb_new = ByteBuffer.allocate(s.length() / 3);\n bb_new.put(bb);\n bb = bb_new;\n }\n }\n\n ((Buffer)bb).flip();\n return bb;\n }\n\n /**\n * Decodes octets to characters using the UTF-8 decoding and appends\n * the characters to a StringBuffer.\n * @return the index to the next unchecked character in the string to decode\n */\n private static int decodeOctets(int i, ByteBuffer bb, StringBuilder sb) {\n // If there is only one octet and is an ASCII character\n if (bb.limit() == 1 && (bb.get(0) & 0xFF) < 0x80) {\n // Octet can be appended directly\n sb.append((char) bb.get(0));\n return i + 2;\n } else {\n // \n CharBuffer cb = UTF_8_CHARSET.decode(bb);\n sb.append(cb);\n return i + bb.limit() * 3 - 1;\n }\n }\n\n private static int decodeHex(String s, int i) {\n final int v = decodeHex(s.charAt(i));\n if (v == -1) // TODO localize\n {\n throw new IllegalArgumentException(\"Malformed percent-encoded octet at index \" + i +\n \", invalid hexadecimal digit '\" + s.charAt(i) + \"'\");\n }\n return v;\n }\n private static final int[] HEX_TABLE = createHexTable();\n\n private static int[] createHexTable() {\n int[] table = new int[0x80];\n Arrays.fill(table, -1);\n\n for (char c = '0'; c <= '9'; c++) {\n table[c] = c - '0';\n }\n for (char c = 'A'; c <= 'F'; c++) {\n table[c] = c - 'A' + 10;\n }\n for (char c = 'a'; c <= 'f'; c++) {\n table[c] = c - 'a' + 10;\n }\n return table;\n }\n\n private static int decodeHex(char c) {\n return (c < 128) ? HEX_TABLE[c] : -1;\n }\n\n private static boolean isHexCharacter(char c) {\n return c < 128 && HEX_TABLE[c] != -1;\n }\n}", "file_name": "UriComponent.java", "human_label": "Decode octets to characters with UTF-8, append them to the given StringBuilder, and return the index to the next unchecked character.", "level": "class_runnable", "lineno": "799", "name": "decodeOctets", "oracle_context": "{ \"apis\" : \"[limit, get, append, decode]\", \"classes\" : \"[CharBuffer]\", \"vars\" : \"[UTF_8_CHARSET]\" }", "package": "org.atmosphere.util.uri", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636766aa1a6d9265ec0175ce", "all_context": "{ \"class_level\" : \"import com.alibaba.fastjson2.JSONException;\\nMethodWriter mv;\\nSymbolTable symbolTable;\\nint accessFlags;\\nint nameIndex;\\nString name;\\nint descriptorIndex;\\nString descriptor;\\nint maxStack;\\nint maxLocals;\\nByteVector code;\\nint stackMapTableNumberOfEntries;\\nByteVector stackMapTableEntries;\\nLabel firstBasicBlock;\\nLabel lastBasicBlock;\\nLabel currentBasicBlock;\\nint[] previousFrame;\\nint[] currentFrame;\\nboolean hasAsmInstructions;\\nint lastBytecodeOffset;\\nMethodWriter(SymbolTable symbolTable,int access,String name,String descriptor,int codeInitCapacity);\\nvisitInsn(int opcode);\\nvisitIntInsn(int opcode,int operand);\\nvisitVarInsn(int opcode,int var);\\nvisitTypeInsn(int opcode,String type);\\nvisitFieldInsn(int opcode,String owner,String name,String descriptor);\\nvisitMethodInsn(int opcode,String owner,String name,String descriptor,boolean isInterface);\\nvisitJumpInsn(int opcode,Label label);\\nvisitLabel(Label label);\\nvisitLdcInsn(String value);\\nvisitLdcInsn(Class value);\\nvisitLdcInsn(int value);\\nvisitLdcInsn(long value);\\nvisitIincInsn(int var,int increment);\\nvisitLookupSwitchInsn(Label dflt,int[] keys,Label[] labels);\\nvisitSwitchInsn(Label dflt,Label[] labels);\\nvisitMaxs(int maxStack,int maxLocals);\\nendCurrentBasicBlockWithNoSuccessor();\\nvisitFrameStart(int offset,int numLocal,int numStack);\\nvisitAbstractType(int frameIndex,int abstractType);\\nvisitFrameEnd();\\nputFrame();\\nputAbstractTypes(int start,int end);\\ncomputeMethodInfoSize();\\nputMethodInfo(ByteVector output);\\naddSuccessorToCurrentBasicBlock(Label successor);\\n\", \"repo_level\" : \"public interface JSONException { }\\n\" }", "class_name": "MethodWriter", "code": "int visitFrameStart(final int offset,final int numLocal,final int numStack){\n int frameLength=3 + numLocal + numStack;\n if (currentFrame == null || currentFrame.length < frameLength) {\n currentFrame=new int[frameLength];\n }\n currentFrame[0]=offset;\n currentFrame[1]=numLocal;\n currentFrame[2]=numStack;\n return 3;\n}\n", "docstring": "/** \n * Starts the visit of a new stack map frame, stored in {@link #currentFrame}.\n * @param offset the bytecode offset of the instruction to which the frame corresponds.\n * @param numLocal the number of local variables in the frame.\n * @param numStack the number of stack elements in the frame.\n * @return the index of the next element to be written in this frame.\n */\n", "end_lineno": "651", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage com.alibaba.fastjson2.internal.asm;\n\nimport com.alibaba.fastjson2.JSONException;\n\n/**\n * @author Eric Bruneton\n * @author Eugene Kuleshov\n */\npublic final class MethodWriter {\n protected MethodWriter mv;\n\n /**\n * Where the constants used in this MethodWriter must be stored.\n */\n private final SymbolTable symbolTable;\n\n private final int accessFlags;\n\n /**\n * The name_index field of the method_info JVMS structure.\n */\n private final int nameIndex;\n\n /**\n * The name of this method.\n */\n private final String name;\n\n /**\n * The descriptor_index field of the method_info JVMS structure.\n */\n private final int descriptorIndex;\n\n /**\n * The descriptor of this method.\n */\n private final String descriptor;\n\n // Code attribute fields and sub attributes:\n\n /**\n * The max_stack field of the Code attribute.\n */\n private int maxStack;\n\n /**\n * The max_locals field of the Code attribute.\n */\n private int maxLocals;\n\n /**\n * The 'code' field of the Code attribute.\n */\n private final ByteVector code;\n\n /**\n * The number_of_entries field of the StackMapTable code attribute.\n */\n int stackMapTableNumberOfEntries;\n\n /**\n * The 'entries' array of the StackMapTable code attribute.\n */\n private ByteVector stackMapTableEntries;\n /**\n * The first basic block of the method. The next ones (in bytecode offset order) can be accessed\n * with the {@link Label#nextBasicBlock} field.\n */\n private Label firstBasicBlock;\n\n /**\n * The last basic block of the method (in bytecode offset order). This field is updated each time\n * a basic block is encountered, and is used to append it at the end of the basic block list.\n */\n private Label lastBasicBlock;\n\n private Label currentBasicBlock;\n\n /**\n * The last frame that was written in {@link #stackMapTableEntries}. This field has the same\n * format as {@link #currentFrame}.\n */\n private int[] previousFrame;\n private int[] currentFrame;\n\n boolean hasAsmInstructions;\n\n /**\n * The start offset of the last visited instruction. Used to set the offset field of type\n * annotations of type 'offset_target' (see JVMS\n * 4.7.20.1).\n */\n private int lastBytecodeOffset;\n\n // -----------------------------------------------------------------------------------------------\n // Constructor and accessors\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Constructs a new {@link MethodWriter}.\n *\n * @param symbolTable where the constants used in this AnnotationWriter must be stored.\n * @param access the method's access flags (see {@link Opcodes}).\n * @param name the method's name.\n * @param descriptor the method's descriptor (see {@link Type}).\n */\n MethodWriter(\n SymbolTable symbolTable,\n int access,\n String name,\n String descriptor,\n int codeInitCapacity\n ) {\n this.symbolTable = symbolTable;\n this.accessFlags = \"\".equals(name) ? access | Constants.ACC_CONSTRUCTOR : access;\n this.nameIndex = symbolTable.addConstantUtf8(name);\n this.name = name;\n this.descriptorIndex = symbolTable.addConstantUtf8(descriptor);\n this.descriptor = descriptor;\n this.code = new ByteVector(codeInitCapacity);\n\n // Update maxLocals and currentLocals.\n int argumentsSize = Type.getArgumentsAndReturnSizes(descriptor) >> 2;\n if ((access & Opcodes.ACC_STATIC) != 0) {\n --argumentsSize;\n }\n maxLocals = argumentsSize;\n // Create and visit the label for the first basic block.\n firstBasicBlock = new Label();\n visitLabel(firstBasicBlock);\n }\n\n // -----------------------------------------------------------------------------------------------\n // Implementation of the MethodVisitor abstract class\n // -----------------------------------------------------------------------------------------------\n\n public void visitInsn(final int opcode) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n code.putByte(opcode);\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n currentBasicBlock.frame.execute(opcode, 0, null, null);\n if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN) || opcode == Opcodes.ATHROW) {\n endCurrentBasicBlockWithNoSuccessor();\n }\n }\n }\n\n public void visitIntInsn(final int opcode, final int operand) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n if (opcode == Opcodes.SIPUSH) {\n code.put12(opcode, operand);\n } else { // BIPUSH or NEWARRAY\n code.put11(opcode, operand);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n currentBasicBlock.frame.execute(opcode, operand, null, null);\n }\n }\n\n public void visitVarInsn(final int opcode, final int var) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n if (var < 4 && opcode != Opcodes.RET) {\n int optimizedOpcode;\n if (opcode < Opcodes.ISTORE) {\n optimizedOpcode = Constants.ILOAD_0 + ((opcode - Opcodes.ILOAD) << 2) + var;\n } else {\n optimizedOpcode = Constants.ISTORE_0 + ((opcode - Opcodes.ISTORE) << 2) + var;\n }\n code.putByte(optimizedOpcode);\n } else if (var >= 256) {\n code.putByte(Constants.WIDE).put12(opcode, var);\n } else {\n code.put11(opcode, var);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n currentBasicBlock.frame.execute(opcode, var, null, null);\n }\n\n int currentMaxLocals;\n if (opcode == Opcodes.LLOAD\n || opcode == Opcodes.DLOAD\n || opcode == Opcodes.LSTORE\n || opcode == Opcodes.DSTORE) {\n currentMaxLocals = var + 2;\n } else {\n currentMaxLocals = var + 1;\n }\n if (currentMaxLocals > maxLocals) {\n maxLocals = currentMaxLocals;\n }\n }\n\n public void visitTypeInsn(final int opcode, final String type) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n Symbol typeSymbol = symbolTable.addConstantUtf8Reference(/*CONSTANT_CLASS_TAG*/ 7, type);\n code.put12(opcode, typeSymbol.index);\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n currentBasicBlock.frame.execute(opcode, lastBytecodeOffset, typeSymbol, symbolTable);\n }\n }\n\n public void visitFieldInsn(\n final int opcode, final String owner, final String name, final String descriptor) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n Symbol fieldrefSymbol = symbolTable.addConstantMemberReference(/*CONSTANT_FIELDREF_TAG*/ 9, owner, name, descriptor);\n code.put12(opcode, fieldrefSymbol.index);\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n currentBasicBlock.frame.execute(opcode, 0, fieldrefSymbol, symbolTable);\n }\n }\n\n public void visitMethodInsn(\n final int opcode,\n final String owner,\n final String name,\n final String descriptor,\n final boolean isInterface) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n Symbol methodrefSymbol = symbolTable.addConstantMemberReference(\n isInterface ? /*CONSTANT_INTERFACE_METHODREF_TAG*/ 11 : /*CONSTANT_METHODREF_TAG*/ 10,\n owner,\n name,\n descriptor\n );\n if (opcode == Opcodes.INVOKEINTERFACE) {\n code.put12(Opcodes.INVOKEINTERFACE, methodrefSymbol.index)\n .put11(methodrefSymbol.getArgumentsAndReturnSizes() >> 2, 0);\n } else {\n code.put12(opcode, methodrefSymbol.index);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n currentBasicBlock.frame.execute(opcode, 0, methodrefSymbol, symbolTable);\n }\n }\n\n public void visitJumpInsn(final int opcode, final Label label) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n // Compute the 'base' opcode, i.e. GOTO or JSR if opcode is GOTO_W or JSR_W, otherwise opcode.\n int baseOpcode =\n opcode >= Constants.GOTO_W ? opcode - Constants.WIDE_JUMP_OPCODE_DELTA : opcode;\n boolean nextInsnIsJumpTarget = false;\n if ((label.flags & Label.FLAG_RESOLVED) != 0\n && label.bytecodeOffset - code.length < Short.MIN_VALUE) {\n throw new JSONException(\"not supported\");\n } else if (baseOpcode != opcode) {\n // Case of a GOTO_W or JSR_W specified by the user (normally ClassReader when used to remove\n // ASM specific instructions). In this case we keep the original instruction.\n code.putByte(opcode);\n label.put(code, code.length - 1, true);\n } else {\n // Case of a jump with an offset >= -32768, or of a jump with an unknown offset. In these\n // cases we store the offset in 2 bytes (which will be increased via a ClassReader ->\n // ClassWriter round trip if it turns out that 2 bytes are not sufficient).\n code.putByte(baseOpcode);\n label.put(code, code.length - 1, false);\n }\n\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n Label nextBasicBlock = null;\n currentBasicBlock.frame.execute(baseOpcode, 0, null, null);\n // Record the fact that 'label' is the target of a jump instruction.\n label.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;\n // Add 'label' as a successor of the current basic block.\n addSuccessorToCurrentBasicBlock(label);\n if (baseOpcode != Opcodes.GOTO) {\n // The next instruction starts a new basic block (except for GOTO: by default the code\n // following a goto is unreachable - unless there is an explicit label for it - and we\n // should not compute stack frame types for its instructions).\n nextBasicBlock = new Label();\n }\n\n // If the next instruction starts a new basic block, call visitLabel to add the label of this\n // instruction as a successor of the current block, and to start a new basic block.\n if (nextBasicBlock != null) {\n if (nextInsnIsJumpTarget) {\n nextBasicBlock.flags |= Label.FLAG_JUMP_TARGET;\n }\n visitLabel(nextBasicBlock);\n }\n if (baseOpcode == Opcodes.GOTO) {\n endCurrentBasicBlockWithNoSuccessor();\n }\n }\n }\n\n public void visitLabel(final Label label) {\n // Resolve the forward references to this label, if any.\n hasAsmInstructions |= label.resolve(code.data, code.length);\n // visitLabel starts a new basic block (except for debug only labels), so we need to update the\n // previous and current block references and list of successors.\n if ((label.flags & Label.FLAG_DEBUG_ONLY) != 0) {\n return;\n }\n\n if (currentBasicBlock != null) {\n if (label.bytecodeOffset == currentBasicBlock.bytecodeOffset) {\n // We use {@link Label#getCanonicalInstance} to store the state of a basic block in only\n // one place, but this does not work for labels which have not been visited yet.\n // Therefore, when we detect here two labels having the same bytecode offset, we need to\n // - consolidate the state scattered in these two instances into the canonical instance:\n currentBasicBlock.flags |= (label.flags & Label.FLAG_JUMP_TARGET);\n // - make sure the two instances share the same Frame instance (the implementation of\n // {@link Label#getCanonicalInstance} relies on this property; here label.frame should be\n // null):\n label.frame = currentBasicBlock.frame;\n // - and make sure to NOT assign 'label' into 'currentBasicBlock' or 'lastBasicBlock', so\n // that they still refer to the canonical instance for this bytecode offset.\n return;\n }\n // End the current basic block (with one new successor).\n addSuccessorToCurrentBasicBlock(label);\n }\n // Append 'label' at the end of the basic block list.\n if (lastBasicBlock != null) {\n if (label.bytecodeOffset == lastBasicBlock.bytecodeOffset) {\n // Same comment as above.\n lastBasicBlock.flags |= (label.flags & Label.FLAG_JUMP_TARGET);\n // Here label.frame should be null.\n label.frame = lastBasicBlock.frame;\n currentBasicBlock = lastBasicBlock;\n return;\n }\n lastBasicBlock.nextBasicBlock = label;\n }\n lastBasicBlock = label;\n // Make it the new current basic block.\n currentBasicBlock = label;\n // Here label.frame should be null.\n label.frame = new Frame(label);\n }\n//\n// public void visitLdcInsn(final Object value) {\n// lastBytecodeOffset = code.length;\n// // Add the instruction to the bytecode of the method.\n// Symbol constantSymbol = symbolTable.addConstant(value);\n// int constantIndex = constantSymbol.index;\n// char firstDescriptorChar;\n// boolean isLongOrDouble =\n// constantSymbol.tag == Symbol.CONSTANT_LONG_TAG\n// || constantSymbol.tag == Symbol.CONSTANT_DOUBLE_TAG\n// || (constantSymbol.tag == Symbol.CONSTANT_DYNAMIC_TAG\n// && ((firstDescriptorChar = constantSymbol.value.charAt(0)) == 'J'\n// || firstDescriptorChar == 'D'));\n// if (isLongOrDouble) {\n// code.put12(Constants.LDC2_W, constantIndex);\n// } else if (constantIndex >= 256) {\n// code.put12(Constants.LDC_W, constantIndex);\n// } else {\n// code.put11(Opcodes.LDC, constantIndex);\n// }\n// // If needed, update the maximum stack size and number of locals, and stack map frames.\n// if (currentBasicBlock != null) {\n// currentBasicBlock.frame.execute(Opcodes.LDC, 0, constantSymbol, symbolTable);\n// }\n// }\n\n public void visitLdcInsn(final String value) {\n final int CONSTANT_STRING_TAG = 8;\n\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n Symbol constantSymbol = symbolTable.addConstantUtf8Reference(CONSTANT_STRING_TAG, value);\n int constantIndex = constantSymbol.index;\n if (constantIndex >= 256) {\n code.put12(Constants.LDC_W, constantIndex);\n } else {\n code.put11(Opcodes.LDC, constantIndex);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n currentBasicBlock.frame.execute(Opcodes.LDC, 0, constantSymbol, symbolTable);\n }\n }\n\n public void visitLdcInsn(Class value) {\n // getTypeInternal(typeDescriptor, 0, typeDescriptor.length())\n String desc = ASMUtils.desc(value);\n Type type = Type.getTypeInternal(desc, 0, desc.length());\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n Symbol constantSymbol;\n// int typeSort = type.getSort();\n int typeSort = type.sort == Type.INTERNAL ? Type.OBJECT : type.sort;\n if (typeSort == Type.OBJECT) {\n // type.valueBuffer.substring(type.valueBegin, type.valueEnd)\n constantSymbol = symbolTable.addConstantUtf8Reference(/*CONSTANT_CLASS_TAG*/ 7, type.valueBuffer.substring(type.valueBegin, type.valueEnd));\n } else { // type is a primitive or array type.\n constantSymbol = symbolTable.addConstantUtf8Reference(/*CONSTANT_CLASS_TAG*/ 7, type.getDescriptor());\n }\n int constantIndex = constantSymbol.index;\n if (constantIndex >= 256) {\n code.put12(Constants.LDC_W, constantIndex);\n } else {\n code.put11(Opcodes.LDC, constantIndex);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n currentBasicBlock.frame.execute(Opcodes.LDC, 0, constantSymbol, symbolTable);\n }\n }\n\n public void visitLdcInsn(final int value) {\n final int CONSTANT_INTEGER_TAG = 3;\n\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n Symbol constantSymbol = symbolTable.addConstantIntegerOrFloat(CONSTANT_INTEGER_TAG, value);\n int constantIndex = constantSymbol.index;\n if (constantIndex >= 256) {\n code.put12(Constants.LDC_W, constantIndex);\n } else {\n code.put11(Opcodes.LDC, constantIndex);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n currentBasicBlock.frame.execute(Opcodes.LDC, 0, constantSymbol, symbolTable);\n }\n }\n\n public void visitLdcInsn(final long value) {\n final int CONSTANT_LONG_TAG = 5;\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n Symbol constantSymbol = symbolTable.addConstantLongOrDouble(CONSTANT_LONG_TAG, value);\n int constantIndex = constantSymbol.index;\n code.put12(Constants.LDC2_W, constantIndex);\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n currentBasicBlock.frame.execute(Opcodes.LDC, 0, constantSymbol, symbolTable);\n }\n }\n\n public void visitIincInsn(final int var, final int increment) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n if ((var > 255) || (increment > 127) || (increment < -128)) {\n code.putByte(Constants.WIDE).put12(Opcodes.IINC, var).putShort(increment);\n } else {\n code.putByte(Opcodes.IINC).put11(var, increment);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n currentBasicBlock.frame.execute(Opcodes.IINC, var, null, null);\n }\n }\n\n public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n code.putByte(Opcodes.LOOKUPSWITCH).putByteArray(null, 0, (4 - code.length % 4) % 4);\n dflt.put(code, lastBytecodeOffset, true);\n code.putInt(labels.length);\n for (int i = 0; i < labels.length; ++i) {\n code.putInt(keys[i]);\n labels[i].put(code, lastBytecodeOffset, true);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n visitSwitchInsn(dflt, labels);\n }\n\n private void visitSwitchInsn(final Label dflt, final Label[] labels) {\n if (currentBasicBlock != null) {\n currentBasicBlock.frame.execute(Opcodes.LOOKUPSWITCH, 0, null, null);\n // Add all the labels as successors of the current basic block.\n addSuccessorToCurrentBasicBlock(dflt);\n dflt.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;\n for (Label label : labels) {\n addSuccessorToCurrentBasicBlock(label);\n label.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;\n }\n // End the current basic block.\n endCurrentBasicBlockWithNoSuccessor();\n }\n }\n\n public void visitMaxs(final int maxStack, final int maxLocals) {\n /**\n * Computes all the stack map frames of the method, from scratch.\n */\n // computeAllFrames();\n // Create and visit the first (implicit) frame.\n Frame firstFrame = firstBasicBlock.frame;\n firstFrame.setInputFrameFromDescriptor(symbolTable, accessFlags, descriptor, this.maxLocals);\n firstFrame.accept(this);\n\n // Fix point algorithm: add the first basic block to a list of blocks to process (i.e. blocks\n // whose stack map frame has changed) and, while there are blocks to process, remove one from\n // the list and update the stack map frames of its successor blocks in the control flow graph\n // (which might change them, in which case these blocks must be processed too, and are thus\n // added to the list of blocks to process). Also compute the maximum stack size of the method,\n // as a by-product.\n Label listOfBlocksToProcess = firstBasicBlock;\n listOfBlocksToProcess.nextListElement = Label.EMPTY_LIST;\n int maxStackSize = 0;\n while (listOfBlocksToProcess != Label.EMPTY_LIST) {\n // Remove a basic block from the list of blocks to process.\n Label basicBlock = listOfBlocksToProcess;\n listOfBlocksToProcess = listOfBlocksToProcess.nextListElement;\n basicBlock.nextListElement = null;\n // By definition, basicBlock is reachable.\n basicBlock.flags |= Label.FLAG_REACHABLE;\n // Update the (absolute) maximum stack size.\n int maxBlockStackSize = basicBlock.frame.inputStack.length + basicBlock.outputStackMax;\n if (maxBlockStackSize > maxStackSize) {\n maxStackSize = maxBlockStackSize;\n }\n // Update the successor blocks of basicBlock in the control flow graph.\n Edge outgoingEdge = basicBlock.outgoingEdges;\n while (outgoingEdge != null) {\n Label successorBlock = outgoingEdge.successor.getCanonicalInstance();\n boolean successorBlockChanged =\n basicBlock.frame.merge(symbolTable, successorBlock.frame);\n if (successorBlockChanged && successorBlock.nextListElement == null) {\n // If successorBlock has changed it must be processed. Thus, if it is not already in the\n // list of blocks to process, add it to this list.\n successorBlock.nextListElement = listOfBlocksToProcess;\n listOfBlocksToProcess = successorBlock;\n }\n outgoingEdge = outgoingEdge.nextEdge;\n }\n }\n\n // Loop over all the basic blocks and visit the stack map frames that must be stored in the\n // StackMapTable attribute. Also replace unreachable code with NOP* ATHROW, and remove it from\n // exception handler ranges.\n Label basicBlock = firstBasicBlock;\n while (basicBlock != null) {\n if ((basicBlock.flags & (Label.FLAG_JUMP_TARGET | Label.FLAG_REACHABLE))\n == (Label.FLAG_JUMP_TARGET | Label.FLAG_REACHABLE)) {\n basicBlock.frame.accept(this);\n }\n if ((basicBlock.flags & Label.FLAG_REACHABLE) == 0) {\n // Find the start and end bytecode offsets of this unreachable block.\n Label nextBasicBlock = basicBlock.nextBasicBlock;\n int startOffset = basicBlock.bytecodeOffset;\n int endOffset = (nextBasicBlock == null ? code.length : nextBasicBlock.bytecodeOffset) - 1;\n if (endOffset >= startOffset) {\n // Replace its instructions with NOP ... NOP ATHROW.\n for (int i = startOffset; i < endOffset; ++i) {\n code.data[i] = Opcodes.NOP;\n }\n code.data[endOffset] = (byte) Opcodes.ATHROW;\n // Emit a frame for this unreachable block, with no local and a Throwable on the stack\n // (so that the ATHROW could consume this Throwable if it were reachable).\n int frameIndex = visitFrameStart(startOffset, /* numLocal = */ 0, /* numStack = */ 1);\n currentFrame[frameIndex] = Frame.REFERENCE_KIND | symbolTable.addType(\"java/lang/Throwable\");\n visitFrameEnd();\n // The maximum stack size is now at least one, because of the Throwable declared above.\n maxStackSize = Math.max(maxStackSize, 1);\n }\n }\n basicBlock = basicBlock.nextBasicBlock;\n }\n\n this.maxStack = maxStackSize;\n }\n\n // -----------------------------------------------------------------------------------------------\n // Utility methods: control flow analysis algorithm\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Adds a successor to {@link #currentBasicBlock} in the control flow graph.\n *\n * @param successor the successor block to be added to the current basic block.\n */\n private void addSuccessorToCurrentBasicBlock(final Label successor) {\n currentBasicBlock.outgoingEdges = new Edge(successor, currentBasicBlock.outgoingEdges);\n }\n\n /**\n * Ends the current basic block. This method must be used in the case where the current basic\n * block does not have any successor.\n *\n *

WARNING: this method must be called after the currently visited instruction has been put in\n * {@link #code} (if frames are computed, this method inserts a new Label to start a new basic\n * block after the current instruction).\n */\n private void endCurrentBasicBlockWithNoSuccessor() {\n Label nextBasicBlock = new Label();\n nextBasicBlock.frame = new Frame(nextBasicBlock);\n nextBasicBlock.resolve(code.data, code.length);\n lastBasicBlock.nextBasicBlock = nextBasicBlock;\n lastBasicBlock = nextBasicBlock;\n currentBasicBlock = null;\n }\n\n // -----------------------------------------------------------------------------------------------\n // Utility methods: stack map frames\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Starts the visit of a new stack map frame, stored in {@link #currentFrame}.\n *\n * @param offset the bytecode offset of the instruction to which the frame corresponds.\n * @param numLocal the number of local variables in the frame.\n * @param numStack the number of stack elements in the frame.\n * @return the index of the next element to be written in this frame.\n */\n int visitFrameStart(final int offset, final int numLocal, final int numStack) {\n int frameLength = 3 + numLocal + numStack;\n if (currentFrame == null || currentFrame.length < frameLength) {\n currentFrame = new int[frameLength];\n }\n currentFrame[0] = offset;\n currentFrame[1] = numLocal;\n currentFrame[2] = numStack;\n return 3;\n }\n\n /**\n * Sets an abstract type in {@link #currentFrame}.\n *\n * @param frameIndex the index of the element to be set in {@link #currentFrame}.\n * @param abstractType an abstract type.\n */\n void visitAbstractType(final int frameIndex, final int abstractType) {\n currentFrame[frameIndex] = abstractType;\n }\n\n /**\n * Ends the visit of {@link #currentFrame} by writing it in the StackMapTable entries and by\n * updating the StackMapTable number_of_entries (except if the current frame is the first one,\n * which is implicit in StackMapTable). Then resets {@link #currentFrame} to {@literal null}.\n */\n void visitFrameEnd() {\n if (previousFrame != null) {\n if (stackMapTableEntries == null) {\n stackMapTableEntries = new ByteVector(2048);\n }\n putFrame();\n ++stackMapTableNumberOfEntries;\n }\n previousFrame = currentFrame;\n currentFrame = null;\n }\n\n /**\n * Compresses and writes {@link #currentFrame} in a new StackMapTable entry.\n */\n private void putFrame() {\n final int numLocal = currentFrame[1];\n final int numStack = currentFrame[2];\n final int offsetDelta =\n stackMapTableNumberOfEntries == 0\n ? currentFrame[0]\n : currentFrame[0] - previousFrame[0] - 1;\n final int previousNumlocal = previousFrame[1];\n final int numLocalDelta = numLocal - previousNumlocal;\n int type = Frame.FULL_FRAME;\n if (numStack == 0) {\n switch (numLocalDelta) {\n case -3:\n case -2:\n case -1:\n type = Frame.CHOP_FRAME;\n break;\n case 0:\n type = offsetDelta < 64 ? Frame.SAME_FRAME : Frame.SAME_FRAME_EXTENDED;\n break;\n case 1:\n case 2:\n case 3:\n type = Frame.APPEND_FRAME;\n break;\n default:\n // Keep the FULL_FRAME type.\n break;\n }\n } else if (numLocalDelta == 0 && numStack == 1) {\n type =\n offsetDelta < 63\n ? Frame.SAME_LOCALS_1_STACK_ITEM_FRAME\n : Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED;\n }\n if (type != Frame.FULL_FRAME) {\n // Verify if locals are the same as in the previous frame.\n int frameIndex = 3;\n for (int i = 0; i < previousNumlocal && i < numLocal; i++) {\n if (currentFrame[frameIndex] != previousFrame[frameIndex]) {\n type = Frame.FULL_FRAME;\n break;\n }\n frameIndex++;\n }\n }\n switch (type) {\n case Frame.SAME_FRAME:\n stackMapTableEntries.putByte(offsetDelta);\n break;\n case Frame.SAME_LOCALS_1_STACK_ITEM_FRAME:\n stackMapTableEntries.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME + offsetDelta);\n putAbstractTypes(3 + numLocal, 4 + numLocal);\n break;\n case Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED:\n stackMapTableEntries\n .putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED)\n .putShort(offsetDelta);\n putAbstractTypes(3 + numLocal, 4 + numLocal);\n break;\n case Frame.SAME_FRAME_EXTENDED:\n stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED).putShort(offsetDelta);\n break;\n case Frame.CHOP_FRAME:\n stackMapTableEntries\n .putByte(Frame.SAME_FRAME_EXTENDED + numLocalDelta)\n .putShort(offsetDelta);\n break;\n case Frame.APPEND_FRAME:\n stackMapTableEntries\n .putByte(Frame.SAME_FRAME_EXTENDED + numLocalDelta)\n .putShort(offsetDelta);\n putAbstractTypes(3 + previousNumlocal, 3 + numLocal);\n break;\n case Frame.FULL_FRAME:\n default:\n stackMapTableEntries.putByte(Frame.FULL_FRAME).putShort(offsetDelta).putShort(numLocal);\n putAbstractTypes(3, 3 + numLocal);\n stackMapTableEntries.putShort(numStack);\n putAbstractTypes(3 + numLocal, 3 + numLocal + numStack);\n break;\n }\n }\n\n /**\n * Puts some abstract types of {@link #currentFrame} in {@link #stackMapTableEntries} , using the\n * JVMS verification_type_info format used in StackMapTable attributes.\n *\n * @param start index of the first type in {@link #currentFrame} to write.\n * @param end index of last type in {@link #currentFrame} to write (exclusive).\n */\n private void putAbstractTypes(final int start, final int end) {\n for (int i = start; i < end; ++i) {\n final int abstractType = currentFrame[i];\n final ByteVector output = stackMapTableEntries;\n\n int arrayDimensions = (abstractType & Frame.DIM_MASK) >> Frame.DIM_SHIFT;\n if (arrayDimensions == 0) {\n int typeValue = abstractType & Frame.VALUE_MASK;\n switch (abstractType & Frame.KIND_MASK) {\n case Frame.CONSTANT_KIND:\n output.putByte(typeValue);\n break;\n case Frame.REFERENCE_KIND:\n output\n .putByte(Frame.ITEM_OBJECT)\n .putShort(symbolTable.addConstantUtf8Reference(/*CONSTANT_CLASS_TAG*/ 7, symbolTable.typeTable[typeValue].value).index);\n break;\n case Frame.UNINITIALIZED_KIND:\n output.putByte(Frame.ITEM_UNINITIALIZED).putShort((int) symbolTable.typeTable[typeValue].data);\n break;\n default:\n throw new AssertionError();\n }\n } else {\n // Case of an array type, we need to build its descriptor first.\n StringBuilder typeDescriptor = new StringBuilder();\n while (arrayDimensions-- > 0) {\n typeDescriptor.append('[');\n }\n if ((abstractType & Frame.KIND_MASK) == Frame.REFERENCE_KIND) {\n typeDescriptor\n .append('L')\n .append(symbolTable.typeTable[abstractType & Frame.VALUE_MASK].value)\n .append(';');\n } else {\n switch (abstractType & Frame.VALUE_MASK) {\n case Frame.ITEM_ASM_BOOLEAN:\n typeDescriptor.append('Z');\n break;\n case Frame.ITEM_ASM_BYTE:\n typeDescriptor.append('B');\n break;\n case Frame.ITEM_ASM_CHAR:\n typeDescriptor.append('C');\n break;\n case Frame.ITEM_ASM_SHORT:\n typeDescriptor.append('S');\n break;\n case Frame.ITEM_INTEGER:\n typeDescriptor.append('I');\n break;\n case Frame.ITEM_FLOAT:\n typeDescriptor.append('F');\n break;\n case Frame.ITEM_LONG:\n typeDescriptor.append('J');\n break;\n case Frame.ITEM_DOUBLE:\n typeDescriptor.append('D');\n break;\n default:\n throw new AssertionError();\n }\n }\n output\n .putByte(Frame.ITEM_OBJECT)\n .putShort(symbolTable.addConstantUtf8Reference(/*CONSTANT_CLASS_TAG*/ 7, typeDescriptor.toString()).index);\n }\n }\n }\n\n // -----------------------------------------------------------------------------------------------\n // Utility methods\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the size of the method_info JVMS structure generated by this MethodWriter. Also add the\n * names of the attributes of this method in the constant pool.\n *\n * @return the size in bytes of the method_info JVMS structure.\n */\n int computeMethodInfoSize() {\n // 2 bytes each for access_flags, name_index, descriptor_index and attributes_count.\n int size = 8;\n // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.\n if (code.length > 0) {\n if (code.length > 65535) {\n throw new JSONException(\"Method too large: \" + symbolTable.className + \".\" + name + \" \" + descriptor + \", length \" + code.length);\n }\n symbolTable.addConstantUtf8(Constants.CODE);\n // The Code attribute has 6 header bytes, plus 2, 2, 4 and 2 bytes respectively for max_stack,\n // max_locals, code_length and attributes_count, plus the bytecode and the exception table.\n size += 16 + code.length + 2;\n if (stackMapTableEntries != null) {\n boolean useStackMapTable = true;\n symbolTable.addConstantUtf8(useStackMapTable ? Constants.STACK_MAP_TABLE : \"StackMap\");\n // 6 header bytes and 2 bytes for number_of_entries.\n size += 8 + stackMapTableEntries.length;\n }\n }\n return size;\n }\n\n /**\n * Puts the content of the method_info JVMS structure generated by this MethodWriter into the\n * given ByteVector.\n *\n * @param output where the method_info structure must be put.\n */\n void putMethodInfo(final ByteVector output) {\n int mask = 0;\n output.putShort(accessFlags & ~mask).putShort(nameIndex).putShort(descriptorIndex);\n // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.\n int attributeCount = 0;\n if (code.length > 0) {\n ++attributeCount;\n }\n // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.\n output.putShort(attributeCount);\n if (code.length > 0) {\n // 2, 2, 4 and 2 bytes respectively for max_stack, max_locals, code_length and\n // attributes_count, plus the bytecode and the exception table.\n int size = 10 + code.length + 2;\n int codeAttributeCount = 0;\n if (stackMapTableEntries != null) {\n // 6 header bytes and 2 bytes for number_of_entries.\n size += 8 + stackMapTableEntries.length;\n ++codeAttributeCount;\n }\n output\n .putShort(symbolTable.addConstantUtf8(Constants.CODE))\n .putInt(size)\n .putShort(maxStack)\n .putShort(maxLocals)\n .putInt(code.length)\n .putByteArray(code.data, 0, code.length);\n output.putShort(0); // putExceptionTable\n output.putShort(codeAttributeCount);\n if (stackMapTableEntries != null) {\n boolean useStackMapTable = true;\n output\n .putShort(\n symbolTable.addConstantUtf8(\n useStackMapTable ? Constants.STACK_MAP_TABLE : \"StackMap\"))\n .putInt(2 + stackMapTableEntries.length)\n .putShort(stackMapTableNumberOfEntries)\n .putByteArray(stackMapTableEntries.data, 0, stackMapTableEntries.length);\n }\n }\n }\n}\n", "file_name": "MethodWriter.java", "human_label": "Init a currentFrame with the given offset, numLocal and numStack, return 3 finally.", "level": "self_contained", "lineno": "634", "name": "visitFrameStart", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[currentFrame]\", \"vars\" : \"[length, currentFrame]\" }", "package": "com.alibaba.fastjson2.internal.asm", "project": "fastjson2-main" }, { "_id": "636767191a6d9265ec017c0f", "all_context": "{ \"class_level\" : \"byte[] data;\\nint length;\\nByteVector();\\nByteVector(int initialCapacity);\\nByteVector(byte[] data);\\nput11(int byteValue1,int byteValue2);\\nputShort(int shortValue);\\nput12(int byteValue,int shortValue);\\nput112(int byteValue1,int byteValue2,int shortValue);\\nputInt(int intValue);\\nput122(int byteValue,int shortValue1,int shortValue2);\\nputLong(long longValue);\\nputUTF8(String stringValue);\\nencodeUtf8(String stringValue,int offset,int maxByteLength);\\nputByteArray(byte[] byteArrayValue,int byteOffset,int byteLength);\\nenlarge(int size);\\nputByte(int byteValue);\\n\", \"repo_level\" : \"\" }", "class_name": "ByteVector", "code": "private void enlarge(final int size){\n int doubleCapacity=2 * data.length;\n int minimalCapacity=length + size;\n byte[] newData=new byte[doubleCapacity > minimalCapacity ? doubleCapacity : minimalCapacity];\n System.arraycopy(data,0,newData,0,length);\n data=newData;\n}\n", "docstring": "/** \n * Enlarges this byte vector so that it can receive 'size' more bytes.\n * @param size number of additional bytes that this byte vector should be able to receive.\n */\n", "end_lineno": "356", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage net.hasor.utils.asm;\n/**\n * A dynamically extensible vector of bytes. This class is roughly equivalent to a DataOutputStream\n * on top of a ByteArrayOutputStream, but is more efficient.\n *\n * @author Eric Bruneton\n */\npublic class ByteVector {\n /** The content of this vector. Only the first {@link #length} bytes contain real data. */\n byte[] data;\n /** The actual number of bytes in this vector. */\n int length;\n\n /** Constructs a new {@link ByteVector} with a default initial capacity. */\n public ByteVector() {\n data = new byte[64];\n }\n\n /**\n * Constructs a new {@link ByteVector} with the given initial capacity.\n *\n * @param initialCapacity the initial capacity of the byte vector to be constructed.\n */\n public ByteVector(final int initialCapacity) {\n data = new byte[initialCapacity];\n }\n\n /**\n * Constructs a new {@link ByteVector} from the given initial data.\n *\n * @param data the initial data of the new byte vector.\n */\n ByteVector(final byte[] data) {\n this.data = data;\n this.length = data.length;\n }\n\n /**\n * Puts a byte into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param byteValue a byte.\n * @return this byte vector.\n */\n public ByteVector putByte(final int byteValue) {\n int currentLength = length;\n if (currentLength + 1 > data.length) {\n enlarge(1);\n }\n data[currentLength++] = (byte) byteValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts two bytes into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param byteValue1 a byte.\n * @param byteValue2 another byte.\n * @return this byte vector.\n */\n final ByteVector put11(final int byteValue1, final int byteValue2) {\n int currentLength = length;\n if (currentLength + 2 > data.length) {\n enlarge(2);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue1;\n currentData[currentLength++] = (byte) byteValue2;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a short into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param shortValue a short.\n * @return this byte vector.\n */\n public ByteVector putShort(final int shortValue) {\n int currentLength = length;\n if (currentLength + 2 > data.length) {\n enlarge(2);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a byte and a short into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteValue a byte.\n * @param shortValue a short.\n * @return this byte vector.\n */\n final ByteVector put12(final int byteValue, final int shortValue) {\n int currentLength = length;\n if (currentLength + 3 > data.length) {\n enlarge(3);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts two bytes and a short into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteValue1 a byte.\n * @param byteValue2 another byte.\n * @param shortValue a short.\n * @return this byte vector.\n */\n final ByteVector put112(final int byteValue1, final int byteValue2, final int shortValue) {\n int currentLength = length;\n if (currentLength + 4 > data.length) {\n enlarge(4);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue1;\n currentData[currentLength++] = (byte) byteValue2;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an int into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param intValue an int.\n * @return this byte vector.\n */\n public ByteVector putInt(final int intValue) {\n int currentLength = length;\n if (currentLength + 4 > data.length) {\n enlarge(4);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts one byte and two shorts into this byte vector. The byte vector is automatically enlarged\n * if necessary.\n *\n * @param byteValue a byte.\n * @param shortValue1 a short.\n * @param shortValue2 another short.\n * @return this byte vector.\n */\n final ByteVector put122(final int byteValue, final int shortValue1, final int shortValue2) {\n int currentLength = length;\n if (currentLength + 5 > data.length) {\n enlarge(5);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue;\n currentData[currentLength++] = (byte) (shortValue1 >>> 8);\n currentData[currentLength++] = (byte) shortValue1;\n currentData[currentLength++] = (byte) (shortValue2 >>> 8);\n currentData[currentLength++] = (byte) shortValue2;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a long into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param longValue a long.\n * @return this byte vector.\n */\n public ByteVector putLong(final long longValue) {\n int currentLength = length;\n if (currentLength + 8 > data.length) {\n enlarge(8);\n }\n byte[] currentData = data;\n int intValue = (int) (longValue >>> 32);\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n intValue = (int) longValue;\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param stringValue a String whose UTF8 encoded length must be less than 65536.\n * @return this byte vector.\n */\n // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility).\n public ByteVector putUTF8(final String stringValue) {\n int charLength = stringValue.length();\n if (charLength > 65535) {\n throw new IllegalArgumentException(\"UTF8 string too large\");\n }\n int currentLength = length;\n if (currentLength + 2 + charLength > data.length) {\n enlarge(2 + charLength);\n }\n byte[] currentData = data;\n // Optimistic algorithm: instead of computing the byte length and then serializing the string\n // (which requires two loops), we assume the byte length is equal to char length (which is the\n // most frequent case), and we start serializing the string right away. During the\n // serialization, if we find that this assumption is wrong, we continue with the general method.\n currentData[currentLength++] = (byte) (charLength >>> 8);\n currentData[currentLength++] = (byte) charLength;\n for (int i = 0; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= '\\u0001' && charValue <= '\\u007F') {\n currentData[currentLength++] = (byte) charValue;\n } else {\n length = currentLength;\n return encodeUtf8(stringValue, i, 65535);\n }\n }\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if\n * necessary. The string length is encoded in two bytes before the encoded characters, if there is\n * space for that (i.e. if this.length - offset - 2 >= 0).\n *\n * @param stringValue the String to encode.\n * @param offset the index of the first character to encode. The previous characters are supposed\n * to have already been encoded, using only one byte per character.\n * @param maxByteLength the maximum byte length of the encoded string, including the already\n * encoded characters.\n * @return this byte vector.\n */\n final ByteVector encodeUtf8(final String stringValue, final int offset, final int maxByteLength) {\n int charLength = stringValue.length();\n int byteLength = offset;\n for (int i = offset; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= 0x0001 && charValue <= 0x007F) {\n byteLength++;\n } else if (charValue <= 0x07FF) {\n byteLength += 2;\n } else {\n byteLength += 3;\n }\n }\n if (byteLength > maxByteLength) {\n throw new IllegalArgumentException(\"UTF8 string too large\");\n }\n // Compute where 'byteLength' must be stored in 'data', and store it at this location.\n int byteLengthOffset = length - offset - 2;\n if (byteLengthOffset >= 0) {\n data[byteLengthOffset] = (byte) (byteLength >>> 8);\n data[byteLengthOffset + 1] = (byte) byteLength;\n }\n if (length + byteLength - offset > data.length) {\n enlarge(byteLength - offset);\n }\n int currentLength = length;\n for (int i = offset; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= 0x0001 && charValue <= 0x007F) {\n data[currentLength++] = (byte) charValue;\n } else if (charValue <= 0x07FF) {\n data[currentLength++] = (byte) (0xC0 | charValue >> 6 & 0x1F);\n data[currentLength++] = (byte) (0x80 | charValue & 0x3F);\n } else {\n data[currentLength++] = (byte) (0xE0 | charValue >> 12 & 0xF);\n data[currentLength++] = (byte) (0x80 | charValue >> 6 & 0x3F);\n data[currentLength++] = (byte) (0x80 | charValue & 0x3F);\n }\n }\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an array of bytes into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteArrayValue an array of bytes. May be {@literal null} to put {@code byteLength} null\n * bytes into this byte vector.\n * @param byteOffset index of the first byte of byteArrayValue that must be copied.\n * @param byteLength number of bytes of byteArrayValue that must be copied.\n * @return this byte vector.\n */\n public ByteVector putByteArray(final byte[] byteArrayValue, final int byteOffset, final int byteLength) {\n if (length + byteLength > data.length) {\n enlarge(byteLength);\n }\n if (byteArrayValue != null) {\n System.arraycopy(byteArrayValue, byteOffset, data, length, byteLength);\n }\n length += byteLength;\n return this;\n }\n\n /**\n * Enlarges this byte vector so that it can receive 'size' more bytes.\n *\n * @param size number of additional bytes that this byte vector should be able to receive.\n */\n private void enlarge(final int size) {\n int doubleCapacity = 2 * data.length;\n int minimalCapacity = length + size;\n byte[] newData = new byte[doubleCapacity > minimalCapacity ? doubleCapacity : minimalCapacity];\n System.arraycopy(data, 0, newData, 0, length);\n data = newData;\n }\n}\n", "file_name": "ByteVector.java", "human_label": "Enlarge the byte vector data, by increasing it by the given size.", "level": "class_runnable", "lineno": "345", "name": "enlarge", "oracle_context": "{ \"apis\" : \"[arraycopy]\", \"classes\" : \"[byte[], data]\", \"vars\" : \"[length, data]\" }", "package": "net.hasor.utils.asm", "project": "hasor-master" }, { "_id": "636767821a6d9265ec0183a0", "all_context": "{ \"class_level\" : \"import org.apache.log4j.RollingCalendar;\\nimport org.apache.log4j.helpers.OptionConverter;\\nimport org.apache.log4j.helpers.QuietWriter;\\nimport org.apache.log4j.helpers.CountingQuietWriter;\\nimport org.apache.log4j.helpers.LogLog;\\nimport org.apache.log4j.spi.LoggingEvent;\\nimport java.util.Date;\\nimport java.io.IOException;\\nimport java.io.Writer;\\nimport java.text.SimpleDateFormat;\\nimport java.io.File;\\nimport java.io.FilenameFilter;\\nint TOP_OF_TROUBLE;\\nint TOP_OF_MINUTE;\\nint TOP_OF_HOUR;\\nint HALF_DAY;\\nint TOP_OF_DAY;\\nint TOP_OF_WEEK;\\nint TOP_OF_MONTH;\\nint BY_SIZE;\\nint BY_DATE;\\nint BY_COMPOSITE;\\nString S_BY_SIZE;\\nString S_BY_DATE;\\nString S_BY_COMPOSITE;\\nString datePattern;\\nString scheduledFilename;\\nlong nextCheck;\\nDate now;\\nSimpleDateFormat sdf;\\nRollingCalendar rc;\\nint checkPeriod;\\nlong maxFileSize;\\nint maxSizeRollBackups;\\nint curSizeRollBackups;\\nint maxTimeRollBackups;\\nint curTimeRollBackups;\\nint countDirection;\\nint rollingStyle;\\nboolean rollDate;\\nboolean rollSize;\\nboolean staticLogFileName;\\nString baseFileName;\\nCompositeRollingAppender();\\nCompositeRollingAppender(Layout layout,String filename,String datePattern);\\nCompositeRollingAppender(Layout layout,String filename,boolean append);\\nCompositeRollingAppender(Layout layout,String filename,String datePattern,boolean append);\\nCompositeRollingAppender(Layout layout,String filename);\\nsetDatePattern(String pattern);\\ngetDatePattern();\\ngetMaxSizeRollBackups();\\ngetMaximumFileSize();\\nsetMaxSizeRollBackups(int maxBackups);\\nsetMaxFileSize(long maxFileSize);\\nsetMaximumFileSize(long maxFileSize);\\nsetMaxFileSize(String value);\\nsetQWForFiles(Writer writer);\\ncomputeCheckPeriod();\\nsetFile(String file);\\nsetFile(String fileName,boolean append);\\ngetCountDirection();\\nsetCountDirection(int direction);\\ngetRollingStyle();\\nsetRollingStyle(int style);\\ngetStaticLogFileName();\\nsetStaticLogFileName(boolean s);\\nsetStaticLogFileName(String value);\\nexistingInit();\\nactivateOptions();\\nrollOverTime();\\nrollFile(String from,String to);\\ndeleteFile(String fileName);\\nrollOverSize();\\nsubAppend(LoggingEvent event);\\n\", \"repo_level\" : \"public interface RollingCalendar { void setType(int type);\\npublic long getNextCheckMillis(Date now);\\npublic Date getNextCheckDate(Date now);\\n }\\npublic interface OptionConverter {static String[] concatanateArrays(String[] l,String[] r);\\nstatic String convertSpecialChars(String s);\\nstatic String getSystemProperty(String key,String def);\\nstatic Object instantiateByKey(Properties props,String key,Class superClass,Object defaultValue);\\nstatic boolean toBoolean(String value,boolean dEfault);\\nstatic int toInt(String value,int dEfault);\\nstatic Level toLevel(String value,Level defaultValue);\\nstatic long toFileSize(String value,long dEfault);\\nstatic String findAndSubst(String key,Properties props);\\nstatic Object instantiateByClassName(String className,Class superClass,Object defaultValue);\\nstatic String substVars(String val,Properties props);\\npublic void selectAndConfigure(InputStream inputStream,String clazz,LoggerRepository hierarchy);\\npublic void selectAndConfigure(URL url,String clazz,LoggerRepository hierarchy);\\n }\\npublic interface QuietWriter {public void write(String string);\\npublic void flush();\\npublic void setErrorHandler(ErrorHandler eh);\\n }\\npublic interface CountingQuietWriter {public void write(String string);\\npublic long getCount();\\npublic void setCount(long count);\\n }\\npublic interface LogLog {public void setInternalDebugging(boolean enabled);\\nstatic void debug(String msg);\\nstatic void debug(String msg,Throwable t);\\nstatic void error(String msg);\\nstatic void error(String msg,Throwable t);\\nstatic void setQuietMode(boolean quietMode);\\nstatic void warn(String msg);\\nstatic void warn(String msg,Throwable t);\\n }\\npublic interface LoggingEvent {public LocationInfo getLocationInformation();\\npublic Level getLevel();\\npublic String getLoggerName();\\npublic Category getLogger();\\npublic Object getMessage();\\npublic String getNDC();\\npublic Object getMDC(String key);\\npublic void getMDCCopy();\\npublic String getRenderedMessage();\\nstatic long getStartTime();\\npublic String getThreadName();\\npublic ThrowableInformation getThrowableInformation();\\npublic String[] getThrowableStrRep();\\nfinal void setProperty(String propName,String propValue);\\nfinal String getProperty(String key);\\nfinal boolean locationInformationExists();\\nfinal long getTimeStamp();\\npublic Set getPropertyKeySet();\\npublic Map getProperties();\\npublic String getFQNOfLoggerClass();\\npublic Object removeProperty(String propName);\\n }\\n\" }", "class_name": "CompositeRollingAppender", "code": "protected static void deleteFile(String fileName){\n File file=new File(fileName);\n if (file.exists()) {\n file.delete();\n }\n}\n", "docstring": "/** \n * Delete's the specified file if it exists \n */\n", "end_lineno": "622", "file_content": "package org.apache.log4j;\n\n/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport org.apache.log4j.RollingCalendar;\nimport org.apache.log4j.helpers.OptionConverter;\nimport org.apache.log4j.helpers.QuietWriter;\nimport org.apache.log4j.helpers.CountingQuietWriter;\nimport org.apache.log4j.helpers.LogLog;\nimport org.apache.log4j.spi.LoggingEvent;\n\nimport java.util.Date;\nimport java.io.IOException;\nimport java.io.Writer;\nimport java.text.SimpleDateFormat;\nimport java.io.File;\nimport java.io.FilenameFilter;\n\n/**\n *

CompositeRollingAppender combines RollingFileAppender and DailyRollingFileAppender
\n * It can function as either or do both at the same time (making size\n * based rolling files like RollingFileAppender until a data/time boundary\n * is crossed at which time it rolls all of those files as per the DailyRollingFileAppender)\n * based on the setting for rollingStyle.
\n *
\n * To use CompositeRollingAppender to roll log files as they reach a certain\n * size (like RollingFileAppender), set rollingStyle=1 (@see config.size)
\n * To use CompositeRollingAppender to roll log files at certain time intervals\n * (daily for example), set rollingStyle=2 and a datePattern (@see config.time)
\n * To have CompositeRollingAppender roll log files at a certain size AND rename those\n * according to time intervals, set rollingStyle=3 (@see config.composite)
\n *\n *

A of few additional optional features have been added:
\n * -- Attach date pattern for current log file (@see staticLogFileName)
\n * -- Backup number increments for newer files (@see countDirection)
\n * -- Infinite number of backups by file size (@see maxSizeRollBackups)
\n *
\n *

A few notes and warnings: For large or infinite number of backups\n * countDirection > 0 is highly recommended, with staticLogFileName = false if\n * time based rolling is also used -- this will reduce the number of file renamings\n * to few or none. Changing staticLogFileName or countDirection without clearing\n * the directory could have nasty side effects. If Date/Time based rolling\n * is enabled, CompositeRollingAppender will attempt to roll existing files\n * in the directory without a date/time tag based on the last modified date\n * of the base log files last modification.
\n *
\n *

A maximum number of backups based on date/time boundries would be nice\n * but is not yet implemented.
\n *\n * @author Kevin Steppe\n * @author Heinz Richter\n * @author Eirik Lygre\n * @author Ceki Gülcü\n */\npublic class CompositeRollingAppender extends org.apache.log4j.FileAppender\n{\n\t// The code assumes that the following 'time' constants are in a increasing\n\t// sequence.\n\tstatic final int TOP_OF_TROUBLE=-1;\n\tstatic final int TOP_OF_MINUTE = 0;\n\tstatic final int TOP_OF_HOUR = 1;\n\tstatic final int HALF_DAY = 2;\n\tstatic final int TOP_OF_DAY = 3;\n\tstatic final int TOP_OF_WEEK = 4;\n\tstatic final int TOP_OF_MONTH = 5;\n\n\t/** Style of rolling to use */\n\tstatic final int BY_SIZE = 1;\n\tstatic final int BY_DATE = 2;\n\tstatic final int BY_COMPOSITE = 3;\n\n\t//Not currently used\n\tstatic final String S_BY_SIZE = \"Size\";\n\tstatic final String S_BY_DATE = \"Date\";\n\tstatic final String S_BY_COMPOSITE = \"Composite\";\n\n\t/**\n\t The date pattern. By default, the pattern is set to\n\t \"'.'yyyy-MM-dd\" meaning daily rollover.\n\t*/\n\tprivate String datePattern = \"'.'yyyy-MM-dd\";\n\n\t/**\t The actual formatted filename that is currently being written to\n\t or will be the file transferred to on roll over\n\t\t (based on staticLogFileName). */\n\tprivate String scheduledFilename = null;\n\n\t/** The timestamp when we shall next recompute the filename. */\n\tprivate long nextCheck = System.currentTimeMillis () - 1;\n\n\t/** Holds date of last roll over */\n\tDate now = new Date();\n\n\tSimpleDateFormat sdf;\n\n\t/** Helper class to determine next rollover time */\n\tRollingCalendar rc = new RollingCalendar();\n\n\t/** Current period for roll overs */\n\tint checkPeriod = TOP_OF_TROUBLE;\n\n\t/**\t The default maximum file size is 10MB. */\n\tprotected long maxFileSize = 10*1024*1024;\n\n\t/**\t There is zero backup files by default. */\n\tprotected int maxSizeRollBackups = 0;\n\t/** How many sized based backups have been made so far */\n\tprotected int curSizeRollBackups = 0;\n\n\t/** not yet implemented */\n\tprotected int maxTimeRollBackups = -1;\n\tprotected int curTimeRollBackups = 0;\n\n\t/** By default newer files have lower numbers. (countDirection < 0)\n\t * ie. log.1 is most recent, log.5 is the 5th backup, etc...\n\t * countDirection > 0 does the opposite ie.\n\t * log.1 is the first backup made, log.5 is the 5th backup made, etc.\n\t * For infinite backups use countDirection > 0 to reduce rollOver costs.\n\t */\n\tprotected int countDirection = -1;\n\n\t/** Style of rolling to Use. BY_SIZE (1), BY_DATE(2), BY COMPOSITE(3) */\n\tprotected int rollingStyle = BY_COMPOSITE;\n\tprotected boolean rollDate = true;\n\tprotected boolean rollSize = true;\n\n\t/** By default file.log is always the current file. Optionally\n\t * file.log.yyyy-mm-dd for current formated datePattern can by the currently\n\t * logging file (or file.log.curSizeRollBackup or even\n\t * file.log.yyyy-mm-dd.curSizeRollBackup) This will make time based roll\n\t * overs with a large number of backups much faster -- it won't have to\n\t * rename all the backups!\n\t */\n\tprotected boolean staticLogFileName = true;\n\n\t/** FileName provided in configuration. Used for rolling properly */\n\tprotected String baseFileName;\n\n /** The default constructor does nothing. */\n\tpublic CompositeRollingAppender() {\n }\n\n\t/**\n\t Instantiate a CompositeRollingAppender and open the\n\t file designated by filename. The opened filename will\n\t become the ouput destination for this appender.\n\t*/\n\tpublic CompositeRollingAppender (Layout layout, String filename,\n\t\t\t\t String datePattern) throws IOException {\n\t this(layout, filename, datePattern, true);\n\t}\n\n\t/**\n\t Instantiate a CompositeRollingAppender and open the file designated by\n\t filename. The opened filename will become the ouput\n\t destination for this appender.\n\n\t

If the append parameter is true, the file will be\n\t appended to. Otherwise, the file desginated by\n\t filename will be truncated before being opened.\n\t*/\n\tpublic CompositeRollingAppender(Layout layout, String filename, boolean append)\n\t\t\t\t\t\t\t\t\t throws IOException {\n\t super(layout, filename, append);\n\t}\n\n\t/**\n\t Instantiate a CompositeRollingAppender and open the file designated by\n\t filename. The opened filename will become the ouput\n\t destination for this appender.\n\t*/\n\tpublic CompositeRollingAppender (Layout layout, String filename,\n\t\t\t\t String datePattern, boolean append) throws IOException {\n\t super(layout, filename, append);\n\t this.datePattern = datePattern;\n\t\tactivateOptions();\n\t}\n\t/**\n\t Instantiate a CompositeRollingAppender and open the file designated by\n\t filename. The opened filename will become the output\n\t destination for this appender.\n\n\t

The file will be appended to. DatePattern is default.\n\t*/\n\tpublic CompositeRollingAppender(Layout layout, String filename) throws IOException {\n\t super(layout, filename);\n\t}\n\n\t/**\n\t The DatePattern takes a string in the same format as\n\t expected by {@link SimpleDateFormat}. This options determines the\n\t rollover schedule.\n\t*/\n\tpublic void setDatePattern(String pattern) {\n\t datePattern = pattern;\n\t}\n\n\t/** Returns the value of the DatePattern option. */\n\tpublic String getDatePattern() {\n\t return datePattern;\n\t}\n\n\t/**\n\t Returns the value of the maxSizeRollBackups option.\n\t*/\n\tpublic int getMaxSizeRollBackups() {\n\t return maxSizeRollBackups;\n\t}\n\n\t/**\n\t Get the maximum size that the output file is allowed to reach\n\t before being rolled over to backup files.\n\n\t @since 1.1\n\t*/\n\tpublic long getMaximumFileSize() {\n\t\treturn maxFileSize;\n\t}\n\n\t/**\n\t

Set the maximum number of backup files to keep around based on file size.\n\n\t

The MaxSizeRollBackups option determines how many backup\n\t files are kept before the oldest is erased. This option takes\n\t an integer value. If set to zero, then there will be no\n\t backup files and the log file will be truncated when it reaches\n\t MaxFileSize. If a negative number is supplied then\n\t no deletions will be made. Note that this could result in\n\t very slow performance as a large number of files are rolled over unless\n\t {@link #setCountDirection} up is used.\n\n\t

The maximum applys to -each- time based group of files and -not- the total.\n\t Using a daily roll the maximum total files would be (#days run) * (maxSizeRollBackups)\n\n\t*/\n\tpublic void setMaxSizeRollBackups(int maxBackups) {\n\t maxSizeRollBackups = maxBackups;\n\t}\n\n\t/**\n\t Set the maximum size that the output file is allowed to reach\n\t before being rolled over to backup files.\n\n\t

This method is equivalent to {@link #setMaxFileSize} except\n\t that it is required for differentiating the setter taking a\n\t long argument from the setter taking a\n\t String argument by the JavaBeans {@link\n\t java.beans.Introspector Introspector}.\n\n\t @see #setMaxFileSize(String)\n\t*/\n\tpublic void setMaxFileSize(long maxFileSize) {\n\t this.maxFileSize = maxFileSize;\n\t}\n\n\t/**\n\t Set the maximum size that the output file is allowed to reach\n\t before being rolled over to backup files.\n\n\t

This method is equivalent to {@link #setMaxFileSize} except\n\t that it is required for differentiating the setter taking a\n\t long argument from the setter taking a\n\t String argument by the JavaBeans {@link\n\t java.beans.Introspector Introspector}.\n\n\t @see #setMaxFileSize(String)\n\t*/\n\tpublic void setMaximumFileSize(long maxFileSize) {\n\t\tthis.maxFileSize = maxFileSize;\n\t}\n\n\t/**\n\t Set the maximum size that the output file is allowed to reach\n\t before being rolled over to backup files.\n\n\t

In configuration files, the MaxFileSize option takes an\n\t long integer in the range 0 - 2^63. You can specify the value\n\t with the suffixes \"KB\", \"MB\" or \"GB\" so that the integer is\n\t interpreted being expressed respectively in kilobytes, megabytes\n\t or gigabytes. For example, the value \"10KB\" will be interpreted\n\t as 10240.\n\t*/\n\tpublic void setMaxFileSize(String value) {\n\t maxFileSize = OptionConverter.toFileSize(value, maxFileSize + 1);\n\t}\n\n\tprotected void setQWForFiles(Writer writer) {\n\t qw = new CountingQuietWriter(writer, errorHandler);\n\t}\n\n\t//Taken verbatum from DailyRollingFileAppender\n\tint computeCheckPeriod() {\n\t\tRollingCalendar c = new RollingCalendar();\n\t\t// set sate to 1970-01-01 00:00:00 GMT\n\t\tDate epoch = new Date(0);\n\t\tif(datePattern != null) {\n\t\t\tfor(int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {\n\t\t\t\tString r0 = sdf.format(epoch);\n\t\t\t\tc.setType(i);\n\t\t\t\tDate next = new Date(c.getNextCheckMillis(epoch));\n\t\t\t\tString r1 = sdf.format(next);\n\t\t\t\t//LogLog.debug(\"Type = \"+i+\", r0 = \"+r0+\", r1 = \"+r1);\n\t\t\t\tif(r0 != null && r1 != null && !r0.equals(r1)) {\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn TOP_OF_TROUBLE; // Deliberately head for trouble...\n\t}\n\n\t//Now for the new stuff\n\t/**\n\t * Handles append time behavior for CompositeRollingAppender. This checks\n\t * if a roll over either by date (checked first) or time (checked second)\n\t * is need and then appends to the file last.\n\t*/\n\tprotected void subAppend(LoggingEvent event) {\n\n\t\tif (rollDate) {\n\t\t\tlong n = System.currentTimeMillis();\n\t\t\tif (n >= nextCheck) {\n\t\t\t\tnow.setTime(n);\n\t\t\t\tnextCheck = rc.getNextCheckMillis(now);\n\n\t\t\t\trollOverTime();\n\t\t\t}\n\t\t}\n\n\t\tif (rollSize) {\n\t\t\tif ((fileName != null) && ((CountingQuietWriter) qw).getCount() >= maxFileSize) {\n\t\t\t rollOverSize();\n\t\t\t}\n\t\t}\n\n\t\tsuper.subAppend(event);\n\t}\n\n\tpublic void setFile(String file)\n\t{\n\t\tbaseFileName = file.trim();\n\t\tfileName = file.trim();\n\t}\n\n\t/**\n\t * Creates and opens the file for logging. If staticLogFileName\n\t * is false then the fully qualified name is determined and used.\n\t */\n\tpublic synchronized void setFile(String fileName, boolean append) throws IOException {\n\t\tif (!staticLogFileName) {\n\t\t scheduledFilename = fileName = fileName.trim() + sdf.format(now);\n\t\t\tif (countDirection > 0) {\n\t\t\t\tscheduledFilename = fileName = fileName + '.' + (++curSizeRollBackups);\n\t\t\t}\n\t\t}\n\n\t\tsuper.setFile(fileName, append);\n\t\tif(append) {\n\t\t File f = new File(fileName);\n\t\t ((CountingQuietWriter) qw).setCount(f.length());\n\t\t}\n\t}\n\n\tpublic int getCountDirection() {\n\t\treturn countDirection;\n\t}\n\n\tpublic void setCountDirection(int direction) {\n\t\tcountDirection = direction;\n\t}\n\n\tpublic int getRollingStyle () {\n return rollingStyle;\n\t}\n\n\tpublic void setRollingStyle(int style) {\n\t rollingStyle = style;\n\t\tswitch (rollingStyle) {\n\t\t\tcase BY_SIZE:\n\t\t\t\t rollDate = false;\n\t\t\t\t rollSize = true;\n\t\t\t\t break;\n\t\t\tcase BY_DATE:\n\t\t\t\t rollDate = true;\n\t\t\t\t rollSize = false;\n\t\t\t\t break;\n\t\t\tcase BY_COMPOSITE:\n\t\t\t\t rollDate = true;\n\t\t\t\t rollSize = true;\n\t\t\t\t break;\n\t\t\tdefault:\n\t\t\t\terrorHandler.error(\"Invalid rolling Style, use 1 (by size only), 2 (by date only) or 3 (both)\");\n\t\t}\n\t}\n\n/*\n\tpublic void setRollingStyle(String style) {\n\t\tif (style == S_BY_SIZE) {\n\t\t rollingStyle = BY_SIZE;\n\t\t}\n\t\telse if (style == S_BY_DATE) {\n\t\t rollingStyle = BY_DATE;\n\t\t}\n\t\telse if (style == S_BY_COMPOSITE) {\n\t\t\trollingStyle = BY_COMPOSITE;\n\t\t}\n\t}\n*/\n\tpublic boolean getStaticLogFileName() {\n\t return staticLogFileName;\n\t}\n\n\tpublic void setStaticLogFileName(boolean s) {\n\t\tstaticLogFileName = s;\n\t}\n\n\tpublic void setStaticLogFileName(String value) {\n\t\tsetStaticLogFileName(OptionConverter.toBoolean(value, true));\n\t}\n\n\t/**\n\t * Initializes based on exisiting conditions at time of \n\t * activateOptions. The following is done:
\n\t *
\n\t *\tA) determine curSizeRollBackups
\n\t *\tB) determine curTimeRollBackups (not implemented)
\n\t *\tC) initiates a roll over if needed for crossing a date boundary since\n\t * the last run.\n\t */\n\tprotected void existingInit() {\n\n\t\tcurSizeRollBackups = 0;\n\t\tcurTimeRollBackups = 0;\n\n\t\t//part A starts here\n\t\tString filter;\n\t\tif (staticLogFileName || !rollDate) {\n\t\t\tfilter = baseFileName + \".*\";\n\t\t}\n\t\telse {\n\t\t\tfilter = scheduledFilename + \".*\";\n\t\t}\n\n\t\tFile f = new File(baseFileName);\n\t\tf = f.getParentFile();\n\t\tif (f == null)\n\t\t f = new File(\".\");\n\n\t\tLogLog.debug(\"Searching for existing files in: \" + f);\n\t\tString[] files = f.list();\n\n\t\tif (files != null) {\n\t\t\tfor (int i = 0; i < files.length; i++) {\n\t\t\t\tif (!files[i].startsWith(baseFileName))\n\t\t\t\t continue;\n\n\t\t\t\tint index = files[i].lastIndexOf(\".\");\n\n\t\t\t\tif (staticLogFileName) {\n\t\t\t\t int endLength = files[i].length() - index;\n\t\t\t\t if (baseFileName.length() + endLength != files[i].length()) {\n\t\t\t\t\t //file is probably scheduledFilename + .x so I don't care\n\t\t\t\t\t continue;\n\t\t\t\t }\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tint backup = Integer.parseInt(files[i].substring(index + 1, files[i].length()));\n\t\t\t\t\tLogLog.debug(\"From file: \" + files[i] + \" -> \" + backup);\n\t\t\t\t\tif (backup > curSizeRollBackups)\n\t\t\t\t\t curSizeRollBackups = backup;\n\t\t\t\t}\n\t\t\t\tcatch (Exception e) {\n\t\t\t\t\t//this happens when file.log -> file.log.yyyy-mm-dd which is normal\n\t\t\t\t\t//when staticLogFileName == false\n\t\t\t\t\tLogLog.debug(\"Encountered a backup file not ending in .x \" + files[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tLogLog.debug(\"curSizeRollBackups starts at: \" + curSizeRollBackups);\n\t\t//part A ends here\n\n\t\t//part B not yet implemented\n\n\t\t//part C\n\t\tif (staticLogFileName && rollDate) {\n\t\t\tFile old = new File(baseFileName);\n\t\t\tif (old.exists()) {\n\t\t\t\tDate last = new Date(old.lastModified());\n\t\t\t\tif (!(sdf.format(last).equals(sdf.format(now)))) {\n\t\t\t\t\tscheduledFilename = baseFileName + sdf.format(last);\n\t\t\t\t\tLogLog.debug(\"Initial roll over to: \" + scheduledFilename);\n\t\t\t\t\trollOverTime();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tLogLog.debug(\"curSizeRollBackups after rollOver at: \" + curSizeRollBackups);\n\t\t//part C ends here\n\n\t}\n\n\t/**\n\t * Sets initial conditions including date/time roll over information, first check,\n\t * scheduledFilename, and calls existingInit to initialize\n\t * the current # of backups.\n\t */\n\tpublic void activateOptions() {\n\n\t //REMOVE removed rollDate from boolean to enable Alex's change\n\t\tif(datePattern != null) {\n\t\t\tnow.setTime(System.currentTimeMillis());\n\t\t\tsdf = new SimpleDateFormat(datePattern);\n\t\t\tint type = computeCheckPeriod();\n\t\t\t//printPeriodicity(type);\n\t\t\trc.setType(type);\n\t\t\t//next line added as this removes the name check in rollOver\n\t\t\tnextCheck = rc.getNextCheckMillis(now);\n\t\t} else {\n\t\t\tif (rollDate)\n\t\t\t LogLog.error(\"Either DatePattern or rollingStyle options are not set for [\"+\n\t\t\t name+\"].\");\n\t\t}\n\n\t\texistingInit();\n\n\t\tsuper.activateOptions();\n\n\t\tif (rollDate && fileName != null && scheduledFilename == null)\n\t\t\tscheduledFilename = fileName + sdf.format(now);\n\t}\n\n\t/**\n\t Rollover the file(s) to date/time tagged file(s).\n\t Opens the new file (through setFile) and resets curSizeRollBackups.\n\t*/\n\tprotected void rollOverTime() {\n\n\t curTimeRollBackups++;\n\n\t\t//delete the old stuff here\n\n\t\tif (staticLogFileName) {\n\t\t\t/* Compute filename, but only if datePattern is specified */\n\t\t\tif (datePattern == null) {\n\t\t\t\terrorHandler.error(\"Missing DatePattern option in rollOver().\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t//is the new file name equivalent to the 'current' one\n\t\t\t//something has gone wrong if we hit this -- we should only\n\t\t\t//roll over if the new file will be different from the old\n\t\t\tString dateFormat = sdf.format(now);\n\t\t\tif (scheduledFilename.equals(fileName + dateFormat)) {\n\t\t\t\terrorHandler.error(\"Compare \" + scheduledFilename + \" : \" + fileName + dateFormat);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// close current file, and rename it to datedFilename\n\t\t\tthis.closeFile();\n\n\t\t\t//we may have to roll over a large number of backups here\n\t String from, to;\n\t\t\tfor (int i = 1; i <= curSizeRollBackups; i++) {\n\t\t\t\tfrom = fileName + '.' + i;\n\t\t\t\tto = scheduledFilename + '.' + i;\n\t\t\t\trollFile(from, to);\n\t }\n\n\t\t\trollFile(fileName, scheduledFilename);\n\t\t}\n\n\t\ttry {\n\t\t\t// This will also close the file. This is OK since multiple\n\t\t\t// close operations are safe.\n\t\t\tcurSizeRollBackups = 0; //We're cleared out the old date and are ready for the new\n\n\t\t\t//new scheduled name\n\t\t\tscheduledFilename = fileName + sdf.format(now);\n\t\t\tthis.setFile(baseFileName, false);\n\t\t}\n\t\tcatch(IOException e) {\n\t\t\terrorHandler.error(\"setFile(\"+fileName+\", false) call failed.\");\n\t\t}\n\n\t}\n\n\t/** Renames file from to file to. It\n\t * also checks for existence of target file and deletes if it does.\n\t */\n\tprotected static void rollFile(String from, String to) {\n\t\tFile target = new File(to);\n\t\tif (target.exists()) {\n\t\t\tLogLog.debug(\"deleting existing target file: \" + target);\n\t\t\ttarget.delete();\n\t\t}\n\n\t\tFile file = new File(from);\n\t\tfile.renameTo(target);\n\t\tLogLog.debug(from +\" -> \"+ to);\n\t}\n\n\t/** Delete's the specified file if it exists */\n\tprotected static void deleteFile(String fileName) {\n\t\tFile file = new File(fileName);\n\t\tif (file.exists()) {\n\t\t file.delete();\n\t\t}\n\t}\n\n\t/**\n\t Implements roll overs base on file size.\n\n\t

If the maximum number of size based backups is reached\n\t (curSizeRollBackups == maxSizeRollBackups\n\t If countDirection < 0, then files\n\t {File.1, ..., File.curSizeRollBackups -1}\n\t are renamed to {File.2, ...,\n\t File.curSizeRollBackups}.\t Moreover, File is\n\t renamed File.1 and closed.
\n\n\t A new file is created to receive further log output.\n\n\t

If maxSizeRollBackups is equal to zero, then the\n\t File is truncated with no backup files created.\n\n\t

If maxSizeRollBackups < 0, then File is\n\t renamed if needed and no files are deleted.\n\t*/\n\n\t// synchronization not necessary since doAppend is alreasy synched\n\tprotected void rollOverSize() {\n\t\tFile file;\n\n\t\tthis.closeFile(); // keep windows happy.\n\n\t\tLogLog.debug(\"rolling over count=\" + ((CountingQuietWriter) qw).getCount());\n\t\tLogLog.debug(\"maxSizeRollBackups = \" + maxSizeRollBackups);\n\t\tLogLog.debug(\"curSizeRollBackups = \" + curSizeRollBackups);\n\t\tLogLog.debug(\"countDirection = \" + countDirection);\n\n\t\t// If maxBackups <= 0, then there is no file renaming to be done.\n\t\tif (maxSizeRollBackups != 0) {\n\n\t\t\tif (countDirection < 0) {\n\t\t\t\t// Delete the oldest file, to keep Windows happy.\n\t\t\t\tif (curSizeRollBackups == maxSizeRollBackups) {\n\t\t\t\t deleteFile(fileName + '.' + maxSizeRollBackups);\n\t\t\t\t\tcurSizeRollBackups--;\n\t\t\t\t}\n\n\t\t\t\t// Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}\n\t\t\t\tfor (int i = curSizeRollBackups; i >= 1; i--) {\n\t\t\t\t\trollFile((fileName + \".\" + i), (fileName + '.' + (i + 1)));\n\t\t\t\t}\n\n\t\t\t\tcurSizeRollBackups++;\n\t\t\t\t// Rename fileName to fileName.1\n\t\t\t\trollFile(fileName, fileName + \".1\");\n\n\t\t\t} //REMOVE This code branching for Alexander Cerna's request\n\t\t\telse if (countDirection == 0) {\n\t\t\t\t//rollFile based on date pattern\n\t\t\t\tcurSizeRollBackups++;\n\t\t\t\tnow.setTime(System.currentTimeMillis());\n\t\t\t\tscheduledFilename = fileName + sdf.format(now);\n\t\t\t\trollFile(fileName, scheduledFilename);\n\t\t\t}\n\t\t\telse { //countDirection > 0\n\t\t\t\tif (curSizeRollBackups >= maxSizeRollBackups && maxSizeRollBackups > 0) {\n\t\t\t\t\t//delete the first and keep counting up.\n\t\t\t\t\tint oldestFileIndex = curSizeRollBackups - maxSizeRollBackups + 1;\n\t\t\t\t\tdeleteFile(fileName + '.' + oldestFileIndex);\n\t\t\t\t}\n\n\t\t\t\tif (staticLogFileName) {\n\t\t\t\t\tcurSizeRollBackups++;\n\t\t\t\t\trollFile(fileName, fileName + '.' + curSizeRollBackups);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// This will also close the file. This is OK since multiple\n\t\t\t// close operations are safe.\n\t\t\tthis.setFile(baseFileName, false);\n\t\t}\n\t\tcatch(IOException e) {\n\t\t\tLogLog.error(\"setFile(\"+fileName+\", false) call failed.\", e);\n\t\t}\n\t}\n\n}", "file_name": "CompositeRollingAppender.java", "human_label": "Delete the given file if it exists", "level": "slib_runnable", "lineno": "616", "name": "deleteFile", "oracle_context": "{ \"apis\" : \"[exists, delete]\", \"classes\" : \"[File]\", \"vars\" : \"[]\" }", "package": "org.apache.log4j", "project": "logging-log4j1-main" }, { "_id": "636767691a6d9265ec0181aa", "all_context": "{ \"class_level\" : \"import java.io.Closeable;\\nimport java.io.IOException;\\nimport java.lang.reflect.Array;\\nimport java.util.Arrays;\\nint INITIAL_HASH;\\nint MULTIPLIER;\\nString EMPTY_STRING;\\nString NULL_STRING;\\nString ARRAY_START;\\nString ARRAY_END;\\nString EMPTY_ARRAY;\\nString ARRAY_ELEMENT_SEPARATOR;\\nObjects();\\nisCompatibleWithThrowsClause(Throwable ex,Class[] declaredExceptions);\\nisArray(Object obj);\\nisEmpty(Object[] array);\\nisEmpty(byte[] array);\\ncontainsElement(Object[] array,Object element);\\ncontainsConstant(Enum[] enumValues,String constant);\\ncontainsConstant(Enum[] enumValues,String constant,boolean caseSensitive);\\ncaseInsensitiveValueOf(E[] enumValues,String constant);\\naddObjectToArray(A[] array,O obj);\\ntoObjectArray(Object source);\\nnullSafeEquals(Object o1,Object o2);\\nnullSafeHashCode(Object obj);\\nnullSafeHashCode(Object[] array);\\nnullSafeHashCode(boolean[] array);\\nnullSafeHashCode(byte[] array);\\nnullSafeHashCode(char[] array);\\nnullSafeHashCode(double[] array);\\nnullSafeHashCode(float[] array);\\nnullSafeHashCode(int[] array);\\nnullSafeHashCode(long[] array);\\nnullSafeHashCode(short[] array);\\nhashCode(boolean bool);\\nhashCode(double dbl);\\nhashCode(float flt);\\nhashCode(long lng);\\nidentityToString(Object obj);\\ngetIdentityHexString(Object obj);\\ngetDisplayString(Object obj);\\nnullSafeClassName(Object obj);\\nnullSafeToString(Object obj);\\nnullSafeToString(Object[] array);\\nnullSafeToString(boolean[] array);\\nnullSafeToString(byte[] array);\\nnullSafeToString(char[] array);\\nnullSafeToString(double[] array);\\nnullSafeToString(float[] array);\\nnullSafeToString(int[] array);\\nnullSafeToString(long[] array);\\nnullSafeToString(short[] array);\\nnullSafeClose(Closeable closeables);\\nisCheckedException(Throwable ex);\\n\", \"repo_level\" : \"\" }", "class_name": "Objects", "code": "public static int nullSafeHashCode(long[] array){\n if (array == null) {\n return 0;\n }\n int hash=INITIAL_HASH;\n int arraySize=array.length;\n for (int i=0; i < arraySize; i++) {\n hash=MULTIPLIER * hash + hashCode(array[i]);\n }\n return hash;\n}\n", "docstring": "/** \n * Return a hash code based on the contents of the specified array. If array is null, this method returns 0.\n * @param array the long array to obtain a hashcode\n * @return the long array's hashcode, which could be 0 if the array is null.\n */\n", "end_lineno": "493", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.lang.reflect.Array;\nimport java.util.Arrays;\n\npublic final class Objects {\n\n private Objects(){} //prevent instantiation\n\n private static final int INITIAL_HASH = 7;\n private static final int MULTIPLIER = 31;\n\n private static final String EMPTY_STRING = \"\";\n private static final String NULL_STRING = \"null\";\n private static final String ARRAY_START = \"{\";\n private static final String ARRAY_END = \"}\";\n private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;\n private static final String ARRAY_ELEMENT_SEPARATOR = \", \";\n\n /**\n * Return whether the given throwable is a checked exception:\n * that is, neither a RuntimeException nor an Error.\n *\n * @param ex the throwable to check\n * @return whether the throwable is a checked exception\n * @see java.lang.Exception\n * @see java.lang.RuntimeException\n * @see java.lang.Error\n */\n public static boolean isCheckedException(Throwable ex) {\n return !(ex instanceof RuntimeException || ex instanceof Error);\n }\n\n /**\n * Check whether the given exception is compatible with the exceptions\n * declared in a throws clause.\n *\n * @param ex the exception to checked\n * @param declaredExceptions the exceptions declared in the throws clause\n * @return whether the given exception is compatible\n */\n public static boolean isCompatibleWithThrowsClause(Throwable ex, Class[] declaredExceptions) {\n if (!isCheckedException(ex)) {\n return true;\n }\n if (declaredExceptions != null) {\n int i = 0;\n while (i < declaredExceptions.length) {\n if (declaredExceptions[i].isAssignableFrom(ex.getClass())) {\n return true;\n }\n i++;\n }\n }\n return false;\n }\n\n /**\n * Returns {@code true} if the specified argument is an Object or primitive array, {@code false} otherwise.\n *\n * @param obj the object instance to check\n * @return {@code true} if the specified argument is an Object or primitive array, {@code false} otherwise.\n */\n public static boolean isArray(Object obj) {\n return (obj != null && obj.getClass().isArray());\n }\n\n /**\n * {@code true} if the specified array is null or zero length, {@code false} if populated.\n *\n * @param array the array to check\n * @return {@code true} if the specified array is null or zero length, {@code false} if populated.\n */\n public static boolean isEmpty(Object[] array) {\n return (array == null || array.length == 0);\n }\n\n /**\n * Returns {@code true} if the specified byte array is null or of zero length, {@code false} if populated.\n *\n * @param array the byte array to check\n * @return {@code true} if the specified byte array is null or of zero length, {@code false} if populated.\n */\n public static boolean isEmpty(byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n * Check whether the given array contains the given element.\n *\n * @param array the array to check (may be null,\n * in which case the return value will always be false)\n * @param element the element to check for\n * @return whether the element has been found in the given array\n */\n public static boolean containsElement(Object[] array, Object element) {\n if (array == null) {\n return false;\n }\n for (Object arrayEle : array) {\n if (nullSafeEquals(arrayEle, element)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given array of enum constants contains a constant with the given name,\n * ignoring case when determining a match.\n *\n * @param enumValues the enum values to check, typically the product of a call to MyEnum.values()\n * @param constant the constant name to find (must not be null or empty string)\n * @return whether the constant has been found in the given array\n */\n public static boolean containsConstant(Enum[] enumValues, String constant) {\n return containsConstant(enumValues, constant, false);\n }\n\n /**\n * Check whether the given array of enum constants contains a constant with the given name.\n *\n * @param enumValues the enum values to check, typically the product of a call to MyEnum.values()\n * @param constant the constant name to find (must not be null or empty string)\n * @param caseSensitive whether case is significant in determining a match\n * @return whether the constant has been found in the given array\n */\n public static boolean containsConstant(Enum[] enumValues, String constant, boolean caseSensitive) {\n for (Enum candidate : enumValues) {\n if (caseSensitive ?\n candidate.toString().equals(constant) :\n candidate.toString().equalsIgnoreCase(constant)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Case insensitive alternative to {@link Enum#valueOf(Class, String)}.\n *\n * @param the concrete Enum type\n * @param enumValues the array of all Enum constants in question, usually per Enum.values()\n * @param constant the constant to get the enum value of\n * @return the enum constant of the specified enum type with the specified case-insensitive name\n * @throws IllegalArgumentException if the given constant is not found in the given array\n * of enum values. Use {@link #containsConstant(Enum[], String)} as a guard to\n * avoid this exception.\n */\n public static > E caseInsensitiveValueOf(E[] enumValues, String constant) {\n for (E candidate : enumValues) {\n if (candidate.toString().equalsIgnoreCase(constant)) {\n return candidate;\n }\n }\n throw new IllegalArgumentException(\n String.format(\"constant [%s] does not exist in enum type %s\",\n constant, enumValues.getClass().getComponentType().getName()));\n }\n\n /**\n * Append the given object to the given array, returning a new array\n * consisting of the input array contents plus the given object.\n *\n * @param array the array to append to (can be null)\n * @param the type of each element in the specified {@code array}\n * @param obj the object to append\n * @param the type of the specified object, which must equal to or extend the {@code <A>} type.\n * @return the new array (of the same component type; never null)\n */\n public static A[] addObjectToArray(A[] array, O obj) {\n Class compType = Object.class;\n if (array != null) {\n compType = array.getClass().getComponentType();\n } else if (obj != null) {\n compType = obj.getClass();\n }\n int newArrLength = (array != null ? array.length + 1 : 1);\n @SuppressWarnings(\"unchecked\")\n A[] newArr = (A[]) Array.newInstance(compType, newArrLength);\n if (array != null) {\n System.arraycopy(array, 0, newArr, 0, array.length);\n }\n newArr[newArr.length - 1] = obj;\n return newArr;\n }\n\n /**\n * Convert the given array (which may be a primitive array) to an\n * object array (if necessary of primitive wrapper objects).\n *

A null source value will be converted to an\n * empty Object array.\n *\n * @param source the (potentially primitive) array\n * @return the corresponding object array (never null)\n * @throws IllegalArgumentException if the parameter is not an array\n */\n public static Object[] toObjectArray(Object source) {\n if (source instanceof Object[]) {\n return (Object[]) source;\n }\n if (source == null) {\n return new Object[0];\n }\n if (!source.getClass().isArray()) {\n throw new IllegalArgumentException(\"Source is not an array: \" + source);\n }\n int length = Array.getLength(source);\n if (length == 0) {\n return new Object[0];\n }\n Class wrapperType = Array.get(source, 0).getClass();\n Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);\n for (int i = 0; i < length; i++) {\n newArray[i] = Array.get(source, i);\n }\n return newArray;\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for content-based equality/hash-code handling\n //---------------------------------------------------------------------\n\n /**\n * Determine if the given objects are equal, returning true\n * if both are null or false if only one is\n * null.\n *

Compares arrays with Arrays.equals, performing an equality\n * check based on the array elements rather than the array reference.\n *\n * @param o1 first Object to compare\n * @param o2 second Object to compare\n * @return whether the given objects are equal\n * @see java.util.Arrays#equals\n */\n public static boolean nullSafeEquals(Object o1, Object o2) {\n if (o1 == o2) {\n return true;\n }\n if (o1 == null || o2 == null) {\n return false;\n }\n if (o1.equals(o2)) {\n return true;\n }\n if (o1.getClass().isArray() && o2.getClass().isArray()) {\n if (o1 instanceof Object[] && o2 instanceof Object[]) {\n return Arrays.equals((Object[]) o1, (Object[]) o2);\n }\n if (o1 instanceof boolean[] && o2 instanceof boolean[]) {\n return Arrays.equals((boolean[]) o1, (boolean[]) o2);\n }\n if (o1 instanceof byte[] && o2 instanceof byte[]) {\n return Arrays.equals((byte[]) o1, (byte[]) o2);\n }\n if (o1 instanceof char[] && o2 instanceof char[]) {\n return Arrays.equals((char[]) o1, (char[]) o2);\n }\n if (o1 instanceof double[] && o2 instanceof double[]) {\n return Arrays.equals((double[]) o1, (double[]) o2);\n }\n if (o1 instanceof float[] && o2 instanceof float[]) {\n return Arrays.equals((float[]) o1, (float[]) o2);\n }\n if (o1 instanceof int[] && o2 instanceof int[]) {\n return Arrays.equals((int[]) o1, (int[]) o2);\n }\n if (o1 instanceof long[] && o2 instanceof long[]) {\n return Arrays.equals((long[]) o1, (long[]) o2);\n }\n if (o1 instanceof short[] && o2 instanceof short[]) {\n return Arrays.equals((short[]) o1, (short[]) o2);\n }\n }\n return false;\n }\n\n /**\n * Return as hash code for the given object; typically the value of\n * {@link Object#hashCode()}. If the object is an array,\n * this method will delegate to any of the nullSafeHashCode\n * methods for arrays in this class. If the object is null,\n * this method returns 0.\n *\n * @see #nullSafeHashCode(Object[])\n * @see #nullSafeHashCode(boolean[])\n * @see #nullSafeHashCode(byte[])\n * @see #nullSafeHashCode(char[])\n * @see #nullSafeHashCode(double[])\n * @see #nullSafeHashCode(float[])\n * @see #nullSafeHashCode(int[])\n * @see #nullSafeHashCode(long[])\n * @see #nullSafeHashCode(short[])\n * @param obj the object to use for obtaining a hashcode\n * @return the object's hashcode, which could be 0 if the object is null.\n */\n public static int nullSafeHashCode(Object obj) {\n if (obj == null) {\n return 0;\n }\n if (obj.getClass().isArray()) {\n if (obj instanceof Object[]) {\n return nullSafeHashCode((Object[]) obj);\n }\n if (obj instanceof boolean[]) {\n return nullSafeHashCode((boolean[]) obj);\n }\n if (obj instanceof byte[]) {\n return nullSafeHashCode((byte[]) obj);\n }\n if (obj instanceof char[]) {\n return nullSafeHashCode((char[]) obj);\n }\n if (obj instanceof double[]) {\n return nullSafeHashCode((double[]) obj);\n }\n if (obj instanceof float[]) {\n return nullSafeHashCode((float[]) obj);\n }\n if (obj instanceof int[]) {\n return nullSafeHashCode((int[]) obj);\n }\n if (obj instanceof long[]) {\n return nullSafeHashCode((long[]) obj);\n }\n if (obj instanceof short[]) {\n return nullSafeHashCode((short[]) obj);\n }\n }\n return obj.hashCode();\n }\n\n /**\n * Return a hash code based on the contents of the specified array.\n * If array is null, this method returns 0.\n * @param array the array to obtain a hashcode\n * @return the array's hashcode, which could be 0 if the array is null.\n */\n public static int nullSafeHashCode(Object[] array) {\n if (array == null) {\n return 0;\n }\n int hash = INITIAL_HASH;\n int arraySize = array.length;\n for (int i = 0; i < arraySize; i++) {\n hash = MULTIPLIER * hash + nullSafeHashCode(array[i]);\n }\n return hash;\n }\n\n /**\n * Return a hash code based on the contents of the specified array.\n * If array is null, this method returns 0.\n * @param array the boolean array to obtain a hashcode\n * @return the boolean array's hashcode, which could be 0 if the array is null.\n */\n public static int nullSafeHashCode(boolean[] array) {\n if (array == null) {\n return 0;\n }\n int hash = INITIAL_HASH;\n int arraySize = array.length;\n for (int i = 0; i < arraySize; i++) {\n hash = MULTIPLIER * hash + hashCode(array[i]);\n }\n return hash;\n }\n\n /**\n * Return a hash code based on the contents of the specified array.\n * If array is null, this method returns 0.\n * @param array the byte array to obtain a hashcode\n * @return the byte array's hashcode, which could be 0 if the array is null.\n */\n public static int nullSafeHashCode(byte[] array) {\n if (array == null) {\n return 0;\n }\n int hash = INITIAL_HASH;\n int arraySize = array.length;\n for (int i = 0; i < arraySize; i++) {\n hash = MULTIPLIER * hash + array[i];\n }\n return hash;\n }\n\n /**\n * Return a hash code based on the contents of the specified array.\n * If array is null, this method returns 0.\n * @param array the char array to obtain a hashcode\n * @return the char array's hashcode, which could be 0 if the array is null.\n */\n public static int nullSafeHashCode(char[] array) {\n if (array == null) {\n return 0;\n }\n int hash = INITIAL_HASH;\n int arraySize = array.length;\n for (int i = 0; i < arraySize; i++) {\n hash = MULTIPLIER * hash + array[i];\n }\n return hash;\n }\n\n /**\n * Return a hash code based on the contents of the specified array.\n * If array is null, this method returns 0.\n * @param array the double array to obtain a hashcode\n * @return the double array's hashcode, which could be 0 if the array is null.\n */\n public static int nullSafeHashCode(double[] array) {\n if (array == null) {\n return 0;\n }\n int hash = INITIAL_HASH;\n int arraySize = array.length;\n for (int i = 0; i < arraySize; i++) {\n hash = MULTIPLIER * hash + hashCode(array[i]);\n }\n return hash;\n }\n\n /**\n * Return a hash code based on the contents of the specified array.\n * If array is null, this method returns 0.\n * @param array the float array to obtain a hashcode\n * @return the float array's hashcode, which could be 0 if the array is null.\n */\n public static int nullSafeHashCode(float[] array) {\n if (array == null) {\n return 0;\n }\n int hash = INITIAL_HASH;\n int arraySize = array.length;\n for (int i = 0; i < arraySize; i++) {\n hash = MULTIPLIER * hash + hashCode(array[i]);\n }\n return hash;\n }\n\n /**\n * Return a hash code based on the contents of the specified array.\n * If array is null, this method returns 0.\n * @param array the int array to obtain a hashcode\n * @return the int array's hashcode, which could be 0 if the array is null.\n */\n public static int nullSafeHashCode(int[] array) {\n if (array == null) {\n return 0;\n }\n int hash = INITIAL_HASH;\n int arraySize = array.length;\n for (int i = 0; i < arraySize; i++) {\n hash = MULTIPLIER * hash + array[i];\n }\n return hash;\n }\n\n /**\n * Return a hash code based on the contents of the specified array.\n * If array is null, this method returns 0.\n * @param array the long array to obtain a hashcode\n * @return the long array's hashcode, which could be 0 if the array is null.\n */\n public static int nullSafeHashCode(long[] array) {\n if (array == null) {\n return 0;\n }\n int hash = INITIAL_HASH;\n int arraySize = array.length;\n for (int i = 0; i < arraySize; i++) {\n hash = MULTIPLIER * hash + hashCode(array[i]);\n }\n return hash;\n }\n\n /**\n * Return a hash code based on the contents of the specified array.\n * If array is null, this method returns 0.\n * @param array the short array to obtain a hashcode\n * @return the short array's hashcode, which could be 0 if the array is null.\n */\n public static int nullSafeHashCode(short[] array) {\n if (array == null) {\n return 0;\n }\n int hash = INITIAL_HASH;\n int arraySize = array.length;\n for (int i = 0; i < arraySize; i++) {\n hash = MULTIPLIER * hash + array[i];\n }\n return hash;\n }\n\n /**\n * Return the same value as {@link Boolean#hashCode()}.\n *\n * @param bool the boolean to get a hashcode\n * @return the same value as {@link Boolean#hashCode()}.\n * @see Boolean#hashCode()\n */\n public static int hashCode(boolean bool) {\n return bool ? 1231 : 1237;\n }\n\n /**\n * Return the same value as {@link Double#hashCode()}.\n *\n * @param dbl the double to get a hashcode\n * @return the same value as {@link Double#hashCode()}.\n * @see Double#hashCode()\n */\n public static int hashCode(double dbl) {\n long bits = Double.doubleToLongBits(dbl);\n return hashCode(bits);\n }\n\n /**\n * Return the same value as {@link Float#hashCode()}.\n *\n * @param flt the float to get a hashcode\n * @return the same value as {@link Float#hashCode()}.\n * @see Float#hashCode()\n */\n public static int hashCode(float flt) {\n return Float.floatToIntBits(flt);\n }\n\n /**\n * Return the same value as {@link Long#hashCode()}.\n *\n * @param lng the long to get a hashcode\n * @return the same value as {@link Long#hashCode()}.\n * @see Long#hashCode()\n */\n public static int hashCode(long lng) {\n return (int) (lng ^ (lng >>> 32));\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for toString output\n //---------------------------------------------------------------------\n\n /**\n * Return a String representation of an object's overall identity.\n *\n * @param obj the object (which may be null).\n * @return the object's identity as String representation, or an empty String if the object was null.\n */\n public static String identityToString(Object obj) {\n if (obj == null) {\n return EMPTY_STRING;\n }\n return obj.getClass().getName() + \"@\" + getIdentityHexString(obj);\n }\n\n /**\n * Return a hex String form of an object's identity hash code.\n *\n * @param obj the object\n * @return the object's identity code in hex notation\n */\n public static String getIdentityHexString(Object obj) {\n return Integer.toHexString(System.identityHashCode(obj));\n }\n\n /**\n * Return a content-based String representation if obj is\n * not null; otherwise returns an empty String.\n *

Differs from {@link #nullSafeToString(Object)} in that it returns\n * an empty String rather than \"null\" for a null value.\n *\n * @param obj the object to build a display String for\n * @return a display String representation of obj\n * @see #nullSafeToString(Object)\n */\n public static String getDisplayString(Object obj) {\n if (obj == null) {\n return EMPTY_STRING;\n }\n return nullSafeToString(obj);\n }\n\n /**\n * Determine the class name for the given object.\n *

Returns \"null\" if obj is null.\n *\n * @param obj the object to introspect (may be null)\n * @return the corresponding class name\n */\n public static String nullSafeClassName(Object obj) {\n return (obj != null ? obj.getClass().getName() : NULL_STRING);\n }\n\n /**\n * Return a String representation of the specified Object.\n *

Builds a String representation of the contents in case of an array.\n * Returns \"null\" if obj is null.\n *\n * @param obj the object to build a String representation for\n * @return a String representation of obj\n */\n public static String nullSafeToString(Object obj) {\n if (obj == null) {\n return NULL_STRING;\n }\n if (obj instanceof String) {\n return (String) obj;\n }\n if (obj instanceof Object[]) {\n return nullSafeToString((Object[]) obj);\n }\n if (obj instanceof boolean[]) {\n return nullSafeToString((boolean[]) obj);\n }\n if (obj instanceof byte[]) {\n return nullSafeToString((byte[]) obj);\n }\n if (obj instanceof char[]) {\n return nullSafeToString((char[]) obj);\n }\n if (obj instanceof double[]) {\n return nullSafeToString((double[]) obj);\n }\n if (obj instanceof float[]) {\n return nullSafeToString((float[]) obj);\n }\n if (obj instanceof int[]) {\n return nullSafeToString((int[]) obj);\n }\n if (obj instanceof long[]) {\n return nullSafeToString((long[]) obj);\n }\n if (obj instanceof short[]) {\n return nullSafeToString((short[]) obj);\n }\n String str = obj.toString();\n return (str != null ? str : EMPTY_STRING);\n }\n\n /**\n * Return a String representation of the contents of the specified array.\n *

The String representation consists of a list of the array's elements,\n * enclosed in curly braces (\"{}\"). Adjacent elements are separated\n * by the characters \", \" (a comma followed by a space). Returns\n * \"null\" if array is null.\n *\n * @param array the array to build a String representation for\n * @return a String representation of array\n */\n public static String nullSafeToString(Object[] array) {\n if (array == null) {\n return NULL_STRING;\n }\n int length = array.length;\n if (length == 0) {\n return EMPTY_ARRAY;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < length; i++) {\n if (i == 0) {\n sb.append(ARRAY_START);\n } else {\n sb.append(ARRAY_ELEMENT_SEPARATOR);\n }\n sb.append(String.valueOf(array[i]));\n }\n sb.append(ARRAY_END);\n return sb.toString();\n }\n\n /**\n * Return a String representation of the contents of the specified array.\n *

The String representation consists of a list of the array's elements,\n * enclosed in curly braces (\"{}\"). Adjacent elements are separated\n * by the characters \", \" (a comma followed by a space). Returns\n * \"null\" if array is null.\n *\n * @param array the array to build a String representation for\n * @return a String representation of array\n */\n public static String nullSafeToString(boolean[] array) {\n if (array == null) {\n return NULL_STRING;\n }\n int length = array.length;\n if (length == 0) {\n return EMPTY_ARRAY;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < length; i++) {\n if (i == 0) {\n sb.append(ARRAY_START);\n } else {\n sb.append(ARRAY_ELEMENT_SEPARATOR);\n }\n\n sb.append(array[i]);\n }\n sb.append(ARRAY_END);\n return sb.toString();\n }\n\n /**\n * Return a String representation of the contents of the specified array.\n *

The String representation consists of a list of the array's elements,\n * enclosed in curly braces (\"{}\"). Adjacent elements are separated\n * by the characters \", \" (a comma followed by a space). Returns\n * \"null\" if array is null.\n *\n * @param array the array to build a String representation for\n * @return a String representation of array\n */\n public static String nullSafeToString(byte[] array) {\n if (array == null) {\n return NULL_STRING;\n }\n int length = array.length;\n if (length == 0) {\n return EMPTY_ARRAY;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < length; i++) {\n if (i == 0) {\n sb.append(ARRAY_START);\n } else {\n sb.append(ARRAY_ELEMENT_SEPARATOR);\n }\n sb.append(array[i]);\n }\n sb.append(ARRAY_END);\n return sb.toString();\n }\n\n /**\n * Return a String representation of the contents of the specified array.\n *

The String representation consists of a list of the array's elements,\n * enclosed in curly braces (\"{}\"). Adjacent elements are separated\n * by the characters \", \" (a comma followed by a space). Returns\n * \"null\" if array is null.\n *\n * @param array the array to build a String representation for\n * @return a String representation of array\n */\n public static String nullSafeToString(char[] array) {\n if (array == null) {\n return NULL_STRING;\n }\n int length = array.length;\n if (length == 0) {\n return EMPTY_ARRAY;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < length; i++) {\n if (i == 0) {\n sb.append(ARRAY_START);\n } else {\n sb.append(ARRAY_ELEMENT_SEPARATOR);\n }\n sb.append(\"'\").append(array[i]).append(\"'\");\n }\n sb.append(ARRAY_END);\n return sb.toString();\n }\n\n /**\n * Return a String representation of the contents of the specified array.\n *

The String representation consists of a list of the array's elements,\n * enclosed in curly braces (\"{}\"). Adjacent elements are separated\n * by the characters \", \" (a comma followed by a space). Returns\n * \"null\" if array is null.\n *\n * @param array the array to build a String representation for\n * @return a String representation of array\n */\n public static String nullSafeToString(double[] array) {\n if (array == null) {\n return NULL_STRING;\n }\n int length = array.length;\n if (length == 0) {\n return EMPTY_ARRAY;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < length; i++) {\n if (i == 0) {\n sb.append(ARRAY_START);\n } else {\n sb.append(ARRAY_ELEMENT_SEPARATOR);\n }\n\n sb.append(array[i]);\n }\n sb.append(ARRAY_END);\n return sb.toString();\n }\n\n /**\n * Return a String representation of the contents of the specified array.\n *

The String representation consists of a list of the array's elements,\n * enclosed in curly braces (\"{}\"). Adjacent elements are separated\n * by the characters \", \" (a comma followed by a space). Returns\n * \"null\" if array is null.\n *\n * @param array the array to build a String representation for\n * @return a String representation of array\n */\n public static String nullSafeToString(float[] array) {\n if (array == null) {\n return NULL_STRING;\n }\n int length = array.length;\n if (length == 0) {\n return EMPTY_ARRAY;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < length; i++) {\n if (i == 0) {\n sb.append(ARRAY_START);\n } else {\n sb.append(ARRAY_ELEMENT_SEPARATOR);\n }\n\n sb.append(array[i]);\n }\n sb.append(ARRAY_END);\n return sb.toString();\n }\n\n /**\n * Return a String representation of the contents of the specified array.\n *

The String representation consists of a list of the array's elements,\n * enclosed in curly braces (\"{}\"). Adjacent elements are separated\n * by the characters \", \" (a comma followed by a space). Returns\n * \"null\" if array is null.\n *\n * @param array the array to build a String representation for\n * @return a String representation of array\n */\n public static String nullSafeToString(int[] array) {\n if (array == null) {\n return NULL_STRING;\n }\n int length = array.length;\n if (length == 0) {\n return EMPTY_ARRAY;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < length; i++) {\n if (i == 0) {\n sb.append(ARRAY_START);\n } else {\n sb.append(ARRAY_ELEMENT_SEPARATOR);\n }\n sb.append(array[i]);\n }\n sb.append(ARRAY_END);\n return sb.toString();\n }\n\n /**\n * Return a String representation of the contents of the specified array.\n *

The String representation consists of a list of the array's elements,\n * enclosed in curly braces (\"{}\"). Adjacent elements are separated\n * by the characters \", \" (a comma followed by a space). Returns\n * \"null\" if array is null.\n *\n * @param array the array to build a String representation for\n * @return a String representation of array\n */\n public static String nullSafeToString(long[] array) {\n if (array == null) {\n return NULL_STRING;\n }\n int length = array.length;\n if (length == 0) {\n return EMPTY_ARRAY;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < length; i++) {\n if (i == 0) {\n sb.append(ARRAY_START);\n } else {\n sb.append(ARRAY_ELEMENT_SEPARATOR);\n }\n sb.append(array[i]);\n }\n sb.append(ARRAY_END);\n return sb.toString();\n }\n\n /**\n * Return a String representation of the contents of the specified array.\n *

The String representation consists of a list of the array's elements,\n * enclosed in curly braces (\"{}\"). Adjacent elements are separated\n * by the characters \", \" (a comma followed by a space). Returns\n * \"null\" if array is null.\n *\n * @param array the array to build a String representation for\n * @return a String representation of array\n */\n public static String nullSafeToString(short[] array) {\n if (array == null) {\n return NULL_STRING;\n }\n int length = array.length;\n if (length == 0) {\n return EMPTY_ARRAY;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < length; i++) {\n if (i == 0) {\n sb.append(ARRAY_START);\n } else {\n sb.append(ARRAY_ELEMENT_SEPARATOR);\n }\n sb.append(array[i]);\n }\n sb.append(ARRAY_END);\n return sb.toString();\n }\n\n public static void nullSafeClose(Closeable... closeables) {\n if (closeables == null) {\n return;\n }\n\n for (Closeable closeable : closeables) {\n if (closeable != null) {\n try {\n closeable.close();\n } catch (IOException e) {\n //Ignore the exception during close.\n }\n }\n }\n }\n}\n", "file_name": "Objects.java", "human_label": "Compute the hash code of the whole array, by accumulating the multiplication of each element hash code and the MULTIPLIER.", "level": "class_runnable", "lineno": "477", "name": "nullSafeHashCode", "oracle_context": "{ \"apis\" : \"[hashCode]\", \"classes\" : \"[]\", \"vars\" : \"[length, INITIAL_HASH, MULTIPLIER]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636767441a6d9265ec017cc1", "all_context": "{ \"class_level\" : \"import java.util.*;\\nTreeNode virtualRoot;\\nint modCount;\\nTreeNodeIterator iterator;\\nTreeNode nextNode;\\nint expectedModCount;\\nT value;\\nTreeNode parent;\\nTreeNode left;\\nTreeNode right;\\nTreeNode successor;\\nTreeNode predecessor;\\nTreeNode subtreeMin;\\nTreeNode subtreeMax;\\nint height;\\nint subtreeSize;\\nAVLTree();\\nAVLTree(TreeNode root);\\naddMaxNode(TreeNode newMax);\\naddMin(T value);\\naddMinNode(TreeNode newMin);\\nsplitAfter(TreeNode node);\\nsplitBefore(TreeNode node);\\nmergeAfter(AVLTree tree);\\nmergeBefore(AVLTree tree);\\nremoveMin();\\nremoveMax();\\ngetRoot();\\nsuccessor(TreeNode node);\\npredecessor(TreeNode node);\\ngetMin();\\ngetMax();\\nisEmpty();\\nclear();\\ngetSize();\\nmakeRoot(TreeNode node);\\nsplit(TreeNode left,TreeNode right,TreeNode p,boolean leftMove);\\nmerge(TreeNode junctionNode,TreeNode left,TreeNode right);\\nswap(AVLTree tree);\\nrotateRight(TreeNode node);\\nrotateLeft(TreeNode node);\\nbalance(TreeNode node);\\nbalance(TreeNode node,TreeNode stop);\\nbalanceNode(TreeNode node);\\nregisterModification();\\ntoString();\\niterator();\\nnodeIterator();\\nTreeValuesIterator();\\nhasNext();\\nnext();\\nTreeNodeIterator();\\ncheckForComodification();\\nTreeNode(T value);\\ngetValue();\\ngetSubtreeMin();\\ngetSubtreeMax();\\ngetTreeMin();\\ngetTreeMax();\\ngetParent();\\ngetLeft();\\ngetRight();\\ngetHeight();\\ngetSubtreeSize();\\nreset();\\ngetRightHeight();\\ngetLeftHeight();\\ngetLeftSubtreeSize();\\ngetRightSubtreeSize();\\nupdateHeightAndSubtreeSize();\\nisLeftDoubleHeavy();\\nisRightDoubleHeavy();\\nisLeftHeavy();\\nisRightHeavy();\\nisLeftChild();\\nisRightChild();\\ngetSuccessor();\\ngetPredecessor();\\nsetSuccessor(TreeNode node);\\nsetPredecessor(TreeNode node);\\nsetLeftChild(TreeNode node);\\nsetRightChild(TreeNode node);\\nsubstituteChild(TreeNode prevChild,TreeNode newChild);\\naddMax(T value);\\n\", \"repo_level\" : \"\" }", "class_name": "AVLTree", "code": "private TreeNode rotateRight(TreeNode node){\n TreeNode left=node.left;\n left.parent=null;\n node.setLeftChild(left.right);\n left.setRightChild(node);\n node.updateHeightAndSubtreeSize();\n left.updateHeightAndSubtreeSize();\n return left;\n}\n", "docstring": "/** \n * Performs a right node rotation.\n * @param node a node to rotate\n * @return a new parent of the {@code node}\n */\n", "end_lineno": "506", "file_content": "/*\n * (C) Copyright 2020-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.util;\n\nimport java.util.*;\n\n/**\n * Implementation of the AVL tree data\n * structure. Note: this tree doesn't use key comparisons, so this tree can't be used as a\n * binary search tree. This implies that the same key can be added to this tree multiple times.\n *

\n * AVL tree is a self-balancing binary tree data structure. In an AVL tree, the heights of two child\n * subtrees differ by at most one. This ensures that the height of the tree is $\\mathcal{O}(\\log n)$\n * where $n$ is the number of elements in the tree. Also this tree doesn't support key comparisons,\n * it does define an element order. As a result, this tree can be used to query node\n * successor/predecessor.\n *

\n * Subtree query means that the result is being computed only on the subtree nodes. This tree\n * supports the following operations:\n *

    \n *
  • Min/max insertion and deletion in $\\mathcal{O}(\\log n)$ time
  • \n *
  • Subtree min/max queries in $\\mathcal{O}(1)$ time
  • \n *
  • Node successor/predecessor queries in $\\mathcal{O}(1)$ time
  • \n *
  • Tree split in $\\mathcal{O}(\\log n)$ time
  • \n *
  • Tree merge in $\\mathcal{O}(\\log n)$ time
  • \n *
\n *

\n * This implementation gives users access to the tree nodes which hold the inserted elements. The\n * user is able to store the tree nodes references but isn't able to modify them.\n *\n * @param the key data type\n * @author Timofey Chudakov\n */\npublic class AVLTree\n implements\n Iterable\n{\n /**\n * An auxiliary node which's always present in a tree and doesn't contain any data.\n */\n private TreeNode virtualRoot = new TreeNode<>(null);\n /**\n * Modification tracker\n */\n private int modCount = 0;\n\n /**\n * Constructs an empty tree\n */\n public AVLTree()\n {\n }\n\n /**\n * Constructor for internal usage\n *\n * @param root the root of the newly create tree\n */\n private AVLTree(TreeNode root)\n {\n makeRoot(root);\n }\n\n /**\n * Adds {@code value} as a maximum element to this tree. The running time of this method is\n * $\\mathcal{O}(\\log n)$\n *\n * @param value a value to add as a tree max\n * @return a tree node holding the {@code value}\n */\n public TreeNode addMax(T value)\n {\n TreeNode newMax = new TreeNode<>(value);\n addMaxNode(newMax);\n return newMax;\n }\n\n /**\n * Adds the {@code newMax} as a maximum node to this tree.\n *\n * @param newMax a node to add as a tree max\n */\n public void addMaxNode(TreeNode newMax)\n {\n registerModification();\n\n if (isEmpty()) {\n virtualRoot.left = newMax;\n newMax.parent = virtualRoot;\n } else {\n TreeNode max = getMax();\n max.setRightChild(newMax);\n balance(max);\n }\n }\n\n /**\n * Adds the {@code value} as a minimum element to this tree\n *\n * @param value a value to add as a tree min\n * @return a tree node holding the {@code value}\n */\n public TreeNode addMin(T value)\n {\n TreeNode newMin = new TreeNode<>(value);\n addMinNode(newMin);\n return newMin;\n }\n\n /**\n * Adds the {@code newMin} as a minimum node to this tree\n *\n * @param newMin a node to add as a tree min\n */\n public void addMinNode(TreeNode newMin)\n {\n registerModification();\n if (isEmpty()) {\n virtualRoot.left = newMin;\n newMin.parent = virtualRoot;\n } else {\n TreeNode min = getMin();\n min.setLeftChild(newMin);\n balance(min);\n }\n }\n\n /**\n * Splits the tree into two parts.\n *

\n * The first part contains the nodes which are smaller than or equal to the {@code node}. The\n * first part stays in this tree. The second part contains the nodes which are strictly greater\n * than the {@code node}. The second part is returned as a tree.\n *\n * @param node a separating node\n * @return a tree containing the nodes which are strictly greater than the {@code node}\n */\n public AVLTree splitAfter(TreeNode node)\n {\n registerModification();\n\n TreeNode parent = node.parent;\n boolean nextMove = node.isLeftChild();\n TreeNode left = node.left;\n TreeNode right = node.right;\n\n node.parent.substituteChild(node, null);\n\n node.reset();\n\n if (left != null) {\n left.parent = null;\n }\n if (right != null) {\n right.parent = null;\n }\n\n if (left == null) {\n left = node;\n } else {\n // insert node as a left subtree max\n TreeNode t = left;\n while (t.right != null) {\n t = t.right;\n }\n t.setRightChild(node);\n\n while (t != left) {\n TreeNode p = t.parent;\n p.substituteChild(t, balanceNode(t));\n t = p;\n }\n left = balanceNode(left);\n\n }\n return split(left, right, parent, nextMove);\n }\n\n /**\n * Splits the tree into two parts.\n *

\n * The first part contains the nodes which are smaller than the {@code node}. The first part\n * stays in this tree. The second part contains the nodes which are greater than or equal to the\n * {@code node}. The second part is returned as a tree.\n *\n * @param node a separating node\n * @return a tree containing the nodes which are greater than or equal to the {@code node}\n */\n public AVLTree splitBefore(TreeNode node)\n {\n registerModification();\n\n TreeNode predecessor = predecessor(node);\n if (predecessor == null) {\n // node is a minimum node\n AVLTree tree = new AVLTree<>();\n swap(tree);\n return tree;\n }\n return splitAfter(predecessor);\n }\n\n /**\n * Append the nodes in the {@code tree} after the nodes in this tree.\n *

\n * The result of this operation is stored in this tree.\n *\n * @param tree a tree to append\n */\n public void mergeAfter(AVLTree tree)\n {\n registerModification();\n if (tree.isEmpty()) {\n return;\n } else if (tree.getSize() == 1) {\n addMaxNode(tree.removeMin());\n return;\n }\n\n TreeNode junctionNode = tree.removeMin();\n TreeNode treeRoot = tree.getRoot();\n tree.clear();\n\n makeRoot(merge(junctionNode, getRoot(), treeRoot));\n }\n\n /**\n * Prepends the nodes in the {@code tree} before the nodes in this tree.\n *

\n * The result of this operation is stored in this tree.\n *\n * @param tree a tree to prepend\n */\n public void mergeBefore(AVLTree tree)\n {\n registerModification();\n\n tree.mergeAfter(this);\n\n swap(tree);\n }\n\n /**\n * Removes the minimum node in this tree. Returns {@code null} if this tree is empty\n *\n * @return the removed node or {@code null} if this tree is empty\n */\n public TreeNode removeMin()\n {\n registerModification();\n\n if (isEmpty()) {\n return null;\n }\n TreeNode min = getMin();\n // min.parent != null\n if (min.parent == virtualRoot) {\n makeRoot(min.right);\n } else {\n min.parent.setLeftChild(min.right);\n }\n\n balance(min.parent);\n\n return min;\n }\n\n /**\n * Removes the maximum node in this tree. Returns {@code null} if this tree is empty\n *\n * @return the removed node or {@code null} if this tree is empty\n */\n public TreeNode removeMax()\n {\n registerModification();\n if (isEmpty()) {\n return null;\n }\n TreeNode max = getMax();\n if (max.parent == virtualRoot) {\n makeRoot(max.left);\n } else {\n max.parent.setRightChild(max.left);\n }\n balance(max.parent);\n return max;\n }\n\n /**\n * Returns the root of this tree or null if this tree is empty.\n *\n * @return the root of this tree or null if this tree is empty.\n */\n public TreeNode getRoot()\n {\n return virtualRoot.left;\n }\n\n /**\n * Returns the node following the {@code node} in the order defined by this tree. Returns null\n * if the {@code node} is the maximum node in the tree.\n *\n * @param node a node to compute successor of\n * @return the successor of the {@code node}\n */\n public TreeNode successor(TreeNode node)\n {\n return node.successor;\n }\n\n /**\n * Returns the node, which is before the {@code node} in the order defined by this tree. Returns\n * null if the {@code node} is the minimum node in the tree.\n *\n * @param node a node to compute predecessor of\n * @return the predecessor of the {@code node}\n */\n public TreeNode predecessor(TreeNode node)\n {\n return node.predecessor;\n }\n\n /**\n * Returns the minimum node in this tree or null if the tree is empty.\n *\n * @return the minimum node in this tree or null if the tree is empty.\n */\n public TreeNode getMin()\n {\n return getRoot() == null ? null : getRoot().getSubtreeMin();\n }\n\n /**\n * Returns the maximum node in this tree or null if the tree is empty.\n *\n * @return the maximum node in this tree or null if the tree is empty.\n */\n public TreeNode getMax()\n {\n return getRoot() == null ? null : getRoot().getSubtreeMax();\n }\n\n /**\n * Check if this tree is empty\n *\n * @return {@code true} if this tree is empty, {@code false otherwise}\n */\n public boolean isEmpty()\n {\n return getRoot() == null;\n }\n\n /**\n * Removes all nodes from this tree.\n *

\n * Note: the memory allocated for the tree structure won't be deallocated until there are\n * active external referenced to the nodes of this tree.\n */\n public void clear()\n {\n registerModification();\n\n virtualRoot.left = null;\n }\n\n /**\n * Returns the size of this tree\n *\n * @return the size of this tree\n */\n public int getSize()\n {\n return virtualRoot.left == null ? 0 : virtualRoot.left.subtreeSize;\n }\n\n /**\n * Makes the {@code node} the root of this tree\n *\n * @param node a new root of this tree\n */\n private void makeRoot(TreeNode node)\n {\n virtualRoot.left = node;\n if (node != null) {\n node.subtreeMax.successor = null;\n node.subtreeMin.predecessor = null;\n node.parent = virtualRoot;\n }\n }\n\n /**\n * Traverses the tree up until the virtual root and splits it into two parts.\n *

\n * The algorithm is described in Donald E. Knuth. The art of computer programming. Second\n * Edition. Volume 3 / Sorting and Searching, p. 474.\n *\n * @param left a left subtree\n * @param right a right subtree\n * @param p next parent node\n * @param leftMove {@code true} if we're moving from the left child, {@code false} otherwise.\n * @return the resulting right tree\n */\n private AVLTree split(TreeNode left, TreeNode right, TreeNode p, boolean leftMove)\n {\n while (p != virtualRoot) {\n boolean nextMove = p.isLeftChild();\n TreeNode nextP = p.parent;\n\n p.parent.substituteChild(p, null);\n p.parent = null;\n\n if (leftMove) {\n right = merge(p, right, p.right);\n } else {\n left = merge(p, p.left, left);\n }\n p = nextP;\n leftMove = nextMove;\n }\n\n makeRoot(left);\n\n return new AVLTree<>(right);\n }\n\n /**\n * Merges the {@code left} and {@code right} subtrees using the {@code junctionNode}.\n *

\n * The algorithm is described in Donald E. Knuth. The art of computer programming. Second\n * Edition. Volume 3 / Sorting and Searching, p. 474.\n *\n * @param junctionNode a node between left and right subtrees\n * @param left a left subtree\n * @param right a right subtree\n * @return the root of the resulting tree\n */\n private TreeNode merge(TreeNode junctionNode, TreeNode left, TreeNode right)\n {\n if (left == null && right == null) {\n junctionNode.reset();\n return junctionNode;\n } else if (left == null) {\n right.setLeftChild(merge(junctionNode, left, right.left));\n return balanceNode(right);\n } else if (right == null) {\n left.setRightChild(merge(junctionNode, left.right, right));\n return balanceNode(left);\n } else if (left.getHeight() > right.getHeight() + 1) {\n left.setRightChild(merge(junctionNode, left.right, right));\n return balanceNode(left);\n } else if (right.getHeight() > left.getHeight() + 1) {\n right.setLeftChild(merge(junctionNode, left, right.left));\n return balanceNode(right);\n } else {\n junctionNode.setLeftChild(left);\n junctionNode.setRightChild(right);\n return balanceNode(junctionNode);\n }\n }\n\n /**\n * Swaps the contents of this tree and the {@code tree}\n *\n * @param tree a tree to swap content of\n */\n private void swap(AVLTree tree)\n {\n TreeNode t = virtualRoot.left;\n makeRoot(tree.virtualRoot.left);\n tree.makeRoot(t);\n }\n\n /**\n * Performs a right node rotation.\n *\n * @param node a node to rotate\n * @return a new parent of the {@code node}\n */\n private TreeNode rotateRight(TreeNode node)\n {\n TreeNode left = node.left;\n left.parent = null;\n\n node.setLeftChild(left.right);\n left.setRightChild(node);\n\n node.updateHeightAndSubtreeSize();\n left.updateHeightAndSubtreeSize();\n\n return left;\n }\n\n /**\n * Performs a left node rotation.\n *\n * @param node a node to rotate\n * @return a new parent of the {@code node}\n */\n private TreeNode rotateLeft(TreeNode node)\n {\n TreeNode right = node.right;\n right.parent = null;\n\n node.setRightChild(right.left);\n\n right.setLeftChild(node);\n\n node.updateHeightAndSubtreeSize();\n right.updateHeightAndSubtreeSize();\n\n return right;\n }\n\n /**\n * Performs a node balancing on the path from {@code node} up until the root\n *\n * @param node a node to start tree balancing from\n */\n private void balance(TreeNode node)\n {\n balance(node, virtualRoot);\n }\n\n /**\n * Performs a node balancing on the path from {@code node} up until the {@code stop} node\n *\n * @param node a node to start tree balancing from\n * @param stop a node to stop balancing at (this node is not being balanced)\n */\n private void balance(TreeNode node, TreeNode stop)\n {\n if (node == stop) {\n return;\n }\n TreeNode p = node.parent;\n if (p == virtualRoot) {\n makeRoot(balanceNode(node));\n } else {\n p.substituteChild(node, balanceNode(node));\n }\n\n balance(p, stop);\n }\n\n /**\n * Checks whether the {@code node} is unbalanced. If so, balances the {@code node}\n *\n * @param node a node to balance\n * @return a new parent of {@code node} if the balancing occurs, {@code node} otherwise\n */\n private TreeNode balanceNode(TreeNode node)\n {\n node.updateHeightAndSubtreeSize();\n if (node.isLeftDoubleHeavy()) {\n if (node.left.isRightHeavy()) {\n node.setLeftChild(rotateLeft(node.left));\n }\n rotateRight(node);\n return node.parent;\n } else if (node.isRightDoubleHeavy()) {\n if (node.right.isLeftHeavy()) {\n node.setRightChild(rotateRight(node.right));\n }\n rotateLeft(node);\n return node.parent;\n }\n return node;\n }\n\n /**\n * Registers a modifying operation\n */\n private void registerModification()\n {\n ++modCount;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n StringBuilder builder = new StringBuilder();\n for (Iterator> i = nodeIterator(); i.hasNext();) {\n TreeNode node = i.next();\n builder.append(node.toString()).append(\"\\n\");\n }\n return builder.toString();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Iterator iterator()\n {\n return new TreeValuesIterator();\n }\n\n /**\n * Returns an iterator over the tree nodes rather than the node values. The tree are returned in\n * the same order as the tree values.\n *\n * @return an iterator over the tree nodes\n */\n public Iterator> nodeIterator()\n {\n return new TreeNodeIterator();\n }\n\n /**\n * Iterator over the values stored in this tree. This implementation uses the\n * {@code TreeNodeIterator} to iterator over the values.\n */\n private class TreeValuesIterator\n implements\n Iterator\n {\n /**\n * Internally used {@code TreeNodeIterator}\n */\n private TreeNodeIterator iterator;\n\n /**\n * Constructs a new {@code TreeValuesIterator}\n */\n public TreeValuesIterator()\n {\n iterator = new TreeNodeIterator();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean hasNext()\n {\n return iterator.hasNext();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public T next()\n {\n return iterator.next().getValue();\n }\n }\n\n /**\n * Iterator over the tree nodes. The nodes are returned according to the in order tree\n * traversal.\n */\n private class TreeNodeIterator\n implements\n Iterator>\n {\n /**\n * A node that is returned next or {@code null} if all nodes are traversed\n */\n private TreeNode nextNode;\n /**\n * Number of modifications of the tree at the time this iterator is created.\n */\n private final int expectedModCount;\n\n /**\n * Constructs a new {@code TreeNodeIterator}\n */\n public TreeNodeIterator()\n {\n nextNode = getMin();\n expectedModCount = modCount;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean hasNext()\n {\n checkForComodification();\n return nextNode != null;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public TreeNode next()\n {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n TreeNode result = nextNode;\n nextNode = successor(nextNode);\n return result;\n }\n\n /**\n * Checks if the tree has been modified during the iteration process\n */\n private void checkForComodification()\n {\n if (expectedModCount != modCount) {\n throw new ConcurrentModificationException();\n }\n }\n }\n\n /**\n * Container holding the values stored in the tree.\n *\n * @param a tree node value type\n */\n public static class TreeNode\n {\n /**\n * A value stored in this tree node\n */\n T value;\n\n /**\n * Parent of this node\n */\n TreeNode parent;\n /**\n * Left child of this node\n */\n TreeNode left;\n /**\n * Right child of this node\n */\n TreeNode right;\n /**\n * Next node in the tree according to the in order traversal\n */\n TreeNode successor;\n /**\n * Previous node in the tree according to the in order traversal\n */\n TreeNode predecessor;\n /**\n * A minimum node in the subtree rooted at this node\n */\n TreeNode subtreeMin;\n /**\n * A maximum node in the subtree rooted at this node\n */\n TreeNode subtreeMax;\n /**\n * Height of the node\n */\n int height;\n /**\n * Size of the subtree rooted at this node\n */\n int subtreeSize;\n\n /**\n * Constructs a new node with the {@code value} stored in it\n *\n * @param value a value to store in this node\n */\n TreeNode(T value)\n {\n this.value = value;\n reset();\n }\n\n /**\n * Returns a value stored in this node\n *\n * @return a value stored in this node\n */\n public T getValue()\n {\n return value;\n }\n\n /**\n * Returns a root of the tree this node is stored in\n *\n * @return a root of the tree this node is stored in\n */\n public TreeNode getRoot()\n {\n TreeNode current = this;\n while (current.parent != null) {\n current = current.parent;\n }\n return current.left;\n }\n\n /**\n * Returns a minimum node stored in the subtree rooted at this node\n *\n * @return a minimum node stored in the subtree rooted at this node\n */\n public TreeNode getSubtreeMin()\n {\n return subtreeMin;\n }\n\n /**\n * Returns a maximum node stored in the subtree rooted at this node\n *\n * @return a maximum node stored in the subtree rooted at this node\n */\n public TreeNode getSubtreeMax()\n {\n return subtreeMax;\n }\n\n /**\n * Returns a minimum node stored in the tree\n *\n * @return a minimum node stored in the tree\n */\n public TreeNode getTreeMin()\n {\n return getRoot().getSubtreeMin();\n }\n\n /**\n * Returns a maximum node stored in the tree\n *\n * @return a maximum node stored in the tree\n */\n public TreeNode getTreeMax()\n {\n return getRoot().getSubtreeMax();\n }\n\n /**\n * Returns a parent of this node\n *\n * @return a parent of this node\n */\n public TreeNode getParent()\n {\n return parent;\n }\n\n /**\n * Returns a left child of this node\n *\n * @return a left child of this node\n */\n public TreeNode getLeft()\n {\n return left;\n }\n\n /**\n * Returns a right child of this node\n *\n * @return a right child of this node\n */\n public TreeNode getRight()\n {\n return right;\n }\n\n /**\n * Returns a height of this node\n *\n * @return a height of this node\n */\n int getHeight()\n {\n return height;\n }\n\n /**\n * Returns a subtree size of the tree rooted at this node\n *\n * @return a subtree size of the tree rooted at this node\n */\n int getSubtreeSize()\n {\n return subtreeSize;\n }\n\n /**\n * Resets this node to the default state\n */\n void reset()\n {\n this.height = 1;\n this.subtreeSize = 1;\n this.subtreeMin = this;\n this.subtreeMax = this;\n this.left = this.right = this.parent = this.predecessor = this.successor = null;\n }\n\n /**\n * Returns a height of the right subtree\n *\n * @return a height of the right subtree\n */\n int getRightHeight()\n {\n return right == null ? 0 : right.height;\n }\n\n /**\n * Returns a height of the left subtree\n *\n * @return a height of the right subtree\n */\n int getLeftHeight()\n {\n return left == null ? 0 : left.height;\n }\n\n /**\n * Returns a size of the left subtree\n *\n * @return a size of the left subtree\n */\n int getLeftSubtreeSize()\n {\n return left == null ? 0 : left.subtreeSize;\n }\n\n /**\n * Returns a size of the right subtree\n *\n * @return a size of the right subtree\n */\n int getRightSubtreeSize()\n {\n return right == null ? 0 : right.subtreeSize;\n }\n\n /**\n * Updates the height and subtree size of this node according to the values of the left and\n * right children\n */\n void updateHeightAndSubtreeSize()\n {\n height = Math.max(getLeftHeight(), getRightHeight()) + 1;\n subtreeSize = getLeftSubtreeSize() + getRightSubtreeSize() + 1;\n }\n\n /**\n * Returns {@code true} if this node is unbalanced and the left child's height is greater,\n * {@code false otherwise}\n *\n * @return {@code true} if this node is unbalanced and the left child's height is greater,\n * {@code false otherwise}\n */\n boolean isLeftDoubleHeavy()\n {\n return getLeftHeight() > getRightHeight() + 1;\n }\n\n /**\n * Returns {@code true} if this node is unbalanced and the right child's height is greater,\n * {@code false otherwise}\n *\n * @return {@code true} if this node is unbalanced and the right child's height is greater,\n * {@code false otherwise}\n */\n boolean isRightDoubleHeavy()\n {\n return getRightHeight() > getLeftHeight() + 1;\n }\n\n /**\n * Returns {@code true} if the height of the left child is greater than the height of the\n * right child\n *\n * @return {@code true} if the height of the left child is greater than the height of the\n * right child\n */\n boolean isLeftHeavy()\n {\n return getLeftHeight() > getRightHeight();\n }\n\n /**\n * Returns {@code true} if the height of the right child is greater than the height of the\n * left child\n *\n * @return {@code true} if the height of the right child is greater than the height of the\n * left child\n */\n boolean isRightHeavy()\n {\n return getRightHeight() > getLeftHeight();\n }\n\n /**\n * Returns {@code true} if this node is a left child of its parent, {@code false} otherwise\n *\n * @return {@code true} if this node is a left child of its parent, {@code false} otherwise\n */\n boolean isLeftChild()\n {\n return this == parent.left;\n }\n\n /**\n * Returns {@code true} if this node is a right child of its parent, {@code false} otherwise\n *\n * @return {@code true} if this node is a right child of its parent, {@code false} otherwise\n */\n boolean isRightChild()\n {\n return this == parent.right;\n }\n\n /**\n * Returns a successor of this node according to the tree in order traversal, or\n * {@code null} if this node is a maximum node in the tree\n *\n * @return successor of this node, or {@code} null if this node in a maximum node in the\n * tree\n */\n public TreeNode getSuccessor()\n {\n return successor;\n }\n\n /**\n * Returns a predecessor of this node according to the tree in order traversal, or\n * {@code null} if this node is a minimum node in the tree\n *\n * @return predecessor of this node, or {@code} null if this node in a minimum node in the\n * tree\n */\n public TreeNode getPredecessor()\n {\n return predecessor;\n }\n\n /**\n * Updates the successor reference of this node. If the {@code node} is not {@code null},\n * updates its predecessor reference as well\n *\n * @param node new successor\n */\n void setSuccessor(TreeNode node)\n {\n successor = node;\n if (node != null) {\n node.predecessor = this;\n }\n }\n\n /**\n * Updates the predecessor reference of this node. If the {@code node} is not {@code null},\n * updates its successor reference as well\n *\n * @param node new predecessor\n */\n void setPredecessor(TreeNode node)\n {\n predecessor = node;\n if (node != null) {\n node.successor = this;\n }\n }\n\n /**\n * Sets the left child reference of this node to {@code node}. If the {@code node} is not\n * {@code null}, updates its parent reference as well.\n *\n * @param node a new left child\n */\n void setLeftChild(TreeNode node)\n {\n left = node;\n if (node != null) {\n node.parent = this;\n setPredecessor(node.subtreeMax);\n subtreeMin = node.subtreeMin;\n } else {\n subtreeMin = this;\n predecessor = null;\n }\n }\n\n /**\n * Sets the right child reference of this node to {@code node}. If the {@code node} is not\n * {@code null}, updates its parent reference as well.\n *\n * @param node a new right child\n */\n void setRightChild(TreeNode node)\n {\n right = node;\n if (node != null) {\n node.parent = this;\n setSuccessor(node.subtreeMin);\n subtreeMax = node.subtreeMax;\n } else {\n successor = null;\n subtreeMax = this;\n }\n }\n\n /**\n * Substitutes the {@code prevChild} with the {@code newChild}. If the {@code newChild} is\n * not {@code null}, updates its parent reference as well\n *\n * @param prevChild either left or right child of this node\n * @param newChild a new child of this node\n */\n void substituteChild(TreeNode prevChild, TreeNode newChild)\n {\n assert left == prevChild || right == prevChild;\n assert !(left == prevChild && right == prevChild);\n if (left == prevChild) {\n setLeftChild(newChild);\n } else {\n setRightChild(newChild);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n return String\n .format(\n \"{%s}: [parent = %s, left = %s, right = %s], [subtreeMin = %s, subtreeMax = %s], [predecessor = %s, successor = %s], [height = %d, subtreeSize = %d]\",\n value, parent == null ? \"null\" : parent.value,\n left == null ? \"null\" : left.value, right == null ? \"null\" : right.value,\n subtreeMin == null ? \"null\" : subtreeMin.value,\n subtreeMax == null ? \"null\" : subtreeMax.value,\n predecessor == null ? \"null\" : predecessor.value,\n successor == null ? \"null\" : successor.value, height, subtreeSize);\n }\n }\n\n}\n", "file_name": "AVLTree.java", "human_label": "Perform a right node rotation on the AVL tree.", "level": "file_runnable", "lineno": "488", "name": "rotateRight", "oracle_context": "{ \"apis\" : \"[setLeftChild, setRightChild, updateHeightAndSubtreeSize, TreeNode]\", \"classes\" : \"[TreeNode]\", \"vars\" : \"[parent, right]\" }", "package": "org.jgrapht.util", "project": "jgrapht-master" }, { "_id": "6367667f1a6d9265ec01745c", "all_context": "{ \"class_level\" : \"import org.slf4j.Logger;\\nimport org.slf4j.LoggerFactory;\\nimport java.io.File;\\nimport java.io.FilenameFilter;\\nimport java.io.IOException;\\nimport java.lang.reflect.Method;\\nimport java.net.InetAddress;\\nimport java.net.MalformedURLException;\\nimport java.net.URL;\\nimport java.net.UnknownHostException;\\nimport java.util.Hashtable;\\nimport java.util.StringTokenizer;\\nimport java.util.Vector;\\nLogger logger;\\nHashtable,Method[]> objectMethods;\\nObject[] emptyArray;\\nint dbg;\\nsetAttribute(Object proxy,String name,Object value);\\ngetAttribute(Object proxy,String name);\\nsetProperty(Object o,String name,String value);\\naddProperty(Object o,String name,String value);\\ninvokeProperty(Object object,String setter,String name,String value);\\ngetProperty(Object object,String name);\\nsetProperty(Object object,String name);\\nreplaceProperties(String value,Hashtable staticProp,PropertySource dynamicProp);\\ncapitalize(String name);\\nunCapitalize(String name);\\naddToClassPath(Vector cpV,String dir);\\naddToolsJar(Vector v);\\ngetFilesByExt(String ld,String ext);\\naccept(File d,String name);\\ngetURL(String base,String file);\\naddJarsFromClassPath(Vector jars,String cp);\\ngetClassPath(Vector v);\\ngetClassPath(String dir,String cpath,String cpathProp,boolean addTools);\\nprocessArgs(Object proxy,String args);\\nprocessArgs(Object proxy,String args,String args0,String args1,Hashtable aliases);\\nclear();\\nfindVoidSetters(Class c);\\nfindBooleanSetters(Class c);\\nfindMethods(Class c);\\nfindMethod(Class c,String name,Class params);\\nhasHook(Object obj,String methodN);\\ncallMain(Class c,String args);\\ncallMethod1(Object target,String methodN,Object param1,String typeParam1,ClassLoader cl);\\ncallMethod0(Object target,String methodN);\\ncallMethodN(Object target,String methodN,Object params,Class typeParams);\\nconvert(String object,Class paramType);\\ngetProperty(String key);\\nsetAttribute(String key,Object o);\\ndebug(String s);\\nexecute(Object proxy,String method);\\n\", \"repo_level\" : \"\" }", "class_name": "IntrospectionUtils", "code": "@SuppressWarnings(\"unchecked\") public static void addToClassPath(Vector cpV,String dir){\n try {\n String cpComp[]=getFilesByExt(dir,\".jar\");\n if (cpComp != null) {\n int jarCount=cpComp.length;\n for (int i=0; i < jarCount; i++) {\n URL url=getURL(dir,cpComp[i]);\n if (url != null) cpV.addElement(url);\n }\n }\n }\n catch ( Exception ex) {\n logger.debug(\"failed to add urls to classpath\",ex);\n }\n}\n", "docstring": "/** \n * Add all the jar files in a dir to the classpath, represented as a Vector of URLs.\n */\n", "end_lineno": "416", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n\n/*\n * This file incorporates work covered by the following copyright and\n * permission notice:\n *\n * Copyright 2004 The Apache Software Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.atmosphere.util;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.io.IOException;\nimport java.lang.reflect.Method;\nimport java.net.InetAddress;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.net.UnknownHostException;\nimport java.util.Hashtable;\nimport java.util.StringTokenizer;\nimport java.util.Vector;\n\n/**\n * Utils for introspection and reflection\n */\npublic final class IntrospectionUtils {\n\n private static final Logger logger = LoggerFactory.getLogger(IntrospectionUtils.class);\n\n /**\n * Call execute() - any ant-like task should work\n */\n public static void execute(Object proxy, String method) throws Exception {\n Method executeM = null;\n Class c = proxy.getClass();\n Class params[] = new Class[0];\n // params[0]=args.getClass();\n executeM = findMethod(c, method, params);\n if (executeM == null) {\n throw new RuntimeException(\"No execute in \" + proxy.getClass());\n }\n executeM.invoke(proxy, (Object[]) null);//new Object[] { args });\n }\n\n /**\n * Call void setAttribute( String ,Object )\n */\n public static void setAttribute(Object proxy, String name, Object value)\n throws Exception {\n if (proxy instanceof AttributeHolder) {\n ((AttributeHolder) proxy).setAttribute(name, value);\n return;\n }\n\n Method executeM = null;\n Class c = proxy.getClass();\n Class params[] = new Class[2];\n params[0] = String.class;\n params[1] = Object.class;\n executeM = findMethod(c, \"setAttribute\", params);\n if (executeM == null) {\n logger.debug(\"No setAttribute in {}\", proxy.getClass());\n return;\n }\n\n logger.debug(\"Setting {}={} in proxy: {}\", new Object[]{name, value, proxy});\n executeM.invoke(proxy, new Object[]{name, value});\n return;\n }\n\n /**\n * Call void getAttribute( String )\n */\n public static Object getAttribute(Object proxy, String name) throws Exception {\n Class c = proxy.getClass();\n Class params[] = new Class[1];\n params[0] = String.class;\n Method executeM = findMethod(c, \"getAttribute\", params);\n if (executeM == null) {\n logger.debug(\"No getAttribute in {}\", proxy.getClass());\n return null;\n }\n return executeM.invoke(proxy, new Object[]{name});\n }\n\n\n /**\n * Find a method with the right name If found, call the method ( if param is\n * int or boolean we'll convert value to the right type before) - that means\n * you can have setDebug(1).\n */\n final public static boolean setProperty(Object o, String name, String value) {\n String setter = \"set\" + capitalize(name);\n return invokeProperty(o, setter, name, value);\n }\n\n final public static boolean addProperty(Object o, String name, String value) {\n String setter = \"add\" + capitalize(name);\n return invokeProperty(o, setter, name, value);\n }\n\n final static public boolean invokeProperty(Object object, String setter, String name, String value) {\n try {\n Method methods[] = findMethods(object.getClass());\n Method setPropertyMethodVoid = null;\n Method setPropertyMethodBool = null;\n\n // First, the ideal case - a setFoo( String ) method\n for (int i = 0; i < methods.length; i++) {\n Class paramT[] = methods[i].getParameterTypes();\n if (setter.equals(methods[i].getName()) && paramT.length == 1\n && \"java.lang.String\".equals(paramT[0].getName())) {\n\n methods[i].invoke(object, new Object[]{value});\n return true;\n }\n }\n\n // Try a setFoo ( int ) or ( boolean )\n for (int i = 0; i < methods.length; i++) {\n boolean ok = true;\n if (setter.equals(methods[i].getName())\n && methods[i].getParameterTypes().length == 1) {\n\n // match - find the type and invoke it\n Class paramType = methods[i].getParameterTypes()[0];\n Object params[] = new Object[1];\n\n // Try a setFoo ( int )\n if (\"java.lang.Integer\".equals(paramType.getName())\n || \"int\".equals(paramType.getName())) {\n try {\n params[0] = new Integer(value);\n } catch (NumberFormatException ex) {\n ok = false;\n }\n // Try a setFoo ( long )\n } else if (\"java.lang.Long\".equals(paramType.getName())\n || \"long\".equals(paramType.getName())) {\n try {\n params[0] = new Long(value);\n } catch (NumberFormatException ex) {\n ok = false;\n }\n\n // Try a setFoo ( boolean )\n } else if (\"java.lang.Boolean\".equals(paramType.getName())\n || \"boolean\".equals(paramType.getName())) {\n params[0] = new Boolean(value);\n\n // Try a setFoo ( InetAddress )\n } else if (\"java.net.InetAddress\".equals(paramType\n .getName())) {\n try {\n params[0] = InetAddress.getByName(value);\n } catch (UnknownHostException exc) {\n debug(\"Unable to resolve host name:\" + value);\n ok = false;\n }\n\n // Unknown type\n } else {\n debug(\"Unknown type \" + paramType.getName());\n }\n\n if (ok) {\n methods[i].invoke(object, params);\n return true;\n }\n }\n\n // save \"setProperty\" for later\n if (\"setProperty\".equals(methods[i].getName())) {\n if (methods[i].getReturnType() == Boolean.TYPE) {\n setPropertyMethodBool = methods[i];\n } else {\n setPropertyMethodVoid = methods[i];\n }\n\n }\n }\n\n // Ok, no setXXX found, try a setProperty(\"name\", \"value\")\n if (setPropertyMethodBool != null || setPropertyMethodVoid != null) {\n Object params[] = new Object[2];\n params[0] = name;\n params[1] = value;\n if (setPropertyMethodBool != null) {\n try {\n return (Boolean) setPropertyMethodBool.invoke(object, params);\n } catch (IllegalArgumentException biae) {\n //the boolean method had the wrong\n //parameter types. lets try the other\n if (setPropertyMethodVoid != null) {\n setPropertyMethodVoid.invoke(object, params);\n return true;\n } else {\n throw biae;\n }\n }\n } else {\n setPropertyMethodVoid.invoke(object, params);\n return true;\n }\n }\n\n } catch (IllegalArgumentException e) {\n logger.info(\"failed, object: \" + object + \", setter: \" + setter + \", value: \" + value, e);\n } catch (Exception e) {\n if (dbg > 0) {\n debug(e.getClass().getSimpleName() + \" for \" + object.getClass() + \" \" + setter + \"=\" + value + \")\");\n }\n if (dbg > 1) {\n logger.debug(\"\", e);\n }\n }\n\n return false;\n }\n\n public static Object getProperty(Object object, String name) {\n String getter = \"get\" + capitalize(name);\n String isGetter = \"is\" + capitalize(name);\n\n try {\n Method methods[] = findMethods(object.getClass());\n Method getPropertyMethod = null;\n\n // First, the ideal case - a getFoo() method\n for (int i = 0; i < methods.length; i++) {\n Class paramT[] = methods[i].getParameterTypes();\n if (getter.equals(methods[i].getName()) && paramT.length == 0) {\n return methods[i].invoke(object, (Object[]) null);\n }\n if (isGetter.equals(methods[i].getName()) && paramT.length == 0) {\n return methods[i].invoke(object, (Object[]) null);\n }\n\n if (\"getProperty\".equals(methods[i].getName())) {\n getPropertyMethod = methods[i];\n }\n }\n\n // Ok, no setXXX found, try a getProperty(\"name\")\n if (getPropertyMethod != null) {\n Object params[] = new Object[1];\n params[0] = name;\n return getPropertyMethod.invoke(object, params);\n }\n\n } catch (IllegalArgumentException e) {\n logger.info(\"failed, object: \" + object + \", name: \" + name, e);\n } catch (Exception e) {\n if (dbg > 0) {\n debug(e.getClass().getSimpleName() + \" for \" + object.getClass() + \" \" + name + \")\");\n }\n if (dbg > 1) {\n logger.debug(\"\", e);\n }\n }\n\n return null;\n }\n\n /**\n */\n public static void setProperty(Object object, String name) {\n String setter = \"set\" + capitalize(name);\n try {\n Method methods[] = findMethods(object.getClass());\n Method setPropertyMethod = null;\n // find setFoo() method\n for (int i = 0; i < methods.length; i++) {\n Class paramT[] = methods[i].getParameterTypes();\n if (setter.equals(methods[i].getName()) && paramT.length == 0) {\n methods[i].invoke(object, new Object[]{});\n return;\n }\n }\n } catch (Exception e) {\n if (dbg > 0) {\n debug(\"Exception for \" + object.getClass() + \" \" + name);\n }\n if (dbg > 1) {\n logger.debug(\"\", e);\n }\n }\n }\n\n /**\n * Replace ${NAME} with the property value\n */\n public static String replaceProperties(String value,\n Hashtable staticProp, PropertySource dynamicProp[]) {\n if (value.indexOf(\"$\") < 0) {\n return value;\n }\n StringBuilder sb = new StringBuilder();\n int prev = 0;\n // assert value!=nil\n int pos;\n while ((pos = value.indexOf(\"$\", prev)) >= 0) {\n if (pos > 0) {\n sb.append(value.substring(prev, pos));\n }\n if (pos == (value.length() - 1)) {\n sb.append('$');\n prev = pos + 1;\n } else if (value.charAt(pos + 1) != '{') {\n sb.append('$');\n prev = pos + 1; // XXX\n } else {\n int endName = value.indexOf('}', pos);\n if (endName < 0) {\n sb.append(value.substring(pos));\n prev = value.length();\n continue;\n }\n String n = value.substring(pos + 2, endName);\n String v = null;\n if (staticProp != null) {\n v = staticProp.get(n);\n }\n if (v == null && dynamicProp != null) {\n for (int i = 0; i < dynamicProp.length; i++) {\n v = dynamicProp[i].getProperty(n);\n if (v != null) {\n break;\n }\n }\n }\n if (v == null)\n v = \"${\" + n + \"}\";\n\n sb.append(v);\n prev = endName + 1;\n }\n }\n if (prev < value.length())\n sb.append(value.substring(prev));\n return sb.toString();\n }\n\n /**\n * Reverse of Introspector.decapitalize\n */\n public static String capitalize(String name) {\n if (name == null || name.length() == 0) {\n return name;\n }\n char chars[] = name.toCharArray();\n chars[0] = Character.toUpperCase(chars[0]);\n return new String(chars);\n }\n\n public static String unCapitalize(String name) {\n if (name == null || name.length() == 0) {\n return name;\n }\n char chars[] = name.toCharArray();\n chars[0] = Character.toLowerCase(chars[0]);\n return new String(chars);\n }\n\n // -------------------- Class path tools --------------------\n\n /**\n * Add all the jar files in a dir to the classpath, represented as a Vector\n * of URLs.\n */\n @SuppressWarnings(\"unchecked\")\n public static void addToClassPath(Vector cpV, String dir) {\n try {\n String cpComp[] = getFilesByExt(dir, \".jar\");\n if (cpComp != null) {\n int jarCount = cpComp.length;\n for (int i = 0; i < jarCount; i++) {\n URL url = getURL(dir, cpComp[i]);\n if (url != null)\n cpV.addElement(url);\n }\n }\n } catch (Exception ex) {\n logger.debug(\"failed to add urls to classpath\", ex);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public static void addToolsJar(Vector v) {\n try {\n // Add tools.jar in any case\n File f = new File(System.getProperty(\"java.home\")\n + \"/../lib/tools.jar\");\n\n if (!f.exists()) {\n // On some systems java.home gets set to the root of jdk.\n // That's a bug, but we can work around and be nice.\n f = new File(System.getProperty(\"java.home\") + \"/lib/tools.jar\");\n if (f.exists()) {\n logger.debug(\"Detected strange java.home value {}, it should point to jre\",\n System.getProperty(\"java.home\"));\n }\n }\n URL url = new URL(\"file\", \"\", f.getAbsolutePath());\n\n v.addElement(url);\n } catch (MalformedURLException ex) {\n logger.debug(\"failed to add tools jar url to vector\", ex);\n }\n }\n\n /**\n * Return all files with a given extension in a dir\n */\n public static String[] getFilesByExt(String ld, String ext) {\n File dir = new File(ld);\n String[] names = null;\n final String lext = ext;\n if (dir.isDirectory()) {\n names = dir.list(new FilenameFilter() {\n public boolean accept(File d, String name) {\n if (name.endsWith(lext)) {\n return true;\n }\n return false;\n }\n });\n }\n return names;\n }\n\n /**\n * Construct a file url from a file, using a base dir\n */\n public static URL getURL(String base, String file) {\n try {\n File baseF = new File(base);\n File f = new File(baseF, file);\n String path = f.getCanonicalPath();\n if (f.isDirectory()) {\n path += \"/\";\n }\n if (!f.exists()) {\n return null;\n }\n return new URL(\"file\", \"\", path);\n } catch (Exception ex) {\n logger.debug(\"failed to get url, base: \" + base + \", file: \" + file, ex);\n return null;\n }\n }\n\n /**\n * Add elements from the classpath cp to a Vector jars as\n * file URLs (We use Vector for JDK 1.1 compat).\n *

\n *\n * @param jars The jar list\n * @param cp a String classpath of directory or jar file elements\n * separated by path.separator delimiters.\n * @throws IOException If an I/O error occurs\n * @throws MalformedURLException Doh ;)\n */\n @SuppressWarnings(\"unchecked\")\n public static void addJarsFromClassPath(Vector jars, String cp)\n throws IOException, MalformedURLException {\n String sep = System.getProperty(\"path.separator\");\n String token;\n StringTokenizer st;\n if (cp != null) {\n st = new StringTokenizer(cp, sep);\n while (st.hasMoreTokens()) {\n File f = new File(st.nextToken());\n String path = f.getCanonicalPath();\n if (f.isDirectory()) {\n path += \"/\";\n }\n URL url = new URL(\"file\", \"\", path);\n if (!jars.contains(url)) {\n jars.addElement(url);\n }\n }\n }\n }\n\n /**\n * Return a URL[] that can be used to construct a class loader\n */\n public static URL[] getClassPath(Vector v) {\n URL[] urls = new URL[v.size()];\n for (int i = 0; i < v.size(); i++) {\n urls[i] = v.elementAt(i);\n }\n return urls;\n }\n\n /**\n * Construct a URL classpath from files in a directory, a cpath property,\n * and tools.jar.\n */\n @SuppressWarnings(\"unchecked\")\n public static URL[] getClassPath(String dir, String cpath,\n String cpathProp, boolean addTools) throws IOException,\n MalformedURLException {\n Vector jarsV = new Vector();\n if (dir != null) {\n // Add dir/classes first, if it exists\n URL url = getURL(dir, \"classes\");\n if (url != null)\n jarsV.addElement(url);\n addToClassPath(jarsV, dir);\n }\n\n if (cpath != null)\n addJarsFromClassPath(jarsV, cpath);\n\n if (cpathProp != null) {\n String cpath1 = System.getProperty(cpathProp);\n addJarsFromClassPath(jarsV, cpath1);\n }\n\n if (addTools)\n addToolsJar(jarsV);\n\n return getClassPath(jarsV);\n }\n\n // -------------------- Mapping command line params to setters\n\n public static boolean processArgs(Object proxy, String args[])\n throws Exception {\n String args0[] = null;\n if (null != findMethod(proxy.getClass(), \"getOptions1\", new Class[]{})) {\n args0 = (String[]) callMethod0(proxy, \"getOptions1\");\n }\n\n if (args0 == null) {\n //args0=findVoidSetters(proxy.getClass());\n args0 = findBooleanSetters(proxy.getClass());\n }\n Hashtable h = null;\n if (null != findMethod(proxy.getClass(), \"getOptionAliases\",\n new Class[]{})) {\n h = (Hashtable) callMethod0(proxy, \"getOptionAliases\");\n }\n return processArgs(proxy, args, args0, null, h);\n }\n\n public static boolean processArgs(Object proxy, String args[],\n String args0[], String args1[],\n Hashtable aliases) throws Exception {\n for (int i = 0; i < args.length; i++) {\n String arg = args[i];\n if (arg.startsWith(\"-\"))\n arg = arg.substring(1);\n if (aliases != null && aliases.get(arg) != null)\n arg = aliases.get(arg);\n\n if (args0 != null) {\n boolean set = false;\n for (int j = 0; j < args0.length; j++) {\n if (args0[j].equalsIgnoreCase(arg)) {\n setProperty(proxy, args0[j], \"true\");\n set = true;\n break;\n }\n }\n if (set)\n continue;\n }\n if (args1 != null) {\n for (int j = 0; j < args1.length; j++) {\n if (args1[j].equalsIgnoreCase(arg)) {\n i++;\n if (i >= args.length)\n return false;\n setProperty(proxy, arg, args[i]);\n break;\n }\n }\n } else {\n // if args1 is not specified,assume all other options have param\n i++;\n if (i >= args.length)\n return false;\n setProperty(proxy, arg, args[i]);\n }\n\n }\n return true;\n }\n\n // -------------------- other utils --------------------\n\n public static void clear() {\n objectMethods.clear();\n }\n\n @SuppressWarnings(\"unchecked\")\n public static String[] findVoidSetters(Class c) {\n Method m[] = findMethods(c);\n if (m == null)\n return null;\n Vector v = new Vector();\n for (int i = 0; i < m.length; i++) {\n if (m[i].getName().startsWith(\"set\")\n && m[i].getParameterTypes().length == 0) {\n String arg = m[i].getName().substring(3);\n v.addElement(unCapitalize(arg));\n }\n }\n String s[] = new String[v.size()];\n for (int i = 0; i < s.length; i++) {\n s[i] = (String) v.elementAt(i);\n }\n return s;\n }\n\n @SuppressWarnings(\"unchecked\")\n public static String[] findBooleanSetters(Class c) {\n Method m[] = findMethods(c);\n if (m == null)\n return null;\n Vector v = new Vector();\n for (int i = 0; i < m.length; i++) {\n if (m[i].getName().startsWith(\"set\")\n && m[i].getParameterTypes().length == 1\n && \"boolean\".equalsIgnoreCase(m[i].getParameterTypes()[0]\n .getName())) {\n String arg = m[i].getName().substring(3);\n v.addElement(unCapitalize(arg));\n }\n }\n String s[] = new String[v.size()];\n for (int i = 0; i < s.length; i++) {\n s[i] = v.elementAt(i);\n }\n return s;\n }\n\n static Hashtable, Method[]> objectMethods =\n new Hashtable, Method[]>();\n\n @SuppressWarnings(\"unchecked\")\n public static Method[] findMethods(Class c) {\n Method methods[] = (Method[]) objectMethods.get(c);\n if (methods != null)\n return methods;\n\n methods = c.getMethods();\n objectMethods.put(c, methods);\n return methods;\n }\n\n public static Method findMethod(Class c, String name,\n Class params[]) {\n Method methods[] = findMethods(c);\n if (methods == null)\n return null;\n for (int i = 0; i < methods.length; i++) {\n if (methods[i].getName().equals(name)) {\n Class methodParams[] = methods[i].getParameterTypes();\n if (methodParams == null)\n if (params == null || params.length == 0)\n return methods[i];\n if (params == null)\n if (methodParams == null || methodParams.length == 0)\n return methods[i];\n if (params.length != methodParams.length)\n continue;\n boolean found = true;\n for (int j = 0; j < params.length; j++) {\n if (params[j] != methodParams[j]) {\n found = false;\n break;\n }\n }\n if (found)\n return methods[i];\n }\n }\n return null;\n }\n\n /**\n * Test if the object implements a particular\n * method\n */\n public static boolean hasHook(Object obj, String methodN) {\n try {\n Method myMethods[] = findMethods(obj.getClass());\n for (int i = 0; i < myMethods.length; i++) {\n if (methodN.equals(myMethods[i].getName())) {\n // check if it's overriden\n Class declaring = myMethods[i].getDeclaringClass();\n Class parentOfDeclaring = declaring.getSuperclass();\n // this works only if the base class doesn't extend\n // another class.\n\n // if the method is declared in a top level class\n // like BaseInterceptor parent is Object, otherwise\n // parent is BaseInterceptor or an intermediate class\n if (!\"java.lang.Object\".equals(parentOfDeclaring.getName())) {\n return true;\n }\n }\n }\n } catch (Exception ex) {\n logger.debug(\"hasHook() failed\", ex);\n }\n return false;\n }\n\n public static void callMain(Class c, String args[]) throws Exception {\n Class p[] = new Class[1];\n p[0] = args.getClass();\n @SuppressWarnings(\"unchecked\")\n Method m = c.getMethod(\"main\", p);\n m.invoke(c, new Object[]{args});\n }\n\n public static Object callMethod1(Object target, String methodN,\n Object param1, String typeParam1, ClassLoader cl) throws Exception {\n if (target == null || param1 == null) {\n debug(\"Assert: Illegal params \" + target + \" \" + param1);\n }\n if (dbg > 0)\n debug(\"callMethod1 \" + target.getClass().getName() + \" \" + param1.getClass().getName() + \" \" +\n typeParam1);\n\n Class params[] = new Class[1];\n if (typeParam1 == null) {\n params[0] = param1.getClass();\n } else {\n params[0] = cl.loadClass(typeParam1);\n }\n Method m = findMethod(target.getClass(), methodN, params);\n if (m == null) {\n throw new NoSuchMethodException(target.getClass().getName() + \" \" + methodN);\n }\n return m.invoke(target, new Object[]{param1});\n }\n\n public static Object callMethod0(Object target, String methodN)\n throws Exception {\n if (target == null) {\n debug(\"Assert: Illegal params \" + target);\n return null;\n }\n if (dbg > 0) {\n debug(\"callMethod0 \" + target.getClass().getName() + \".\" + methodN);\n }\n\n Class params[] = new Class[0];\n Method m = findMethod(target.getClass(), methodN, params);\n if (m == null) {\n throw new NoSuchMethodException(target.getClass().getName() + \" \" + methodN);\n }\n return m.invoke(target, emptyArray);\n }\n\n static Object[] emptyArray = new Object[]{};\n\n public static Object callMethodN(Object target, String methodN,\n Object params[], Class typeParams[]) throws Exception {\n Method m = null;\n m = findMethod(target.getClass(), methodN, typeParams);\n if (m == null) {\n debug(\"Can't find method \" + methodN + \" in \" + target + \" CLASS \" + target.getClass());\n return null;\n }\n Object o = m.invoke(target, params);\n\n if (dbg > 0) {\n // debug\n StringBuffer sb = new StringBuffer();\n sb.append(\"\" + target.getClass().getName() + \".\" + methodN + \"( \");\n for (int i = 0; i < params.length; i++) {\n if (i > 0)\n sb.append(\", \");\n sb.append(params[i]);\n }\n sb.append(\")\");\n debug(sb.toString());\n }\n return o;\n }\n\n public static Object convert(String object, Class paramType) {\n Object result = null;\n if (\"java.lang.String\".equals(paramType.getName())) {\n result = object;\n } else if (\"java.lang.Integer\".equals(paramType.getName())\n || \"int\".equals(paramType.getName())) {\n try {\n result = new Integer(object);\n } catch (NumberFormatException ex) {\n }\n // Try a setFoo ( boolean )\n } else if (\"java.lang.Boolean\".equals(paramType.getName())\n || \"boolean\".equals(paramType.getName())) {\n result = new Boolean(object);\n\n // Try a setFoo ( InetAddress )\n } else if (\"java.net.InetAddress\".equals(paramType\n .getName())) {\n try {\n result = InetAddress.getByName(object);\n } catch (UnknownHostException exc) {\n debug(\"Unable to resolve host name:\" + object);\n }\n\n // Unknown type\n } else {\n debug(\"Unknown type \" + paramType.getName());\n }\n if (result == null) {\n throw new IllegalArgumentException(\"Can't convert argument: \" + object);\n }\n return result;\n }\n\n // -------------------- Get property --------------------\n // This provides a layer of abstraction\n\n public static interface PropertySource {\n\n public String getProperty(String key);\n\n }\n\n public static interface AttributeHolder {\n\n public void setAttribute(String key, Object o);\n\n }\n\n // debug --------------------\n static final int dbg = 0;\n\n static void debug(String s) {\n logger.debug(\"IntrospectionUtils: {}\", s);\n }\n}\n", "file_name": "IntrospectionUtils.java", "human_label": "Add all the jar files in the given dir to the classpath. The classpath is represented as a Vector of URLs.", "level": "class_runnable", "lineno": "397", "name": "addToClassPath", "oracle_context": "{ \"apis\" : \"[getFilesByExt, getURL, addElement, debug]\", \"classes\" : \"[String, URL]\", \"vars\" : \"[length, logger]\" }", "package": "org.atmosphere.util", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "6367677e1a6d9265ec01830f", "all_context": "{ \"class_level\" : \"import org.apache.log4j.spi.LoggingEvent;\\nimport org.apache.log4j.helpers.PatternParser;\\nimport org.apache.log4j.helpers.PatternConverter;\\nString DEFAULT_CONVERSION_PATTERN;\\nString TTCC_CONVERSION_PATTERN;\\nint BUF_SIZE;\\nint MAX_CAPACITY;\\nStringBuffer sbuf;\\nString pattern;\\nPatternConverter head;\\nPatternLayout();\\nPatternLayout(String pattern);\\nsetConversionPattern(String conversionPattern);\\ngetConversionPattern();\\nignoresThrowable();\\ncreatePatternParser(String pattern);\\nformat(LoggingEvent event);\\nactivateOptions();\\n\", \"repo_level\" : \"public interface LoggingEvent {public LocationInfo getLocationInformation();\\npublic Level getLevel();\\npublic String getLoggerName();\\npublic Category getLogger();\\npublic Object getMessage();\\npublic String getNDC();\\npublic Object getMDC(String key);\\npublic void getMDCCopy();\\npublic String getRenderedMessage();\\nstatic long getStartTime();\\npublic String getThreadName();\\npublic ThrowableInformation getThrowableInformation();\\npublic String[] getThrowableStrRep();\\nfinal void setProperty(String propName,String propValue);\\nfinal String getProperty(String key);\\nfinal boolean locationInformationExists();\\nfinal long getTimeStamp();\\npublic Set getPropertyKeySet();\\npublic Map getProperties();\\npublic String getFQNOfLoggerClass();\\npublic Object removeProperty(String propName);\\n }\\npublic interface PatternParser {protected String extractOption();\\nprotected int extractPrecisionOption();\\npublic PatternConverter parse();\\nprotected void finalizeConverter(char c);\\nprotected void addConverter(PatternConverter pc);\\npublic String convert(LoggingEvent event);\\nfinal void format(StringBuffer sbuf,LoggingEvent event);\\npublic String convert(LoggingEvent event);\\npublic String convert(LoggingEvent event);\\npublic String convert(LoggingEvent event);\\npublic String convert(LoggingEvent event);\\nabstract String getFullyQualifiedName(LoggingEvent event);\\npublic String convert(LoggingEvent event);\\n String getFullyQualifiedName(LoggingEvent event);\\n String getFullyQualifiedName(LoggingEvent event);\\n }\\npublic interface PatternConverter {protected String convert(LoggingEvent event);\\npublic void format(StringBuffer sbuf,LoggingEvent e);\\npublic void spacePad(StringBuffer sbuf,int length);\\n }\\n\" }", "class_name": "PatternLayout", "code": "public String format(LoggingEvent event){\n if (sbuf.capacity() > MAX_CAPACITY) {\n sbuf=new StringBuffer(BUF_SIZE);\n }\n else {\n sbuf.setLength(0);\n }\n PatternConverter c=head;\n while (c != null) {\n c.format(sbuf,event);\n c=c.next;\n }\n return sbuf.toString();\n}\n", "docstring": "/** \n * Produces a formatted string as specified by the conversion pattern.\n */\n", "end_lineno": "510", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.log4j;\n\nimport org.apache.log4j.spi.LoggingEvent;\nimport org.apache.log4j.helpers.PatternParser;\nimport org.apache.log4j.helpers.PatternConverter;\n\n\n// Contributors: Nelson Minar \n// Anders Kristensen \n\n/**\n\n A flexible layout configurable with pattern string.\n \n This code is known to have synchronization and other issues\n which are not present in org.apache.log4j.EnhancedPatternLayout.\n EnhancedPatternLayout should be used in preference to PatternLayout.\n EnhancedPatternLayout is distributed in the log4j extras companion.\n\n

The goal of this class is to {@link #format format} a {@link\n LoggingEvent} and return the results as a String. The results\n depend on the conversion pattern.\n\n

The conversion pattern is closely related to the conversion\n pattern of the printf function in C. A conversion pattern is\n composed of literal text and format control expressions called\n conversion specifiers.\n\n

You are free to insert any literal text within the conversion\n pattern.\n\n

Each conversion specifier starts with a percent sign (%) and is\n followed by optional format modifiers and a conversion\n character. The conversion character specifies the type of\n data, e.g. category, priority, date, thread name. The format\n modifiers control such things as field width, padding, left and\n right justification. The following is a simple example.\n\n

Let the conversion pattern be \"%-5p [%t]: %m%n\" and assume\n that the log4j environment was set to use a PatternLayout. Then the\n statements\n

\n   Category root = Category.getRoot();\n   root.debug(\"Message 1\");\n   root.warn(\"Message 2\");\n   
\n would yield the output\n
\n   DEBUG [main]: Message 1\n   WARN  [main]: Message 2\n   
\n\n

Note that there is no explicit separator between text and\n conversion specifiers. The pattern parser knows when it has reached\n the end of a conversion specifier when it reads a conversion\n character. In the example above the conversion specifier\n %-5p means the priority of the logging event should be left\n justified to a width of five characters.\n\n The recognized conversion characters are\n\n

\n \n \n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n\n \n \n\n \n \n\n \n \n\n \n\n\n \n \n \n \n\n \n \n\n \n\n \n \n\n \n\n \n \n \n \n\n \n\n \n\n \n \n\n\n \n \n\n \n\n \n\n \n\n \n\n \n \n\n\n \n \n\n \n \n\n \n\n \n\n \n \n\n
Conversion CharacterEffect
cUsed to output the category of the logging event. The\n category conversion specifier can be optionally followed by\n precision specifier, that is a decimal constant in\n brackets.\n\n

If a precision specifier is given, then only the corresponding\n number of right most components of the category name will be\n printed. By default the category name is printed in full.\n\n

For example, for the category name \"a.b.c\" the pattern\n %c{2} will output \"b.c\".\n\n

CUsed to output the fully qualified class name of the caller\n issuing the logging request. This conversion specifier\n can be optionally followed by precision specifier, that\n is a decimal constant in brackets.\n\n

If a precision specifier is given, then only the corresponding\n number of right most components of the class name will be\n printed. By default the class name is output in fully qualified form.\n\n

For example, for the class name \"org.apache.xyz.SomeClass\", the\n pattern %C{1} will output \"SomeClass\".\n\n

WARNING Generating the caller class information is\n slow. Thus, use should be avoided unless execution speed is\n not an issue.\n\n

d Used to output the date of\n\t the logging event. The date conversion specifier may be\n\t followed by a date format specifier enclosed between\n\t braces. For example, %d{HH:mm:ss,SSS} or\n\t %d{dd MMM yyyy HH:mm:ss,SSS}. If no\n\t date format specifier is given then ISO8601 format is\n\t assumed.\n\n\t

The date format specifier admits the same syntax as the\n\t time pattern string of the {@link\n\t java.text.SimpleDateFormat}. Although part of the standard\n\t JDK, the performance of SimpleDateFormat is\n\t quite poor.\n\n\t

For better results it is recommended to use the log4j date\n\t formatters. These can be specified using one of the strings\n\t \"ABSOLUTE\", \"DATE\" and \"ISO8601\" for specifying {@link\n\t org.apache.log4j.helpers.AbsoluteTimeDateFormat\n\t AbsoluteTimeDateFormat}, {@link\n\t org.apache.log4j.helpers.DateTimeDateFormat DateTimeDateFormat}\n\t and respectively {@link\n\t org.apache.log4j.helpers.ISO8601DateFormat\n\t ISO8601DateFormat}. For example, %d{ISO8601} or\n\t %d{ABSOLUTE}.\n\n\t

These dedicated date formatters perform significantly\n\t better than {@link java.text.SimpleDateFormat}.\n

FUsed to output the file name where the logging request was\n issued.\n\n

WARNING Generating caller location information is\n extremely slow and should be avoided unless execution speed\n is not an issue.\n\n

lUsed to output location information of the caller which generated\n the logging event.\n\n

The location information depends on the JVM implementation but\n usually consists of the fully qualified name of the calling\n method followed by the callers source the file name and line\n number between parentheses.\n\n

The location information can be very useful. However, its\n generation is extremely slow and should be avoided\n unless execution speed is not an issue.\n\n

LUsed to output the line number from where the logging request\n was issued.\n\n

WARNING Generating caller location information is\n extremely slow and should be avoided unless execution speed\n is not an issue.\n\n

mUsed to output the application supplied message associated with\n the logging event.
MUsed to output the method name where the logging request was\n issued.\n\n

WARNING Generating caller location information is\n extremely slow and should be avoided unless execution speed\n is not an issue.\n\n

nOutputs the platform dependent line separator character or\n characters.\n\n

This conversion character offers practically the same\n performance as using non-portable line separator strings such as\n \"\\n\", or \"\\r\\n\". Thus, it is the preferred way of specifying a\n line separator.\n\n\n

pUsed to output the priority of the logging event.
rUsed to output the number of milliseconds elapsed from the construction \n of the layout until the creation of the logging event.
tUsed to output the name of the thread that generated the\n logging event.
xUsed to output the NDC (nested diagnostic context) associated\n with the thread that generated the logging event.\n
X \n \n

Used to output the MDC (mapped diagnostic context) associated\n with the thread that generated the logging event. The X\n conversion character must be followed by the key for the\n map placed between braces, as in %X{clientNumber} where\n clientNumber is the key. The value in the MDC\n corresponding to the key will be output.

\n \n

See {@link MDC} class for more details.\n

\n \n
%The sequence %% outputs a single percent sign.\n
\n\n

By default the relevant information is output as is. However,\n with the aid of format modifiers it is possible to change the\n minimum field width, the maximum field width and justification.\n\n

The optional format modifier is placed between the percent sign\n and the conversion character.\n\n

The first optional format modifier is the left justification\n flag which is just the minus (-) character. Then comes the\n optional minimum field width modifier. This is a decimal\n constant that represents the minimum number of characters to\n output. If the data item requires fewer characters, it is padded on\n either the left or the right until the minimum width is\n reached. The default is to pad on the left (right justify) but you\n can specify right padding with the left justification flag. The\n padding character is space. If the data item is larger than the\n minimum field width, the field is expanded to accommodate the\n data. The value is never truncated.\n\n

This behavior can be changed using the maximum field\n width modifier which is designated by a period followed by a\n decimal constant. If the data item is longer than the maximum\n field, then the extra characters are removed from the\n beginning of the data item and not from the end. For\n example, it the maximum field width is eight and the data item is\n ten characters long, then the first two characters of the data item\n are dropped. This behavior deviates from the printf function in C\n where truncation is done from the end.\n\n

Below are various format modifier examples for the category\n conversion specifier.\n\n

\n \n \n \n \n \n \n\n 20 \n \n \n \n \n\n \n \n \n \n \n\n \n \n \n \n \n\n
Format modifier\n left justify\n minimum width\n maximum width\n comment\n\n
%20cfalse20noneLeft pad with spaces if the category name is less than 20\n characters long.\n\n
%-20c true none Right pad with\n spaces if the category name is less than 20 characters long.\n\n
%.30cNAnone30Truncate from the beginning if the category name is longer than 30\n characters.\n\n
%20.30cfalse2030Left pad with spaces if the category name is shorter than 20\n characters. However, if category name is longer than 30 characters,\n then truncate from the beginning.\n\n
%-20.30ctrue2030Right pad with spaces if the category name is shorter than 20\n characters. However, if category name is longer than 30 characters,\n then truncate from the beginning.\n\n
\n\n

Below are some examples of conversion patterns.\n\n

\n\n

%r [%t] %-5p %c %x - %m%n\n

This is essentially the TTCC layout.\n\n

%-6r [%15.15t] %-5p %30.30c %x - %m%n\n\n

Similar to the TTCC layout except that the relative time is\n right padded if less than 6 digits, thread name is right padded if\n less than 15 characters and truncated if longer and the category\n name is left padded if shorter than 30 characters and truncated if\n longer.\n\n
\n\n

The above text is largely inspired from Peter A. Darnell and\n Philip E. Margolis' highly recommended book \"C -- a Software\n Engineering Approach\", ISBN 0-387-97389-3.\n\n @author James P. Cakalic\n @author Ceki Gülcü\n\n\n @since 0.8.2 */\npublic class PatternLayout extends Layout {\n\n\n /** Default pattern string for log output. Currently set to the\n string \"%m%n\" which just prints the application supplied\n message. */\n public final static String DEFAULT_CONVERSION_PATTERN =\"%m%n\";\n\n /** A conversion pattern equivalent to the TTCCCLayout.\n Current value is %r [%t] %p %c %x - %m%n. */\n public final static String TTCC_CONVERSION_PATTERN\n = \"%r [%t] %p %c %x - %m%n\";\n\n\n protected final int BUF_SIZE = 256;\n protected final int MAX_CAPACITY = 1024;\n\n\n // output buffer appended to when format() is invoked\n private StringBuffer sbuf = new StringBuffer(BUF_SIZE);\n\n private String pattern;\n\n private PatternConverter head;\n\n /**\n Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN.\n\n The default pattern just produces the application supplied message.\n */\n public PatternLayout() {\n this(DEFAULT_CONVERSION_PATTERN);\n }\n\n /**\n Constructs a PatternLayout using the supplied conversion pattern.\n */\n public PatternLayout(String pattern) {\n this.pattern = pattern;\n head = createPatternParser((pattern == null) ? DEFAULT_CONVERSION_PATTERN :\n\t\t\t pattern).parse();\n }\n\n /**\n Set the ConversionPattern option. This is the string which\n controls formatting and consists of a mix of literal content and\n conversion specifiers.\n */\n public\n void setConversionPattern(String conversionPattern) {\n pattern = conversionPattern;\n head = createPatternParser(conversionPattern).parse();\n }\n\n /**\n Returns the value of the ConversionPattern option.\n */\n public\n String getConversionPattern() {\n return pattern;\n }\n\n /**\n Does not do anything as options become effective\n */\n public\n void activateOptions() {\n // nothing to do.\n }\n\n /**\n The PatternLayout does not handle the throwable contained within\n {@link LoggingEvent LoggingEvents}. Thus, it returns\n true.\n\n @since 0.8.4 */\n public\n boolean ignoresThrowable() {\n return true;\n }\n\n /**\n Returns PatternParser used to parse the conversion string. Subclasses\n may override this to return a subclass of PatternParser which recognize\n custom conversion characters.\n\n @since 0.9.0\n */\n protected PatternParser createPatternParser(String pattern) {\n return new PatternParser(pattern);\n }\n\n\n /**\n Produces a formatted string as specified by the conversion pattern.\n */\n public String format(LoggingEvent event) {\n // Reset working stringbuffer\n if(sbuf.capacity() > MAX_CAPACITY) {\n sbuf = new StringBuffer(BUF_SIZE);\n } else {\n sbuf.setLength(0);\n }\n\n PatternConverter c = head;\n\n while(c != null) {\n c.format(sbuf, event);\n c = c.next;\n }\n return sbuf.toString();\n }\n}\n", "file_name": "PatternLayout.java", "human_label": "Format the buffered string with the pattern converter, and return the result.", "level": "project_runnable", "lineno": "492", "name": "format", "oracle_context": "{ \"apis\" : \"[capacity, setLength, toString]\", \"classes\" : \"[PatternConverter]\", \"vars\" : \"[next, sbuf, MAX_CAPACITY, BUF_SIZE, head]\" }", "package": "org.apache.log4j", "project": "logging-log4j1-main" }, { "_id": "636767031a6d9265ec0178dd", "all_context": "{ \"class_level\" : \"import javax.servlet.http.HttpServletRequest;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport static java.lang.String.format;\\nHttpServletRequest request;\\nServletRequestContext(HttpServletRequest request);\\ngetCharacterEncoding();\\ngetContentType();\\ngetInputStream();\\ntoString();\\n\", \"repo_level\" : \"\" }", "class_name": "ServletRequestContext", "code": "public long contentLength(){\n long size;\n try {\n size=Long.parseLong(request.getHeader(FileUpload.CONTENT_LENGTH));\n }\n catch ( NumberFormatException e) {\n size=request.getContentLength();\n }\n return size;\n}\n", "docstring": "/** \n * Retrieve the content length of the request.\n * @return The content length of the request.\n * @since 1.3\n */\n", "end_lineno": "73", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.web.upload;\nimport javax.servlet.http.HttpServletRequest;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport static java.lang.String.format;\n\n/**\n *

Provides access to the request information needed for a request made to an HTTP servlet.

\n * @since FileUpload 1.1\n * @version $Id: ServletRequestContext.java 1564788 2014-02-05 14:36:41Z markt $\n */\nclass ServletRequestContext {\n // ----------------------------------------------------- Instance Variables\n /** The request for which the context is being provided. */\n private final HttpServletRequest request;\n // ----------------------------------------------------------- Constructors\n\n /**\n * Construct a context for this request.\n * @param request The request to which this context applies.\n */\n public ServletRequestContext(HttpServletRequest request) {\n this.request = request;\n }\n // --------------------------------------------------------- Public Methods\n\n /**\n * Retrieve the character encoding for the request.\n * @return The character encoding for the request.\n */\n public String getCharacterEncoding() {\n return request.getCharacterEncoding();\n }\n\n /**\n * Retrieve the content type of the request.\n * @return The content type of the request.\n */\n public String getContentType() {\n return request.getContentType();\n }\n\n /**\n * Retrieve the content length of the request.\n * @return The content length of the request.\n * @since 1.3\n */\n public long contentLength() {\n long size;\n try {\n size = Long.parseLong(request.getHeader(FileUpload.CONTENT_LENGTH));\n } catch (NumberFormatException e) {\n size = request.getContentLength();\n }\n return size;\n }\n\n /**\n * Retrieve the input stream for the request.\n * @return The input stream for the request.\n *\n * @throws IOException if a problem occurs.\n */\n public InputStream getInputStream() throws IOException {\n return request.getInputStream();\n }\n\n /**\n * Returns a string representation of this object.\n * @return a string representation of this object.\n */\n @Override\n public String toString() {\n return format(\"ContentLength=%s, ContentType=%s\", Long.valueOf(this.contentLength()), this.getContentType());\n }\n}", "file_name": "ServletRequestContext.java", "human_label": "Compute and return the length of the request content header, return the content length if NumberFormatException happens.", "level": "project_runnable", "lineno": "60", "name": "contentLength", "oracle_context": "{ \"apis\" : \"[parseLong, getHeader, getContentLength]\", \"classes\" : \"[FileUpload]\", \"vars\" : \"[CONTENT_LENGTH, request]\" }", "package": "net.hasor.web.upload", "project": "hasor-master" }, { "_id": "636766f11a6d9265ec017658", "all_context": "{ \"class_level\" : \"import java.io.File;\\nimport java.util.Collection;\\nchar EXTENSION_SEPARATOR;\\nString EXTENSION_SEPARATOR_STR;\\nchar UNIX_SEPARATOR;\\nchar WINDOWS_SEPARATOR;\\nchar SYSTEM_SEPARATOR;\\nchar OTHER_SEPARATOR;\\nFilenameUtils();\\nisSeparator(char ch);\\nnormalize(String filename);\\nnormalize(String filename,boolean unixSeparator);\\nnormalizeNoEndSeparator(String filename);\\nnormalizeNoEndSeparator(String filename,boolean unixSeparator);\\ndoNormalize(String filename,char separator,boolean keepSeparator);\\nconcat(String basePath,String fullFilenameToAdd);\\nseparatorsToUnix(String path);\\nseparatorsToWindows(String path);\\nseparatorsToSystem(String path);\\ngetPrefixLength(String filename);\\nindexOfLastSeparator(String filename);\\nindexOfExtension(String filename);\\ngetPrefix(String filename);\\ngetPath(String filename);\\ngetPathNoEndSeparator(String filename);\\ndoGetPath(String filename,int separatorAdd);\\ngetFullPath(String filename);\\ngetFullPathNoEndSeparator(String filename);\\ndoGetFullPath(String filename,boolean includeSeparator);\\ngetName(String filename);\\ngetBaseName(String filename);\\ngetExtension(String filename);\\nremoveExtension(String filename);\\nisExtension(String filename,String extension);\\nisExtension(String filename,String[] extensions);\\nisExtension(String filename,Collection extensions);\\nisSystemWindows();\\n\", \"repo_level\" : \"\" }", "class_name": "FilenameUtils", "code": "public static int indexOfLastSeparator(String filename){\n if (filename == null) {\n return -1;\n }\n int lastUnixPos=filename.lastIndexOf(UNIX_SEPARATOR);\n int lastWindowsPos=filename.lastIndexOf(WINDOWS_SEPARATOR);\n return Math.max(lastUnixPos,lastWindowsPos);\n}\n", "docstring": "/** \n * Returns the index of the last directory separator character.

This method will handle a file in either Unix or Windows format. The position of the last forward or backslash is returned.

The output will be the same irrespective of the machine that the code is running on.\n * @param filename the filename to find the last path separator in, null returns -1\n * @return the index of the last separator character, or -1 if thereis no such character\n */\n", "end_lineno": "635", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.io;\nimport java.io.File;\nimport java.util.Collection;\n\n/**\n * General filename and filepath manipulation utilities.\n *

\n * When dealing with filenames you can hit problems when moving from a Windows\n * based development machine to a Unix based production machine.\n * This class aims to help avoid those problems.\n *

\n * NOTE: You may be able to avoid using this class entirely simply by\n * using JDK {@link File File} objects and the two argument constructor\n * {@link File#File(File, String) File(File,String)}.\n *

\n * Most methods on this class are designed to work the same on both Unix and Windows.\n * Those that don't include 'System', 'Unix' or 'Windows' in their name.\n *

\n * Most methods recognise both separators (forward and back), and both\n * sets of prefixes. See the javadoc of each method for details.\n *

\n * This class defines six components within a filename\n * (example C:\\dev\\project\\file.txt):\n *

    \n *
  • the prefix - C:\\
  • \n *
  • the path - dev\\project\\
  • \n *
  • the full path - C:\\dev\\project\\
  • \n *
  • the name - file.txt
  • \n *
  • the base name - file
  • \n *
  • the extension - txt
  • \n *
\n * Note that this class works best if directory filenames end with a separator.\n * If you omit the last separator, it is impossible to determine if the filename\n * corresponds to a file or a directory. As a result, we have chosen to say\n * it corresponds to a file.\n *

\n * This class only supports Unix and Windows style names.\n * Prefixes are matched as follows:\n *

\n * Windows:\n * a\\b\\c.txt           --> \"\"          --> relative\n * \\a\\b\\c.txt          --> \"\\\"         --> current drive absolute\n * C:a\\b\\c.txt         --> \"C:\"        --> drive relative\n * C:\\a\\b\\c.txt        --> \"C:\\\"       --> absolute\n * \\\\server\\a\\b\\c.txt  --> \"\\\\server\\\" --> UNC\n *\n * Unix:\n * a/b/c.txt           --> \"\"          --> relative\n * /a/b/c.txt          --> \"/\"         --> absolute\n * ~/a/b/c.txt         --> \"~/\"        --> current user\n * ~                   --> \"~/\"        --> current user (slash added)\n * ~user/a/b/c.txt     --> \"~user/\"    --> named user\n * ~user               --> \"~user/\"    --> named user (slash added)\n * 
\n * Both prefix styles are matched always, irrespective of the machine that you are\n * currently running on.\n *

\n * Origin of code: Excalibur, Alexandria, Tomcat, Commons-Utils.\n *\n * @version $Id: FilenameUtils.java 1307462 2012-03-30 15:13:11Z ggregory $\n * @since 1.1\n */\npublic class FilenameUtils {\n /**\n * The extension separator character.\n * @since 1.4\n */\n public static final char EXTENSION_SEPARATOR = '.';\n /**\n * The extension separator String.\n * @since 1.4\n */\n public static final String EXTENSION_SEPARATOR_STR = Character.toString(EXTENSION_SEPARATOR);\n /**\n * The Unix separator character.\n */\n private static final char UNIX_SEPARATOR = '/';\n /**\n * The Windows separator character.\n */\n private static final char WINDOWS_SEPARATOR = '\\\\';\n /**\n * The system separator character.\n */\n private static final char SYSTEM_SEPARATOR = File.separatorChar;\n /**\n * The separator character that is the opposite of the system separator.\n */\n private static final char OTHER_SEPARATOR;\n\n static {\n if (isSystemWindows()) {\n OTHER_SEPARATOR = UNIX_SEPARATOR;\n } else {\n OTHER_SEPARATOR = WINDOWS_SEPARATOR;\n }\n }\n\n /**\n * Instances should NOT be constructed in standard programming.\n */\n public FilenameUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n * Determines if Windows file system is in use.\n *\n * @return true if the system is Windows\n */\n static boolean isSystemWindows() {\n return SYSTEM_SEPARATOR == WINDOWS_SEPARATOR;\n }\n //-----------------------------------------------------------------------\n\n /**\n * Checks if the character is a separator.\n *\n * @param ch the character to check\n * @return true if it is a separator character\n */\n private static boolean isSeparator(char ch) {\n return ch == UNIX_SEPARATOR || ch == WINDOWS_SEPARATOR;\n }\n //-----------------------------------------------------------------------\n\n /**\n * Normalizes a path, removing double and single dot path steps.\n *

\n * This method normalizes a path to a standard format.\n * The input may contain separators in either Unix or Windows format.\n * The output will contain separators in the format of the system.\n *

\n * A trailing slash will be retained.\n * A double slash will be merged to a single slash (but UNC names are handled).\n * A single dot path segment will be removed.\n * A double dot will cause that path segment and the one before to be removed.\n * If the double dot has no parent path segment to work with, {@code null}\n * is returned.\n *

\n * The output will be the same on both Unix and Windows except\n * for the separator character.\n *

\n     * /foo//               -->   /foo/\n     * /foo/./              -->   /foo/\n     * /foo/../bar          -->   /bar\n     * /foo/../bar/         -->   /bar/\n     * /foo/../bar/../baz   -->   /baz\n     * //foo//./bar         -->   /foo/bar\n     * /../                 -->   null\n     * ../foo               -->   null\n     * foo/bar/..           -->   foo/\n     * foo/../../bar        -->   null\n     * foo/../bar           -->   bar\n     * //server/foo/../bar  -->   //server/bar\n     * //server/../bar      -->   null\n     * C:\\foo\\..\\bar        -->   C:\\bar\n     * C:\\..\\bar            -->   null\n     * ~/foo/../bar/        -->   ~/bar/\n     * ~/../bar             -->   null\n     * 
\n * (Note the file separator returned will be correct for Windows/Unix)\n *\n * @param filename the filename to normalize, null returns null\n * @return the normalized filename, or null if invalid\n */\n public static String normalize(String filename) {\n return doNormalize(filename, SYSTEM_SEPARATOR, true);\n }\n\n /**\n * Normalizes a path, removing double and single dot path steps.\n *

\n * This method normalizes a path to a standard format.\n * The input may contain separators in either Unix or Windows format.\n * The output will contain separators in the format specified.\n *

\n * A trailing slash will be retained.\n * A double slash will be merged to a single slash (but UNC names are handled).\n * A single dot path segment will be removed.\n * A double dot will cause that path segment and the one before to be removed.\n * If the double dot has no parent path segment to work with, {@code null}\n * is returned.\n *

\n * The output will be the same on both Unix and Windows except\n * for the separator character.\n *

\n     * /foo//               -->   /foo/\n     * /foo/./              -->   /foo/\n     * /foo/../bar          -->   /bar\n     * /foo/../bar/         -->   /bar/\n     * /foo/../bar/../baz   -->   /baz\n     * //foo//./bar         -->   /foo/bar\n     * /../                 -->   null\n     * ../foo               -->   null\n     * foo/bar/..           -->   foo/\n     * foo/../../bar        -->   null\n     * foo/../bar           -->   bar\n     * //server/foo/../bar  -->   //server/bar\n     * //server/../bar      -->   null\n     * C:\\foo\\..\\bar        -->   C:\\bar\n     * C:\\..\\bar            -->   null\n     * ~/foo/../bar/        -->   ~/bar/\n     * ~/../bar             -->   null\n     * 
\n * The output will be the same on both Unix and Windows including\n * the separator character.\n *\n * @param filename the filename to normalize, null returns null\n * @param unixSeparator {@code true} if a unix separator should\n * be used or {@code false} if a windows separator should be used.\n * @return the normalized filename, or null if invalid\n * @since 2.0\n */\n public static String normalize(String filename, boolean unixSeparator) {\n char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR;\n return doNormalize(filename, separator, true);\n }\n //-----------------------------------------------------------------------\n\n /**\n * Normalizes a path, removing double and single dot path steps,\n * and removing any final directory separator.\n *

\n * This method normalizes a path to a standard format.\n * The input may contain separators in either Unix or Windows format.\n * The output will contain separators in the format of the system.\n *

\n * A trailing slash will be removed.\n * A double slash will be merged to a single slash (but UNC names are handled).\n * A single dot path segment will be removed.\n * A double dot will cause that path segment and the one before to be removed.\n * If the double dot has no parent path segment to work with, {@code null}\n * is returned.\n *

\n * The output will be the same on both Unix and Windows except\n * for the separator character.\n *

\n     * /foo//               -->   /foo\n     * /foo/./              -->   /foo\n     * /foo/../bar          -->   /bar\n     * /foo/../bar/         -->   /bar\n     * /foo/../bar/../baz   -->   /baz\n     * //foo//./bar         -->   /foo/bar\n     * /../                 -->   null\n     * ../foo               -->   null\n     * foo/bar/..           -->   foo\n     * foo/../../bar        -->   null\n     * foo/../bar           -->   bar\n     * //server/foo/../bar  -->   //server/bar\n     * //server/../bar      -->   null\n     * C:\\foo\\..\\bar        -->   C:\\bar\n     * C:\\..\\bar            -->   null\n     * ~/foo/../bar/        -->   ~/bar\n     * ~/../bar             -->   null\n     * 
\n * (Note the file separator returned will be correct for Windows/Unix)\n *\n * @param filename the filename to normalize, null returns null\n * @return the normalized filename, or null if invalid\n */\n public static String normalizeNoEndSeparator(String filename) {\n return doNormalize(filename, SYSTEM_SEPARATOR, false);\n }\n\n /**\n * Normalizes a path, removing double and single dot path steps,\n * and removing any final directory separator.\n *

\n * This method normalizes a path to a standard format.\n * The input may contain separators in either Unix or Windows format.\n * The output will contain separators in the format specified.\n *

\n * A trailing slash will be removed.\n * A double slash will be merged to a single slash (but UNC names are handled).\n * A single dot path segment will be removed.\n * A double dot will cause that path segment and the one before to be removed.\n * If the double dot has no parent path segment to work with, {@code null}\n * is returned.\n *

\n * The output will be the same on both Unix and Windows including\n * the separator character.\n *

\n     * /foo//               -->   /foo\n     * /foo/./              -->   /foo\n     * /foo/../bar          -->   /bar\n     * /foo/../bar/         -->   /bar\n     * /foo/../bar/../baz   -->   /baz\n     * //foo//./bar         -->   /foo/bar\n     * /../                 -->   null\n     * ../foo               -->   null\n     * foo/bar/..           -->   foo\n     * foo/../../bar        -->   null\n     * foo/../bar           -->   bar\n     * //server/foo/../bar  -->   //server/bar\n     * //server/../bar      -->   null\n     * C:\\foo\\..\\bar        -->   C:\\bar\n     * C:\\..\\bar            -->   null\n     * ~/foo/../bar/        -->   ~/bar\n     * ~/../bar             -->   null\n     * 
\n *\n * @param filename the filename to normalize, null returns null\n * @param unixSeparator {@code true} if a unix separator should\n * be used or {@code false} if a windows separtor should be used.\n * @return the normalized filename, or null if invalid\n * @since 2.0\n */\n public static String normalizeNoEndSeparator(String filename, boolean unixSeparator) {\n char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR;\n return doNormalize(filename, separator, false);\n }\n\n /**\n * Internal method to perform the normalization.\n *\n * @param filename the filename\n * @param separator The separator character to use\n * @param keepSeparator true to keep the final separator\n * @return the normalized filename\n */\n private static String doNormalize(String filename, char separator, boolean keepSeparator) {\n if (filename == null) {\n return null;\n }\n int size = filename.length();\n if (size == 0) {\n return filename;\n }\n int prefix = getPrefixLength(filename);\n if (prefix < 0) {\n return null;\n }\n char[] array = new char[size + 2]; // +1 for possible extra slash, +2 for arraycopy\n filename.getChars(0, filename.length(), array, 0);\n // fix separators throughout\n char otherSeparator = separator == SYSTEM_SEPARATOR ? OTHER_SEPARATOR : SYSTEM_SEPARATOR;\n for (int i = 0; i < array.length; i++) {\n if (array[i] == otherSeparator) {\n array[i] = separator;\n }\n }\n // add extra separator on the end to simplify code below\n boolean lastIsDirectory = true;\n if (array[size - 1] != separator) {\n array[size++] = separator;\n lastIsDirectory = false;\n }\n // adjoining slashes\n for (int i = prefix + 1; i < size; i++) {\n if (array[i] == separator && array[i - 1] == separator) {\n System.arraycopy(array, i, array, i - 1, size - i);\n size--;\n i--;\n }\n }\n // dot slash\n for (int i = prefix + 1; i < size; i++) {\n if (array[i] == separator && array[i - 1] == '.' && (i == prefix + 1 || array[i - 2] == separator)) {\n if (i == size - 1) {\n lastIsDirectory = true;\n }\n System.arraycopy(array, i + 1, array, i - 1, size - i);\n size -= 2;\n i--;\n }\n }\n // double dot slash\n outer:\n for (int i = prefix + 2; i < size; i++) {\n if (array[i] == separator && array[i - 1] == '.' && array[i - 2] == '.' && (i == prefix + 2 || array[i - 3] == separator)) {\n if (i == prefix + 2) {\n return null;\n }\n if (i == size - 1) {\n lastIsDirectory = true;\n }\n int j;\n for (j = i - 4; j >= prefix; j--) {\n if (array[j] == separator) {\n // remove b/../ from a/b/../c\n System.arraycopy(array, i + 1, array, j + 1, size - i);\n size -= i - j;\n i = j + 1;\n continue outer;\n }\n }\n // remove a/../ from a/../c\n System.arraycopy(array, i + 1, array, prefix, size - i);\n size -= i + 1 - prefix;\n i = prefix + 1;\n }\n }\n if (size <= 0) { // should never be less than 0\n return \"\";\n }\n if (size <= prefix) { // should never be less than prefix\n return new String(array, 0, size);\n }\n if (lastIsDirectory && keepSeparator) {\n return new String(array, 0, size); // keep trailing separator\n }\n return new String(array, 0, size - 1); // lose trailing separator\n }\n //-----------------------------------------------------------------------\n\n /**\n * Concatenates a filename to a base path using normal command line style rules.\n *

\n * The effect is equivalent to resultant directory after changing\n * directory to the first argument, followed by changing directory to\n * the second argument.\n *

\n * The first argument is the base path, the second is the path to concatenate.\n * The returned path is always normalized via {@link #normalize(String)},\n * thus .. is handled.\n *

\n * If pathToAdd is absolute (has an absolute prefix), then\n * it will be normalized and returned.\n * Otherwise, the paths will be joined, normalized and returned.\n *

\n * The output will be the same on both Unix and Windows except\n * for the separator character.\n *

\n     * /foo/ + bar          -->   /foo/bar\n     * /foo + bar           -->   /foo/bar\n     * /foo + /bar          -->   /bar\n     * /foo + C:/bar        -->   C:/bar\n     * /foo + C:bar         -->   C:bar (*)\n     * /foo/a/ + ../bar     -->   foo/bar\n     * /foo/ + ../../bar    -->   null\n     * /foo/ + /bar         -->   /bar\n     * /foo/.. + /bar       -->   /bar\n     * /foo + bar/c.txt     -->   /foo/bar/c.txt\n     * /foo/c.txt + bar     -->   /foo/c.txt/bar (!)\n     * 
\n * (*) Note that the Windows relative drive prefix is unreliable when\n * used with this method.\n * (!) Note that the first parameter must be a path. If it ends with a name, then\n * the name will be built into the concatenated path. If this might be a problem,\n * use {@link #getFullPath(String)} on the base path argument.\n *\n * @param basePath the base path to attach to, always treated as a path\n * @param fullFilenameToAdd the filename (or path) to attach to the base\n * @return the concatenated path, or null if invalid\n */\n public static String concat(String basePath, String fullFilenameToAdd) {\n int prefix = getPrefixLength(fullFilenameToAdd);\n if (prefix < 0) {\n return null;\n }\n if (prefix > 0) {\n return normalize(fullFilenameToAdd);\n }\n if (basePath == null) {\n return null;\n }\n int len = basePath.length();\n if (len == 0) {\n return normalize(fullFilenameToAdd);\n }\n char ch = basePath.charAt(len - 1);\n if (isSeparator(ch)) {\n return normalize(basePath + fullFilenameToAdd);\n } else {\n return normalize(basePath + '/' + fullFilenameToAdd);\n }\n }\n //-----------------------------------------------------------------------\n\n /**\n * Converts all separators to the Unix separator of forward slash.\n *\n * @param path the path to be changed, null ignored\n * @return the updated path\n */\n public static String separatorsToUnix(String path) {\n if (path == null || path.indexOf(WINDOWS_SEPARATOR) == -1) {\n return path;\n }\n return path.replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR);\n }\n\n /**\n * Converts all separators to the Windows separator of backslash.\n *\n * @param path the path to be changed, null ignored\n * @return the updated path\n */\n public static String separatorsToWindows(String path) {\n if (path == null || path.indexOf(UNIX_SEPARATOR) == -1) {\n return path;\n }\n return path.replace(UNIX_SEPARATOR, WINDOWS_SEPARATOR);\n }\n\n /**\n * Converts all separators to the system separator.\n *\n * @param path the path to be changed, null ignored\n * @return the updated path\n */\n public static String separatorsToSystem(String path) {\n if (path == null) {\n return null;\n }\n if (isSystemWindows()) {\n return separatorsToWindows(path);\n } else {\n return separatorsToUnix(path);\n }\n }\n //-----------------------------------------------------------------------\n\n /**\n * Returns the length of the filename prefix, such as C:/ or ~/.\n *

\n * This method will handle a file in either Unix or Windows format.\n *

\n * The prefix length includes the first slash in the full filename\n * if applicable. Thus, it is possible that the length returned is greater\n * than the length of the input string.\n *

\n     * Windows:\n     * a\\b\\c.txt           --> \"\"          --> relative\n     * \\a\\b\\c.txt          --> \"\\\"         --> current drive absolute\n     * C:a\\b\\c.txt         --> \"C:\"        --> drive relative\n     * C:\\a\\b\\c.txt        --> \"C:\\\"       --> absolute\n     * \\\\server\\a\\b\\c.txt  --> \"\\\\server\\\" --> UNC\n     *\n     * Unix:\n     * a/b/c.txt           --> \"\"          --> relative\n     * /a/b/c.txt          --> \"/\"         --> absolute\n     * ~/a/b/c.txt         --> \"~/\"        --> current user\n     * ~                   --> \"~/\"        --> current user (slash added)\n     * ~user/a/b/c.txt     --> \"~user/\"    --> named user\n     * ~user               --> \"~user/\"    --> named user (slash added)\n     * 
\n *

\n * The output will be the same irrespective of the machine that the code is running on.\n * ie. both Unix and Windows prefixes are matched regardless.\n *\n * @param filename the filename to find the prefix in, null returns -1\n * @return the length of the prefix, -1 if invalid or null\n */\n public static int getPrefixLength(String filename) {\n if (filename == null) {\n return -1;\n }\n int len = filename.length();\n if (len == 0) {\n return 0;\n }\n char ch0 = filename.charAt(0);\n if (ch0 == ':') {\n return -1;\n }\n if (len == 1) {\n if (ch0 == '~') {\n return 2; // return a length greater than the input\n }\n return isSeparator(ch0) ? 1 : 0;\n } else {\n if (ch0 == '~') {\n int posUnix = filename.indexOf(UNIX_SEPARATOR, 1);\n int posWin = filename.indexOf(WINDOWS_SEPARATOR, 1);\n if (posUnix == -1 && posWin == -1) {\n return len + 1; // return a length greater than the input\n }\n posUnix = posUnix == -1 ? posWin : posUnix;\n posWin = posWin == -1 ? posUnix : posWin;\n return Math.min(posUnix, posWin) + 1;\n }\n char ch1 = filename.charAt(1);\n if (ch1 == ':') {\n ch0 = Character.toUpperCase(ch0);\n if (ch0 >= 'A' && ch0 <= 'Z') {\n if (len == 2 || isSeparator(filename.charAt(2)) == false) {\n return 2;\n }\n return 3;\n }\n return -1;\n } else if (isSeparator(ch0) && isSeparator(ch1)) {\n int posUnix = filename.indexOf(UNIX_SEPARATOR, 2);\n int posWin = filename.indexOf(WINDOWS_SEPARATOR, 2);\n if (posUnix == -1 && posWin == -1 || posUnix == 2 || posWin == 2) {\n return -1;\n }\n posUnix = posUnix == -1 ? posWin : posUnix;\n posWin = posWin == -1 ? posUnix : posWin;\n return Math.min(posUnix, posWin) + 1;\n } else {\n return isSeparator(ch0) ? 1 : 0;\n }\n }\n }\n\n /**\n * Returns the index of the last directory separator character.\n *

\n * This method will handle a file in either Unix or Windows format.\n * The position of the last forward or backslash is returned.\n *

\n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to find the last path separator in, null returns -1\n * @return the index of the last separator character, or -1 if there\n * is no such character\n */\n public static int indexOfLastSeparator(String filename) {\n if (filename == null) {\n return -1;\n }\n int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR);\n int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR);\n return Math.max(lastUnixPos, lastWindowsPos);\n }\n\n /**\n * Returns the index of the last extension separator character, which is a dot.\n *

\n * This method also checks that there is no directory separator after the last dot.\n * To do this it uses {@link #indexOfLastSeparator(String)} which will\n * handle a file in either Unix or Windows format.\n *

\n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to find the last path separator in, null returns -1\n * @return the index of the last separator character, or -1 if there\n * is no such character\n */\n public static int indexOfExtension(String filename) {\n if (filename == null) {\n return -1;\n }\n int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);\n int lastSeparator = indexOfLastSeparator(filename);\n return lastSeparator > extensionPos ? -1 : extensionPos;\n }\n //-----------------------------------------------------------------------\n\n /**\n * Gets the prefix from a full filename, such as C:/\n * or ~/.\n *

\n * This method will handle a file in either Unix or Windows format.\n * The prefix includes the first slash in the full filename where applicable.\n *

\n     * Windows:\n     * a\\b\\c.txt           --> \"\"          --> relative\n     * \\a\\b\\c.txt          --> \"\\\"         --> current drive absolute\n     * C:a\\b\\c.txt         --> \"C:\"        --> drive relative\n     * C:\\a\\b\\c.txt        --> \"C:\\\"       --> absolute\n     * \\\\server\\a\\b\\c.txt  --> \"\\\\server\\\" --> UNC\n     *\n     * Unix:\n     * a/b/c.txt           --> \"\"          --> relative\n     * /a/b/c.txt          --> \"/\"         --> absolute\n     * ~/a/b/c.txt         --> \"~/\"        --> current user\n     * ~                   --> \"~/\"        --> current user (slash added)\n     * ~user/a/b/c.txt     --> \"~user/\"    --> named user\n     * ~user               --> \"~user/\"    --> named user (slash added)\n     * 
\n *

\n * The output will be the same irrespective of the machine that the code is running on.\n * ie. both Unix and Windows prefixes are matched regardless.\n *\n * @param filename the filename to query, null returns null\n * @return the prefix of the file, null if invalid\n */\n public static String getPrefix(String filename) {\n if (filename == null) {\n return null;\n }\n int len = getPrefixLength(filename);\n if (len < 0) {\n return null;\n }\n if (len > filename.length()) {\n return filename + UNIX_SEPARATOR; // we know this only happens for unix\n }\n return filename.substring(0, len);\n }\n\n /**\n * Gets the path from a full filename, which excludes the prefix.\n *

\n * This method will handle a file in either Unix or Windows format.\n * The method is entirely text based, and returns the text before and\n * including the last forward or backslash.\n *

\n     * C:\\a\\b\\c.txt --> a\\b\\\n     * ~/a/b/c.txt  --> a/b/\n     * a.txt        --> \"\"\n     * a/b/c        --> a/b/\n     * a/b/c/       --> a/b/c/\n     * 
\n *

\n * The output will be the same irrespective of the machine that the code is running on.\n *

\n * This method drops the prefix from the result.\n * See {@link #getFullPath(String)} for the method that retains the prefix.\n *\n * @param filename the filename to query, null returns null\n * @return the path of the file, an empty string if none exists, null if invalid\n */\n public static String getPath(String filename) {\n return doGetPath(filename, 1);\n }\n\n /**\n * Gets the path from a full filename, which excludes the prefix, and\n * also excluding the final directory separator.\n *

\n * This method will handle a file in either Unix or Windows format.\n * The method is entirely text based, and returns the text before the\n * last forward or backslash.\n *

\n     * C:\\a\\b\\c.txt --> a\\b\n     * ~/a/b/c.txt  --> a/b\n     * a.txt        --> \"\"\n     * a/b/c        --> a/b\n     * a/b/c/       --> a/b/c\n     * 
\n *

\n * The output will be the same irrespective of the machine that the code is running on.\n *

\n * This method drops the prefix from the result.\n * See {@link #getFullPathNoEndSeparator(String)} for the method that retains the prefix.\n *\n * @param filename the filename to query, null returns null\n * @return the path of the file, an empty string if none exists, null if invalid\n */\n public static String getPathNoEndSeparator(String filename) {\n return doGetPath(filename, 0);\n }\n\n /**\n * Does the work of getting the path.\n *\n * @param filename the filename\n * @param separatorAdd 0 to omit the end separator, 1 to return it\n * @return the path\n */\n private static String doGetPath(String filename, int separatorAdd) {\n if (filename == null) {\n return null;\n }\n int prefix = getPrefixLength(filename);\n if (prefix < 0) {\n return null;\n }\n int index = indexOfLastSeparator(filename);\n int endIndex = index + separatorAdd;\n if (prefix >= filename.length() || index < 0 || prefix >= endIndex) {\n return \"\";\n }\n return filename.substring(prefix, endIndex);\n }\n\n /**\n * Gets the full path from a full filename, which is the prefix + path.\n *

\n * This method will handle a file in either Unix or Windows format.\n * The method is entirely text based, and returns the text before and\n * including the last forward or backslash.\n *

\n     * C:\\a\\b\\c.txt --> C:\\a\\b\\\n     * ~/a/b/c.txt  --> ~/a/b/\n     * a.txt        --> \"\"\n     * a/b/c        --> a/b/\n     * a/b/c/       --> a/b/c/\n     * C:           --> C:\n     * C:\\          --> C:\\\n     * ~            --> ~/\n     * ~/           --> ~/\n     * ~user        --> ~user/\n     * ~user/       --> ~user/\n     * 
\n *

\n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to query, null returns null\n * @return the path of the file, an empty string if none exists, null if invalid\n */\n public static String getFullPath(String filename) {\n return doGetFullPath(filename, true);\n }\n\n /**\n * Gets the full path from a full filename, which is the prefix + path,\n * and also excluding the final directory separator.\n *

\n * This method will handle a file in either Unix or Windows format.\n * The method is entirely text based, and returns the text before the\n * last forward or backslash.\n *

\n     * C:\\a\\b\\c.txt --> C:\\a\\b\n     * ~/a/b/c.txt  --> ~/a/b\n     * a.txt        --> \"\"\n     * a/b/c        --> a/b\n     * a/b/c/       --> a/b/c\n     * C:           --> C:\n     * C:\\          --> C:\\\n     * ~            --> ~\n     * ~/           --> ~\n     * ~user        --> ~user\n     * ~user/       --> ~user\n     * 
\n *

\n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to query, null returns null\n * @return the path of the file, an empty string if none exists, null if invalid\n */\n public static String getFullPathNoEndSeparator(String filename) {\n return doGetFullPath(filename, false);\n }\n\n /**\n * Does the work of getting the path.\n *\n * @param filename the filename\n * @param includeSeparator true to include the end separator\n * @return the path\n */\n private static String doGetFullPath(String filename, boolean includeSeparator) {\n if (filename == null) {\n return null;\n }\n int prefix = getPrefixLength(filename);\n if (prefix < 0) {\n return null;\n }\n if (prefix >= filename.length()) {\n if (includeSeparator) {\n return getPrefix(filename); // add end slash if necessary\n } else {\n return filename;\n }\n }\n int index = indexOfLastSeparator(filename);\n if (index < 0) {\n return filename.substring(0, prefix);\n }\n int end = index + (includeSeparator ? 1 : 0);\n if (end == 0) {\n end++;\n }\n return filename.substring(0, end);\n }\n\n /**\n * Gets the name minus the path from a full filename.\n *

\n * This method will handle a file in either Unix or Windows format.\n * The text after the last forward or backslash is returned.\n *

\n     * a/b/c.txt --> c.txt\n     * a.txt     --> a.txt\n     * a/b/c     --> c\n     * a/b/c/    --> \"\"\n     * 
\n *

\n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to query, null returns null\n * @return the name of the file without the path, or an empty string if none exists\n */\n public static String getName(String filename) {\n if (filename == null) {\n return null;\n }\n int index = indexOfLastSeparator(filename);\n return filename.substring(index + 1);\n }\n\n /**\n * Gets the base name, minus the full path and extension, from a full filename.\n *

\n * This method will handle a file in either Unix or Windows format.\n * The text after the last forward or backslash and before the last dot is returned.\n *

\n     * a/b/c.txt --> c\n     * a.txt     --> a\n     * a/b/c     --> c\n     * a/b/c/    --> \"\"\n     * 
\n *

\n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to query, null returns null\n * @return the name of the file without the path, or an empty string if none exists\n */\n public static String getBaseName(String filename) {\n return removeExtension(getName(filename));\n }\n\n /**\n * Gets the extension of a filename.\n *

\n * This method returns the textual part of the filename after the last dot.\n * There must be no directory separator after the dot.\n *

\n     * foo.txt      --> \"txt\"\n     * a/b/c.jpg    --> \"jpg\"\n     * a/b.txt/c    --> \"\"\n     * a/b/c        --> \"\"\n     * 
\n *

\n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to retrieve the extension of.\n * @return the extension of the file or an empty string if none exists or {@code null}\n * if the filename is {@code null}.\n */\n public static String getExtension(String filename) {\n if (filename == null) {\n return null;\n }\n int index = indexOfExtension(filename);\n if (index == -1) {\n return \"\";\n } else {\n return filename.substring(index + 1);\n }\n }\n //-----------------------------------------------------------------------\n\n /**\n * Removes the extension from a filename.\n *

\n * This method returns the textual part of the filename before the last dot.\n * There must be no directory separator after the dot.\n *

\n     * foo.txt    --> foo\n     * a\\b\\c.jpg  --> a\\b\\c\n     * a\\b\\c      --> a\\b\\c\n     * a.b\\c      --> a.b\\c\n     * 
\n *

\n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to query, null returns null\n * @return the filename minus the extension\n */\n public static String removeExtension(String filename) {\n if (filename == null) {\n return null;\n }\n int index = indexOfExtension(filename);\n if (index == -1) {\n return filename;\n } else {\n return filename.substring(0, index);\n }\n }\n //-----------------------------------------------------------------------\n\n /**\n * Checks whether the extension of the filename is that specified.\n *

\n * This method obtains the extension as the textual part of the filename\n * after the last dot. There must be no directory separator after the dot.\n * The extension check is case-sensitive on all platforms.\n *\n * @param filename the filename to query, null returns false\n * @param extension the extension to check for, null or empty checks for no extension\n * @return true if the filename has the specified extension\n */\n public static boolean isExtension(String filename, String extension) {\n if (filename == null) {\n return false;\n }\n if (extension == null || extension.length() == 0) {\n return indexOfExtension(filename) == -1;\n }\n String fileExt = getExtension(filename);\n return fileExt.equals(extension);\n }\n\n /**\n * Checks whether the extension of the filename is one of those specified.\n *

\n * This method obtains the extension as the textual part of the filename\n * after the last dot. There must be no directory separator after the dot.\n * The extension check is case-sensitive on all platforms.\n *\n * @param filename the filename to query, null returns false\n * @param extensions the extensions to check for, null checks for no extension\n * @return true if the filename is one of the extensions\n */\n public static boolean isExtension(String filename, String[] extensions) {\n if (filename == null) {\n return false;\n }\n if (extensions == null || extensions.length == 0) {\n return indexOfExtension(filename) == -1;\n }\n String fileExt = getExtension(filename);\n for (String extension : extensions) {\n if (fileExt.equals(extension)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Checks whether the extension of the filename is one of those specified.\n *

\n * This method obtains the extension as the textual part of the filename\n * after the last dot. There must be no directory separator after the dot.\n * The extension check is case-sensitive on all platforms.\n *\n * @param filename the filename to query, null returns false\n * @param extensions the extensions to check for, null checks for no extension\n * @return true if the filename is one of the extensions\n */\n public static boolean isExtension(String filename, Collection extensions) {\n if (filename == null) {\n return false;\n }\n if (extensions == null || extensions.isEmpty()) {\n return indexOfExtension(filename) == -1;\n }\n String fileExt = getExtension(filename);\n for (String extension : extensions) {\n if (fileExt.equals(extension)) {\n return true;\n }\n }\n return false;\n }\n}", "file_name": "FilenameUtils.java", "human_label": "Return the index of the last directory separator character, under Unix or Windows.", "level": "class_runnable", "lineno": "616", "name": "indexOfLastSeparator", "oracle_context": "{ \"apis\" : \"[lastIndexOf, max]\", \"classes\" : \"[]\", \"vars\" : \"[UNIX_SEPARATOR, WINDOWS_SEPARATOR]\" }", "package": "net.hasor.utils.io", "project": "hasor-master" }, { "_id": "636767121a6d9265ec017b0a", "all_context": "{ \"class_level\" : \"import net.hasor.core.Settings;\\nimport net.hasor.utils.ExceptionUtils;\\nimport net.hasor.web.FileItem;\\nimport net.hasor.web.FileItemFactory;\\nimport net.hasor.web.FileItemHeaders;\\nimport net.hasor.web.FileItemStream;\\nimport net.hasor.web.upload.util.Closeable;\\nimport net.hasor.web.upload.util.HeadersSet;\\nimport net.hasor.web.upload.util.LimitedInputStream;\\nimport net.hasor.web.upload.util.Streams;\\nimport javax.servlet.http.HttpServletRequest;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport java.nio.charset.StandardCharsets;\\nimport java.util.*;\\nimport static java.lang.String.format;\\nimport static net.hasor.web.upload.FileUploadException.UploadErrorCodes.*;\\nString CONTENT_TYPE;\\nString CONTENT_DISPOSITION;\\nString CONTENT_LENGTH;\\nString FORM_DATA;\\nString ATTACHMENT;\\nString MULTIPART;\\nString MULTIPART_FORM_DATA;\\nString MULTIPART_MIXED;\\nString POST_METHOD;\\nlong sizeMax;\\nlong fileSizeMax;\\nString headerEncoding;\\nString contentType;\\nString fieldName;\\nString name;\\nboolean formField;\\nInputStream stream;\\nboolean opened;\\nFileItemHeaders headers;\\nMultipartStream multi;\\nbyte[] boundary;\\nFileItemStreamImpl currentItem;\\nString currentFieldName;\\nboolean skipPreamble;\\nboolean itemValid;\\nboolean eof;\\nFileUpload();\\nFileUpload(Settings settings);\\ngetSizeMax();\\nsetSizeMax(long sizeMax);\\ngetFileSizeMax();\\nsetFileSizeMax(long fileSizeMax);\\ngetHeaderEncoding();\\nsetHeaderEncoding(String encoding);\\ngetItemIterator(HttpServletRequest request);\\nparseRequest(HttpServletRequest request,FileItemFactory factory);\\ngetBoundary(String contentType);\\ngetFileName(FileItemHeaders headers);\\ngetFileName(String pContentDisposition);\\ngetFieldName(FileItemHeaders headers);\\ngetFieldName(String pContentDisposition);\\ngetParsedHeaders(String headerPart);\\nparseEndOfLine(String headerPart,int end);\\nparseHeaderLine(HeadersSet headers,String header);\\nFileItemStreamImpl(FileItemHeaders headers,String pName,String pFieldName,boolean pFormField,long pContentLength);\\nraiseError(long pSizeMax,long pCount);\\ngetContentType();\\ngetFieldName();\\ngetName();\\nisFormField();\\nopenStream();\\nclose();\\ngetHeaders();\\nFileItemIteratorImpl(ServletRequestContext ctx);\\nfindNextItem();\\ngetContentLength(FileItemHeaders pHeaders);\\nremove();\\nhasNext();\\nnext();\\nisMultipartContent(HttpServletRequest request);\\n\", \"repo_level\" : \"public interface Settings {public String[] getSettingArray();\\npublic Settings getSettings(String namespace);\\npublic void refresh();\\npublic void setSetting(String key,Object value);\\npublic void setSetting(String key,Object value,String namespace);\\npublic void removeSetting(String s);\\npublic void removeSetting(String key,String namespace);\\npublic void addSetting(String key,Object var);\\npublic void addSetting(String key,Object var,String namespace);\\npublic Character getChar(String name);\\npublic Character getChar(String name,Character defaultValue);\\npublic String getString(String name);\\npublic String getString(String name,String defaultValue);\\npublic Boolean getBoolean(String name);\\npublic Boolean getBoolean(String name,Boolean defaultValue);\\npublic Short getShort(String name);\\npublic Short getShort(String name,Short defaultValue);\\npublic Integer getInteger(String name);\\npublic Integer getInteger(String name,Integer defaultValue);\\npublic Long getLong(String name);\\npublic Long getLong(String name,Long defaultValue);\\npublic Float getFloat(String name);\\npublic Float getFloat(String name,Float defaultValue);\\npublic Double getDouble(String name);\\npublic Double getDouble(String name,Double defaultValue);\\npublic Date getDate(String name);\\npublic Date getDate(String name,Date defaultValue);\\npublic Date getDate(String name,long defaultValue);\\npublic Date getDate(String name,String format);\\npublic Date getDate(String name,String format,Date defaultValue);\\npublic Date getDate(String name,String format,long defaultValue);\\npublic T getEnum(String name,Class enmType);\\npublic T getEnum(String name,Class enmType,T defaultValue);\\npublic String getFilePath(String name);\\npublic String getFilePath(String name,String defaultValue);\\npublic String getDirectoryPath(String name);\\npublic String getDirectoryPath(String name,String defaultValue);\\npublic SettingNode getNode(String name);\\npublic Character[] getCharArray(String name);\\npublic Character[] getCharArray(String name,Character defaultValue);\\npublic String[] getStringArray(String name);\\npublic String[] getStringArray(String name,String defaultValue);\\npublic Boolean[] getBooleanArray(String name);\\npublic Boolean[] getBooleanArray(String name,Boolean defaultValue);\\npublic Short[] getShortArray(String name);\\npublic Short[] getShortArray(String name,Short defaultValue);\\npublic Integer[] getIntegerArray(String name);\\npublic Integer[] getIntegerArray(String name,Integer defaultValue);\\npublic Long[] getLongArray(String name);\\npublic Long[] getLongArray(String name,Long defaultValue);\\npublic Float[] getFloatArray(String name);\\npublic Float[] getFloatArray(String name,Float defaultValue);\\npublic Double[] getDoubleArray(String name);\\npublic Double[] getDoubleArray(String name,Double defaultValue);\\npublic Date[] getDateArray(String name);\\npublic Date[] getDateArray(String name,Date defaultValue);\\npublic Date[] getDateArray(String name,long defaultValue);\\npublic Date[] getDateArray(String name,String format);\\npublic Date[] getDateArray(String name,String format,Date defaultValue);\\npublic Date[] getDateArray(String name,String format,long defaultValue);\\npublic T[] getEnumArray(String name,Class enmType);\\npublic T[] getEnumArray(String name,Class enmType,T defaultValue);\\npublic String[] getFilePathArray(String name);\\npublic String[] getFilePathArray(String name,String defaultValue);\\npublic String[] getDirectoryPathArray(String name);\\npublic String[] getDirectoryPathArray(String name,String defaultValue);\\npublic SettingNode[] getNodeArray(String name);\\n }\\npublic interface ExceptionUtils {static RuntimeException toRuntime(Throwable proxy);\\nstatic RuntimeException toRuntime(Throwable proxy,Function convert);\\nstatic Throwable toRuntime(Throwable proxy,Class[] exceptionTypes);\\nstatic Throwable getRootCause(Throwable throwable);\\nstatic int getThrowableCount(Throwable throwable);\\nstatic Throwable[] getThrowables(Throwable throwable);\\nstatic List getThrowableList(Throwable throwable);\\nstatic int indexOfThrowable(Throwable throwable,Class clazz);\\nstatic int indexOfThrowable(Throwable throwable,Class clazz,int fromIndex);\\nstatic int indexOfType(Throwable throwable,Class type);\\nstatic int indexOfType(Throwable throwable,Class type,int fromIndex);\\nstatic void printRootCauseStackTrace(Throwable throwable);\\nstatic void printRootCauseStackTrace(Throwable throwable,PrintStream stream);\\nstatic void printRootCauseStackTrace(Throwable throwable,PrintWriter writer);\\nstatic String[] getRootCauseStackTrace(Throwable throwable);\\nstatic void removeCommonFrames(List causeFrames,List wrapperFrames);\\nstatic String getStackTrace(Throwable throwable);\\nstatic String[] getStackFrames(Throwable throwable);\\nstatic String[] getStackFrames(String stackTrace);\\nstatic List getStackFrameList(Throwable t);\\nstatic String getMessage(Throwable th);\\nstatic String getRootCauseMessage(Throwable th);\\n }\\npublic interface FileItem {public long getSize();\\npublic void writeTo(OutputStream outStream);\\npublic void deleteOrSkip();\\npublic byte[] get();\\npublic String getString(String encoding);\\npublic String getString();\\n }\\npublic interface FileItemFactory {public FileItem createItem(FileItemStream itemStream);\\n }\\npublic interface FileItemHeaders {public String getHeader(String name);\\npublic Iterator getHeaders(String name);\\npublic Iterator getHeaderNames();\\n }\\npublic interface FileItemStream {public FileItemHeaders getHeaders();\\npublic String getContentType();\\npublic String getName();\\npublic String getFieldName();\\npublic boolean isFormField();\\npublic InputStream openStream();\\n }\\npublic interface Closeable { void close();\\n boolean isClosed();\\n }\\npublic interface HeadersSet {public String getHeader(String name);\\npublic Iterator getHeaderNames();\\npublic Iterator getHeaders(String name);\\nsynchronized void addHeader(String name,String value);\\n }\\npublic interface LimitedInputStream {abstract void raiseError(long pSizeMax,long pCount);\\npublic int read();\\npublic int read(byte[] b,int off,int len);\\npublic boolean isClosed();\\npublic void close();\\n }\\npublic interface Streams {static long copy(InputStream inputStream,OutputStream outputStream,boolean closeOutputStream);\\nstatic long copy(InputStream inputStream,OutputStream outputStream,boolean closeOutputStream,byte[] buffer);\\nstatic String asString(InputStream inputStream);\\nstatic String asString(InputStream inputStream,String encoding);\\nstatic String checkFileName(String fileName);\\n }\\n\" }", "class_name": "FileUpload", "code": "private int parseEndOfLine(String headerPart,int end){\n int index=end;\n for (; ; ) {\n int offset=headerPart.indexOf('\\r',index);\n if (offset == -1 || offset + 1 >= headerPart.length()) {\n throw new IllegalStateException(\"Expected headers to be terminated by an empty line.\");\n }\n if (headerPart.charAt(offset + 1) == '\\n') {\n return offset;\n }\n index=offset + 1;\n }\n}\n", "docstring": "/** \n * Skips bytes until the end of the current line.\n * @param headerPart The headers, which are being parsed.\n * @param end Index of the last byte, which has yet been processed.\n * @return Index of the \\r\\n sequence, which indicates end of line.\n */\n", "end_lineno": "357", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.web.upload;\nimport net.hasor.core.Settings;\nimport net.hasor.utils.ExceptionUtils;\nimport net.hasor.web.FileItem;\nimport net.hasor.web.FileItemFactory;\nimport net.hasor.web.FileItemHeaders;\nimport net.hasor.web.FileItemStream;\nimport net.hasor.web.upload.util.Closeable;\nimport net.hasor.web.upload.util.HeadersSet;\nimport net.hasor.web.upload.util.LimitedInputStream;\nimport net.hasor.web.upload.util.Streams;\n\nimport javax.servlet.http.HttpServletRequest;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.charset.StandardCharsets;\nimport java.util.*;\n\nimport static java.lang.String.format;\nimport static net.hasor.web.upload.FileUploadException.UploadErrorCodes.*;\n\n/**\n *

High level API for processing file uploads.

\n *\n *

This class handles multiple files per single HTML widget, sent using multipart/mixed encoding type, as specified by\n * RFC 1867.\n *\n *

How the data for individual parts is stored is determined by the factory\n * used to create them; a given part may be in memory, on disk, or somewhere else.

\n *\n * @version $Id: FileUpload.java 1743630 2016-05-13 09:20:45Z jochen $\n */\npublic class FileUpload {\n /** HTTP content type header name. */\n public static final String CONTENT_TYPE = \"Content-type\";\n /** HTTP content disposition header name. */\n public static final String CONTENT_DISPOSITION = \"Content-disposition\";\n /** HTTP content length header name. */\n public static final String CONTENT_LENGTH = \"Content-length\";\n /** Content-disposition value for form data. */\n public static final String FORM_DATA = \"form-data\";\n /** Content-disposition value for file attachment. */\n public static final String ATTACHMENT = \"attachment\";\n /** Part of HTTP content type header. */\n public static final String MULTIPART = \"multipart/\";\n /** HTTP content type header for multipart forms. */\n public static final String MULTIPART_FORM_DATA = \"multipart/form-data\";\n /** HTTP content type header for multiple uploads. */\n public static final String MULTIPART_MIXED = \"multipart/mixed\";\n /** Constant for HTTP POST method. */\n private static final String POST_METHOD = \"POST\";\n // ---------------------------------------------------------- Class methods\n\n /**\n * Utility method that determines whether the request contains multipart content.\n * @param request The servlet request to be evaluated. Must be non-null.\n * @return true if the request is multipart;\n * false otherwise.\n */\n public static final boolean isMultipartContent(HttpServletRequest request) {\n if (!POST_METHOD.equalsIgnoreCase(request.getMethod())) {\n return false;\n }\n String contentType = new ServletRequestContext(request).getContentType();\n if (contentType == null) {\n return false;\n }\n if (contentType.toLowerCase(Locale.ENGLISH).startsWith(MULTIPART)) {\n return true;\n }\n return false;\n }\n // ----------------------------------------------------------- Data members\n /** The maximum size permitted for the complete request, as opposed to {@link #fileSizeMax}. A value of -1 indicates no maximum. */\n private long sizeMax = -1;\n /** The maximum size permitted for a single uploaded file, as opposed to {@link #sizeMax}. A value of -1 indicates no maximum. */\n private long fileSizeMax = -1;\n /** The content encoding to use when reading part headers. */\n private String headerEncoding;\n\n // ----------------------------------------------------- Property accessors\n public FileUpload() {\n }\n\n public FileUpload(Settings settings) {\n this.setHeaderEncoding(Settings.DefaultCharset);\n this.setSizeMax(settings.getInteger(\"hasor.fileupload.maxRequestSize\", -1));\n this.setFileSizeMax(settings.getInteger(\"hasor.fileupload.maxFileSize\", -1));\n }\n\n /**\n * Returns the maximum allowed size of a complete request, as opposed to {@link #getFileSizeMax()}.\n * @return The maximum allowed size, in bytes. The default value of -1 indicates, that there is no limit.\n * @see #setSizeMax(long)\n */\n public long getSizeMax() {\n return sizeMax;\n }\n\n /**\n * Sets the maximum allowed size of a complete request, as opposed to {@link #setFileSizeMax(long)}.\n * @param sizeMax The maximum allowed size, in bytes. The default value of -1 indicates, that there is no limit.\n * @see #getSizeMax()\n */\n public void setSizeMax(long sizeMax) {\n this.sizeMax = sizeMax;\n }\n\n /**\n * Returns the maximum allowed size of a single uploaded file, as opposed to {@link #getSizeMax()}.\n * @see #setFileSizeMax(long)\n * @return Maximum size of a single uploaded file.\n */\n public long getFileSizeMax() {\n return fileSizeMax;\n }\n\n /**\n * Sets the maximum allowed size of a single uploaded file, as opposed to {@link #getSizeMax()}.\n * @see #getFileSizeMax()\n * @param fileSizeMax Maximum size of a single uploaded file.\n */\n public void setFileSizeMax(long fileSizeMax) {\n this.fileSizeMax = fileSizeMax;\n }\n\n /**\n * Retrieves the character encoding used when reading the headers of an individual part.\n * When not specified, or null, the request encoding is used.\n * If that is also not specified, or null, the platform default encoding is used.\n * @return The encoding used to read part headers.\n */\n public String getHeaderEncoding() {\n return headerEncoding;\n }\n\n /**\n * Specifies the character encoding to be used when reading the headers of individual part.\n * When not specified, or null, the request encoding is used.\n * If that is also not specified, or null, the platform default encoding is used.\n * @param encoding The encoding used to read part headers.\n */\n public void setHeaderEncoding(String encoding) {\n headerEncoding = encoding;\n }\n // --------------------------------------------------------- Public methods\n\n /**\n * Processes an RFC 1867 compliant multipart/form-data stream.\n * @param request The request.\n * @return An iterator to instances of FileItemStream\n * parsed from the request, in the order that they were transmitted.\n * @throws net.hasor.web.upload.FileUploadException if there are problems reading/parsing the request or storing files.\n * @throws IOException An I/O error occurred. This may be a network\n * error while communicating with the client or a problem while storing the uploaded content.\n */\n public Iterator getItemIterator(HttpServletRequest request) throws IOException {\n return new FileItemIteratorImpl(new ServletRequestContext(request));\n }\n\n /**\n * Processes an RFC 1867 compliant multipart/form-data stream.\n * @param request the request.\n * @return A list of FileItem instances parsed from the request, in the order that they were transmitted.\n * @throws FileUploadException if there are problems reading/parsing the request or storing files.\n */\n public List parseRequest(HttpServletRequest request, FileItemFactory factory) throws IOException {\n List items = new ArrayList<>();\n boolean successful = false;\n try {\n Iterator fileItems = this.getItemIterator(request);\n if (factory == null) {\n throw new NullPointerException(\"No FileItemFactory has been set.\");\n }\n while (fileItems.hasNext()) {\n FileItemStream itemStream = fileItems.next();\n FileItem fileItem = factory.createItem(itemStream);\n items.add(fileItem);\n }\n successful = true;\n return items;\n } catch (IOException e) {\n throw e;\n } finally {\n if (!successful) {\n for (FileItem fileItem : items) {\n try {\n fileItem.deleteOrSkip();\n } catch (Throwable e) { /*ignore it*/ }\n }\n }\n }\n }\n // ------------------------------------------------------ Protected methods\n\n /**\n * Retrieves the boundary from the Content-type header.\n * @param contentType The value of the content type header from which to extract the boundary value.\n * @return The boundary, as a byte array.\n */\n protected byte[] getBoundary(String contentType) {\n ParameterParser parser = new ParameterParser();\n parser.setLowerCaseNames(true);\n // Parameter parser can handle null input\n Map params = parser.parse(contentType, new char[] { ';', ',' });\n String boundaryStr = params.get(\"boundary\");\n if (boundaryStr == null) {\n return null;\n }\n byte[] boundary;\n boundary = boundaryStr.getBytes(StandardCharsets.ISO_8859_1);\n return boundary;\n }\n\n /**\n * Retrieves the file name from the Content-disposition header.\n * @param headers The HTTP headers object.\n * @return The file name for the current encapsulation.\n */\n protected String getFileName(FileItemHeaders headers) {\n return getFileName(headers.getHeader(CONTENT_DISPOSITION));\n }\n\n /**\n * Returns the given content-disposition headers file name.\n * @param pContentDisposition The content-disposition headers value.\n * @return The file name\n */\n private String getFileName(String pContentDisposition) {\n String fileName = null;\n if (pContentDisposition != null) {\n String cdl = pContentDisposition.toLowerCase(Locale.ENGLISH);\n if (cdl.startsWith(FORM_DATA) || cdl.startsWith(ATTACHMENT)) {\n ParameterParser parser = new ParameterParser();\n parser.setLowerCaseNames(true);\n // Parameter parser can handle null input\n Map params = parser.parse(pContentDisposition, ';');\n if (params.containsKey(\"filename\")) {\n fileName = params.get(\"filename\");\n if (fileName != null) {\n fileName = fileName.trim();\n } else {\n // Even if there is no value, the parameter is present,\n // so we return an empty file name rather than no file\n // name.\n fileName = \"\";\n }\n }\n }\n }\n return fileName;\n }\n\n /**\n * Retrieves the field name from the Content-disposition header.\n * @param headers A Map containing the HTTP request headers.\n * @return The field name for the current encapsulation.\n */\n protected String getFieldName(FileItemHeaders headers) {\n return getFieldName(headers.getHeader(CONTENT_DISPOSITION));\n }\n\n /**\n * Returns the field name, which is given by the content-disposition header.\n * @param pContentDisposition The content-dispositions header value.\n * @return The field jake\n */\n private String getFieldName(String pContentDisposition) {\n String fieldName = null;\n if (pContentDisposition != null && pContentDisposition.toLowerCase(Locale.ENGLISH).startsWith(FORM_DATA)) {\n ParameterParser parser = new ParameterParser();\n parser.setLowerCaseNames(true);\n // Parameter parser can handle null input\n Map params = parser.parse(pContentDisposition, ';');\n fieldName = params.get(\"name\");\n if (fieldName != null) {\n fieldName = fieldName.trim();\n }\n }\n return fieldName;\n }\n\n /**\n *

Parses the header-part and returns as key/value pairs.\n *

If there are multiple headers of the same names, the name will map to a comma-separated list containing the values.\n * @param headerPart The header-part of the current\n * encapsulation.\n * @return A Map containing the parsed HTTP request headers.\n */\n protected FileItemHeaders getParsedHeaders(String headerPart) {\n final int len = headerPart.length();\n HeadersSet headers = new HeadersSet();\n int start = 0;\n for (; ; ) {\n int end = parseEndOfLine(headerPart, start);\n if (start == end) {\n break;\n }\n StringBuilder header = new StringBuilder(headerPart.substring(start, end));\n start = end + 2;\n while (start < len) {\n int nonWs = start;\n while (nonWs < len) {\n char c = headerPart.charAt(nonWs);\n if (c != ' ' && c != '\\t') {\n break;\n }\n ++nonWs;\n }\n if (nonWs == start) {\n break;\n }\n // Continuation line found\n end = parseEndOfLine(headerPart, nonWs);\n header.append(\" \").append(headerPart.substring(nonWs, end));\n start = end + 2;\n }\n parseHeaderLine(headers, header.toString());\n }\n return headers;\n }\n\n /**\n * Skips bytes until the end of the current line.\n * @param headerPart The headers, which are being parsed.\n * @param end Index of the last byte, which has yet been processed.\n * @return Index of the \\r\\n sequence, which indicates end of line.\n */\n private int parseEndOfLine(String headerPart, int end) {\n int index = end;\n for (; ; ) {\n int offset = headerPart.indexOf('\\r', index);\n if (offset == -1 || offset + 1 >= headerPart.length()) {\n throw new IllegalStateException(\"Expected headers to be terminated by an empty line.\");\n }\n if (headerPart.charAt(offset + 1) == '\\n') {\n return offset;\n }\n index = offset + 1;\n }\n }\n\n /**\n * Reads the next header line.\n * @param headers String with all headers.\n * @param header Map where to store the current header.\n */\n private void parseHeaderLine(HeadersSet headers, String header) {\n final int colonOffset = header.indexOf(':');\n if (colonOffset == -1) {\n // This header line is malformed, skip it.\n return;\n }\n String headerName = header.substring(0, colonOffset).trim();\n String headerValue = header.substring(header.indexOf(':') + 1).trim();\n headers.addHeader(headerName, headerValue);\n }\n //\n //\n\n /** The iterator, which is returned by {@link FileUpload#getItemIterator(HttpServletRequest)}. */\n public class FileItemIteratorImpl implements Iterator {\n class FileItemStreamImpl implements FileItemStream {\n /** The file items content type. */\n private final String contentType;\n /** The file items field name. */\n private final String fieldName;\n /** The file items file name. */\n private final String name;\n /** Whether the file item is a form field. */\n private final boolean formField;\n /** The file items input stream. */\n private final InputStream stream;\n /** Whether the file item was already opened. */\n private boolean opened;\n /** The headers, if any. */\n private FileItemHeaders headers;\n\n /**\n * Creates a new instance.\n * @param pName The items file name, or null.\n * @param pFieldName The items field name.\n * @param pFormField Whether the item is a form field.\n * @param pContentLength The items content length, if known, or -1\n * @throws IOException Creating the file item failed.\n */\n FileItemStreamImpl(FileItemHeaders headers, String pName, String pFieldName, boolean pFormField, long pContentLength) throws IOException {\n this.headers = headers;\n this.name = pName;\n this.fieldName = pFieldName;\n this.contentType = headers.getHeader(CONTENT_TYPE);\n this.formField = pFormField;\n final MultipartStream.ItemInputStream itemStream = multi.newInputStream();\n InputStream istream = itemStream;\n if (fileSizeMax != -1) {\n if (pContentLength != -1 && pContentLength > fileSizeMax) {\n String logMessage = format(\"The field %s exceeds its maximum permitted size of %s bytes.\", fieldName, fileSizeMax);\n throw new FileUploadException(FileSizeLimitExceededException, logMessage);\n }\n istream = new LimitedInputStream(istream, fileSizeMax) {\n @Override\n protected void raiseError(long pSizeMax, long pCount) throws IOException {\n itemStream.close(true);\n String logMessage = format(\"The field %s exceeds its maximum permitted size of %s bytes.\", fieldName, pSizeMax);\n throw new FileUploadException(FileSizeLimitExceededException, logMessage);\n }\n };\n }\n this.stream = istream;\n }\n\n /**\n * Returns the items content type, or null.\n *\n * @return Content type, if known, or null.\n */\n public String getContentType() {\n return contentType;\n }\n\n /**\n * Returns the items field name.\n *\n * @return Field name.\n */\n public String getFieldName() {\n return fieldName;\n }\n\n /**\n * Returns the items file name.\n *\n * @return File name, if known, or null.\n * @throws IllegalArgumentException The file name contains a NUL character,\n * which might be an indicator of a security attack. If you intend to\n * use the file name anyways, catch the exception and use\n * InvalidFileNameException#getName().\n */\n public String getName() {\n return Streams.checkFileName(name);\n }\n\n /**\n * Returns, whether this is a form field.\n *\n * @return True, if the item is a form field,\n * otherwise false.\n */\n public boolean isFormField() {\n return formField;\n }\n\n /**\n * Returns an input stream, which may be used to\n * read the items contents.\n *\n * @return Opened input stream.\n * @throws IOException An I/O error occurred.\n */\n public InputStream openStream() throws IOException {\n if (opened) {\n throw new IllegalStateException(\"The stream was already opened.\");\n }\n if (((Closeable) stream).isClosed()) {\n throw new FileUploadException(ItemSkippedException);\n }\n return stream;\n }\n\n /**\n * Closes the file item.\n *\n * @throws IOException An I/O error occurred.\n */\n void close() throws IOException {\n stream.close();\n }\n\n /**\n * Returns the file item headers.\n * @return The items header object\n */\n public FileItemHeaders getHeaders() {\n return headers;\n }\n }\n\n /** The multi part stream to process. */\n private final MultipartStream multi;\n /** The boundary, which separates the various parts. */\n private final byte[] boundary;\n /** The item, which we currently process. */\n private FileItemStreamImpl currentItem;\n /** The current items field name. */\n private String currentFieldName;\n /** Whether we are currently skipping the preamble. */\n private boolean skipPreamble;\n /** Whether the current item may still be read. */\n private boolean itemValid;\n /** Whether we have seen the end of the file. */\n private boolean eof;\n\n /**\n * Creates a new instance.\n * @param ctx The request context.\n * @throws FileUploadException An error occurred while parsing the request.\n * @throws IOException An I/O error occurred.\n */\n FileItemIteratorImpl(ServletRequestContext ctx) throws IOException {\n if (ctx == null) {\n throw new NullPointerException(\"ctx parameter\");\n }\n String contentType = ctx.getContentType();\n if ((null == contentType) || (!contentType.toLowerCase(Locale.ENGLISH).startsWith(MULTIPART))) {\n String logMEssage = format(\"the request doesn't contain a %s or %s stream, content type header is %s\", MULTIPART_FORM_DATA, MULTIPART_MIXED, contentType);\n throw new FileUploadException(InvalidContentTypeException, logMEssage);\n }\n InputStream input = ctx.getInputStream();\n long requestSize = ctx.contentLength();\n // CHECKSTYLE:ON\n if (sizeMax >= 0) {\n if (requestSize != -1 && requestSize > sizeMax) {\n String logMEssage = format(\"the request was rejected because its size (%s) exceeds the configured maximum (%s)\", requestSize, sizeMax);\n throw new FileUploadException(SizeLimitExceededException, logMEssage);\n }\n input = new LimitedInputStream(input, sizeMax) {\n @Override\n protected void raiseError(long pSizeMax, long pCount) throws IOException {\n String logMEssage = format(\"the request was rejected because its size (%s) exceeds the configured maximum (%s)\", pCount, pSizeMax);\n throw new FileUploadException(SizeLimitExceededException, logMEssage);\n }\n };\n }\n String charEncoding = headerEncoding;\n if (charEncoding == null) {\n charEncoding = ctx.getCharacterEncoding();\n }\n boundary = getBoundary(contentType);\n if (boundary == null) {\n throw new FileUploadException(\"the request was rejected because no multipart boundary was found\");\n }\n try {\n multi = new MultipartStream(input, boundary);\n } catch (IllegalArgumentException iae) {\n String logMessage = format(\"The boundary specified in the %s header is too long\", CONTENT_TYPE);\n throw new FileUploadException(InvalidContentTypeException, logMessage);\n }\n multi.setHeaderEncoding(charEncoding);\n skipPreamble = true;\n findNextItem();\n }\n\n /**\n * Called for finding the next item, if any.\n * @return True, if an next item was found, otherwise false.\n * @throws IOException An I/O error occurred.\n */\n private boolean findNextItem() throws IOException {\n if (eof) {\n return false;\n }\n if (currentItem != null) {\n currentItem.close();\n currentItem = null;\n }\n for (; ; ) {\n boolean nextPart;\n if (skipPreamble) {\n nextPart = multi.skipPreamble();\n } else {\n nextPart = multi.readBoundary();\n }\n if (!nextPart) {\n if (currentFieldName == null) {\n eof = true; // Outer multipart terminated -> No more data\n return false;\n }\n multi.setBoundary(boundary);// Inner multipart terminated -> Return to parsing the outer\n currentFieldName = null;\n continue;\n }\n FileItemHeaders headers = getParsedHeaders(multi.readHeaders());\n if (currentFieldName == null) {\n // We're parsing the outer multipart\n String fieldName = getFieldName(headers);\n if (fieldName != null) {\n String subContentType = headers.getHeader(CONTENT_TYPE);\n if (subContentType != null && subContentType.toLowerCase(Locale.ENGLISH).startsWith(MULTIPART_MIXED)) {\n currentFieldName = fieldName;\n // Multiple files associated with this field name\n byte[] subBoundary = getBoundary(subContentType);\n multi.setBoundary(subBoundary);\n skipPreamble = true;\n continue;\n }\n String fileName = getFileName(headers);\n currentItem = new FileItemStreamImpl(headers, fileName, fieldName, fileName == null, getContentLength(headers));\n itemValid = true;\n return true;\n }\n } else {\n String fileName = getFileName(headers);\n if (fileName != null) {\n currentItem = new FileItemStreamImpl(headers, fileName, currentFieldName, false, getContentLength(headers));\n itemValid = true;\n return true;\n }\n }\n multi.discardBodyData();\n }\n }\n\n private long getContentLength(FileItemHeaders pHeaders) {\n try {\n return Long.parseLong(pHeaders.getHeader(CONTENT_LENGTH));\n } catch (Exception e) {\n return -1;\n }\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Returns, whether another instance of {@link FileItemStream} is available.\n *\n * @throws FileUploadException Parsing or processing the file item failed.\n * @throws IOException Reading the file item failed.\n * @return True, if one or more additional file items are available, otherwise false.\n */\n public boolean hasNext() {\n if (eof) {\n return false;\n }\n if (itemValid) {\n return true;\n }\n try {\n return findNextItem();\n } catch (IOException e) {\n throw ExceptionUtils.toRuntime(e);\n }\n }\n\n /**\n * Returns the next available {@link FileItemStream}.\n *\n * @throws java.util.NoSuchElementException No more items are available.\n * Use {@link #hasNext()} to prevent this exception.\n * @throws FileUploadException Parsing or processing the file item failed.\n * @throws IOException Reading the file item failed.\n * @return FileItemStream instance, which provides access to the next file item.\n */\n public FileItemStream next() {\n if (eof || (!itemValid && !hasNext())) {\n throw new NoSuchElementException();\n }\n itemValid = false;\n return currentItem;\n }\n }\n}\n", "file_name": "FileUpload.java", "human_label": "Parse the header part starting from the given end position and return the index of the enter sequence. ", "level": "self_contained", "lineno": "339", "name": "parseEndOfLine", "oracle_context": "{ \"apis\" : \"[indexOf, length, charAt]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.web.upload", "project": "hasor-master" }, { "_id": "636766f61a6d9265ec017701", "all_context": "{ \"class_level\" : \"import net.hasor.core.Singleton;\\nimport net.hasor.dataql.UdfSourceAssembly;\\nimport net.hasor.utils.StringUtils;\\nimport java.util.Arrays;\\nimport java.util.List;\\nimport java.util.regex.Matcher;\\nimport java.util.regex.Pattern;\\nPattern linePattern;\\nPattern humpPattern;\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWith(String str,String suffix);\\nendsWithIgnoreCase(String str,String suffix);\\n_startsWith(String str,String prefix,boolean ignoreCase);\\n_endsWith(String str,String suffix,boolean ignoreCase);\\nlineToHump(String str);\\nhumpToLine(String str);\\nfirstCharToUpperCase(String value);\\nfirstCharToLowerCase(String value);\\ntoUpperCase(String value);\\ntoLowerCase(String value);\\nindexOf(String str,String searchStr);\\nindexOfWithStart(String str,String searchStr,int startPos);\\nindexOfIgnoreCase(String str,String searchStr);\\nindexOfIgnoreCaseWithStart(String str,String searchStr,int startPos);\\nlastIndexOf(String str,String searchStr);\\nlastIndexOfWithStart(String str,String searchChar,int startPos);\\nlastIndexOfIgnoreCase(String str,String searchStr);\\nlastIndexOfIgnoreCaseWithStart(String str,String searchStr,int startPos);\\ncontains(String str,String searchStr);\\ncontainsIgnoreCase(String str,String searchStr);\\ncontainsAny(String str,List searchStrArray);\\ncontainsAnyIgnoreCase(String str,List searchStrArray);\\ntrim(String str);\\nsub(String str,int start,int end);\\nleft(String str,int len);\\nright(String str,int len);\\nalignRight(String str,String padChar,int len);\\nalignLeft(String str,String padChar,int len);\\nalignCenter(String str,String padChar,int len);\\ncompareString(String str1,String str2);\\ncompareStringIgnoreCase(String str1,String str2);\\nsplit(String str,String separatorChars);\\njoin(List array,String separator);\\nisEmpty(String str);\\nequalsIgnoreCase(String str1,String str2);\\nstartsWith(String str,String prefix);\\n\", \"repo_level\" : \"public interface UdfSourceAssembly {default Supplier getSupplier(Class targetType,Finder finder);\\ndefault Predicate getPredicate(Class targetType);\\npublic Object[] allParams();\\ndefault Supplier> getUdfResource(Finder finder);\\npublic Class annotationType();\\npublic String value();\\npublic Object call(Hints readOnly,Object values);\\npublic Object call(Hints readOnly,Object values);\\n }\\npublic interface StringUtils {static boolean isEmpty(String str);\\nstatic boolean isNotEmpty(String str);\\nstatic boolean isBlank(String str);\\nstatic boolean isNotBlank(String str);\\nstatic String trim(String str);\\nstatic String trimToNull(String str);\\nstatic String trimToEmpty(String str);\\nstatic String strip(String str);\\nstatic String stripToNull(String str);\\nstatic String stripToEmpty(String str);\\nstatic String strip(String str,String stripChars);\\nstatic String stripStart(String str,String stripChars);\\nstatic String stripEnd(String str,String stripChars);\\nstatic String[] stripAll(String[] strs);\\nstatic String[] stripAll(String[] strs,String stripChars);\\nstatic boolean equals(String str1,String str2);\\nstatic boolean equalsIgnoreCase(String str1,String str2);\\nstatic int indexOf(String str,char searchChar);\\nstatic int indexOf(String str,char searchChar,int startPos);\\nstatic int indexOf(String str,String searchStr);\\nstatic int ordinalIndexOf(String str,String searchStr,int ordinal);\\nstatic int indexOf(String str,String searchStr,int startPos);\\nstatic int indexOfIgnoreCase(String str,String searchStr);\\nstatic int indexOfIgnoreCase(String str,String searchStr,int startPos);\\nstatic int lastIndexOf(String str,char searchChar);\\nstatic int lastIndexOf(String str,char searchChar,int startPos);\\nstatic int lastIndexOf(String str,String searchStr);\\nstatic int lastOrdinalIndexOf(String str,String searchStr,int ordinal);\\nstatic int lastIndexOf(String str,String searchStr,int startPos);\\nstatic int lastIndexOfIgnoreCase(String str,String searchStr);\\nstatic int lastIndexOfIgnoreCase(String str,String searchStr,int startPos);\\nstatic boolean contains(String str,char searchChar);\\nstatic boolean contains(String str,String searchStr);\\nstatic boolean containsIgnoreCase(String str,String searchStr);\\nstatic int indexOfAny(String str,char[] searchChars);\\nstatic int indexOfAny(String str,String searchChars);\\nstatic boolean containsAny(String str,char[] searchChars);\\nstatic boolean containsAny(String str,String searchChars);\\nstatic int indexOfAnyBut(String str,char[] searchChars);\\nstatic int indexOfAnyBut(String str,String searchChars);\\nstatic boolean containsOnly(String str,char[] valid);\\nstatic boolean containsOnly(String str,String validChars);\\nstatic boolean containsNone(String str,char[] searchChars);\\nstatic boolean containsNone(String str,String invalidChars);\\nstatic int indexOfAny(String str,String[] searchStrs);\\nstatic int lastIndexOfAny(String str,String[] searchStrs);\\nstatic String substring(String str,int start);\\nstatic String substring(String str,int start,int end);\\nstatic String left(String str,int len);\\nstatic String right(String str,int len);\\nstatic String mid(String str,int pos,int len);\\nstatic String substringBefore(String str,String separator);\\nstatic String substringAfter(String str,String separator);\\nstatic String substringBeforeLast(String str,String separator);\\nstatic String substringAfterLast(String str,String separator);\\nstatic String substringBetween(String str,String tag);\\nstatic String substringBetween(String str,String open,String close);\\nstatic String[] substringsBetween(String str,String open,String close);\\nstatic String[] splitKeep(String str,char separatorChar);\\nstatic String[] splitKeep(String str,String separatorStr);\\nstatic String[] split(String str);\\nstatic String[] split(String str,char separatorChar);\\nstatic String[] split(String str,String separatorChars);\\nstatic String[] split(String str,String separatorChars,int max);\\nstatic String[] splitByWholeSeparator(String str,String separator);\\nstatic String[] splitByWholeSeparator(String str,String separator,int max);\\nstatic String[] splitByWholeSeparatorPreserveAllTokens(String str,String separator);\\nstatic String[] splitByWholeSeparatorPreserveAllTokens(String str,String separator,int max);\\nstatic String[] splitPreserveAllTokens(String str);\\nstatic String[] splitPreserveAllTokens(String str,char separatorChar);\\nstatic String[] splitPreserveAllTokens(String str,String separatorChars);\\nstatic String[] splitPreserveAllTokens(String str,String separatorChars,int max);\\nstatic String[] splitByCharacterType(String str);\\nstatic String[] splitByCharacterTypeCamelCase(String str);\\nstatic String join(Object[] array);\\nstatic String join(Object[] array,char separator);\\nstatic String join(Object[] array,char separator,int startIndex,int endIndex);\\nstatic String join(Object[] array,String separator);\\nstatic String join(Object[] array,String separator,int startIndex,int endIndex);\\nstatic String deleteWhitespace(String str);\\nstatic String removeStart(String str,String remove);\\nstatic String removeStartIgnoreCase(String str,String remove);\\nstatic String removeEnd(String str,String remove);\\nstatic String removeEndIgnoreCase(String str,String remove);\\nstatic String remove(String str,String remove);\\nstatic String remove(String str,char remove);\\nstatic String replaceOnce(String text,String searchString,String replacement);\\nstatic String replace(String text,String searchString,String replacement);\\nstatic String replace(String text,String searchString,String replacement,int max);\\nstatic String replaceEach(String text,String[] searchList,String[] replacementList);\\nstatic String replaceEachRepeatedly(String text,String[] searchList,String[] replacementList);\\nstatic String replaceChars(String str,char searchChar,char replaceChar);\\nstatic String replaceChars(String str,String searchChars,String replaceChars);\\nstatic String overlay(String str,String overlay,int start,int end);\\nstatic String chomp(String str);\\nstatic String chomp(String str,String separator);\\nstatic String chop(String str);\\nstatic String repeat(char character,int repeat);\\nstatic String repeat(String str,int repeat);\\nstatic String repeat(String str,String separator,int repeat);\\nstatic String rightPad(String str,int size);\\nstatic String rightPad(String str,int size,char padChar);\\nstatic String rightPad(String str,int size,String padStr);\\nstatic String leftPad(String str,int size);\\nstatic String leftPad(String str,int size,char padChar);\\nstatic String leftPad(String str,int size,String padStr);\\nstatic int length(String str);\\nstatic String center(String str,int size);\\nstatic String center(String str,int size,char padChar);\\nstatic String center(String str,int size,String padStr);\\nstatic String upperCase(String str);\\nstatic String upperCase(String str,Locale locale);\\nstatic String lowerCase(String str);\\nstatic String lowerCase(String str,Locale locale);\\nstatic String capitalize(String str);\\nstatic String uncapitalize(String str);\\nstatic String swapCase(String str);\\nstatic int countMatches(String str,String sub);\\nstatic boolean isAlpha(String str);\\nstatic boolean isAlphaSpace(String str);\\nstatic boolean isAlphanumeric(String str);\\nstatic boolean isAlphanumericSpace(String str);\\nstatic boolean isAsciiPrintable(String str);\\nstatic boolean isNumeric(String str);\\nstatic boolean isNumericSpace(String str);\\nstatic boolean isWhitespace(String str);\\nstatic boolean isAllLowerCase(String str);\\nstatic boolean isAllUpperCase(String str);\\nstatic String defaultString(String str);\\nstatic String defaultString(String str,String defaultStr);\\nstatic String defaultIfBlank(String str,String defaultStr);\\nstatic String defaultIfEmpty(String str,String defaultStr);\\nstatic String reverse(String str);\\nstatic String reverseDelimited(String str,char separatorChar);\\nstatic String abbreviate(String str,int maxWidth);\\nstatic String abbreviate(String str,int offset,int maxWidth);\\nstatic String abbreviateMiddle(String str,String middle,int length);\\nstatic String difference(String str1,String str2);\\nstatic int indexOfDifference(String str1,String str2);\\nstatic int indexOfDifference(String[] strs);\\nstatic String getCommonPrefix(String[] strs);\\nstatic int getLevenshteinDistance(String s,String t);\\nstatic boolean startsWith(String str,String prefix);\\nstatic boolean startsWithIgnoreCase(String str,String prefix);\\nstatic boolean startsWithAny(String string,String[] searchStrings);\\nstatic boolean endsWith(String str,String suffix);\\nstatic boolean endsWithIgnoreCase(String str,String suffix);\\nstatic String normalizeSpace(String str);\\nstatic boolean endsWithAny(String string,String[] searchStrings);\\nstatic String firstCharToUpperCase(String value);\\nstatic String firstCharToLowerCase(String value);\\nstatic boolean equalsBlankIgnoreCase(String str1,String str2);\\nstatic String quote(String input);\\nstatic void quote(Appendable buffer,String input);\\nstatic String toString(Object object);\\n }\\n\" }", "class_name": "StringUdfSource", "code": "public static int lastIndexOf(String str,String searchStr){\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr);\n}\n", "docstring": "/** \n * Finds the last index within a String, handling null. This method uses {@link String#lastIndexOf(String)}. \n */\n", "end_lineno": "166", "file_content": "/*\n * Copyright 2008-2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.dataql.fx.basic;\nimport net.hasor.core.Singleton;\nimport net.hasor.dataql.UdfSourceAssembly;\nimport net.hasor.utils.StringUtils;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * 字符串函数 import 'net.hasor.dataql.fx.basic.StringUdfSource' as string;\n * @version : 2019-12-12\n */\n@Singleton\npublic class StringUdfSource implements UdfSourceAssembly {\n // startsWith/endsWith\n //-----------------------------------------------------------------------\n\n /** Check if a String starts with a specified prefix. */\n public static boolean startsWith(String str, String prefix) {\n return _startsWith(str, prefix, false);\n }\n\n /** Case insensitive check if a String starts with a specified prefix. */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n return _startsWith(str, prefix, true);\n }\n\n /** Case insensitive check if a String ends with a specified suffix. */\n public static boolean endsWith(String str, String suffix) {\n return _endsWith(str, suffix, false);\n }\n\n /** Case insensitive check if a String ends with a specified suffix. */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n return _endsWith(str, suffix, true);\n }\n\n private static boolean _startsWith(String str, String prefix, boolean ignoreCase) {\n if (str == null || prefix == null) {\n return str == null && prefix == null;\n }\n if (prefix.length() > str.length()) {\n return false;\n }\n return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());\n }\n\n private static boolean _endsWith(String str, String suffix, boolean ignoreCase) {\n if (str == null || suffix == null) {\n return str == null && suffix == null;\n }\n if (suffix.length() > str.length()) {\n return false;\n }\n int strOffset = str.length() - suffix.length();\n return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());\n }\n\n // Hump\n //-----------------------------------------------------------------------\n private static final Pattern linePattern = Pattern.compile(\"_(\\\\w)\");\n private static final Pattern humpPattern = Pattern.compile(\"[A-Z]\");\n\n /** 下划线转驼峰 */\n public static String lineToHump(String str) {\n if (str == null) {\n return null;\n }\n str = str.toLowerCase();\n Matcher matcher = linePattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, matcher.group(1).toUpperCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n\n /** 驼峰转下划线 */\n public static String humpToLine(String str) {\n if (str == null) {\n return null;\n }\n Matcher matcher = humpPattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, \"_\" + matcher.group(0).toLowerCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n // UpperCase/LowerCase\n //-----------------------------------------------------------------------\n\n /** 转换首字母大写 */\n public static String firstCharToUpperCase(String value) {\n return StringUtils.firstCharToUpperCase(value);\n }\n\n /** 转换首字母小写 */\n public static String firstCharToLowerCase(String value) {\n return StringUtils.firstCharToLowerCase(value);\n }\n\n /** 转换大写 */\n public static String toUpperCase(String value) {\n return StringUtils.upperCase(value);\n }\n\n /** 转换小写 */\n public static String toLowerCase(String value) {\n return StringUtils.lowerCase(value);\n }\n // IndexOf/lastIndexOf\n //-----------------------------------------------------------------------\n\n /** Finds the first index within a String, handling null. This method uses {@link String#indexOf(String)}. */\n public static int indexOf(String str, String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr);\n }\n\n /** Finds the first index within a String from a start position, handling null. This method uses {@link String#indexOf(String, int)}. */\n public static int indexOfWithStart(String str, String searchStr, int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr, startPos);\n }\n\n /** Case in-sensitive find of the first index within a String. */\n public static int indexOfIgnoreCase(String str, String searchStr) {\n return StringUtils.indexOfIgnoreCase(str, searchStr, 0);\n }\n\n /** Case in-sensitive find of the first index within a String from the specified position. */\n public static int indexOfIgnoreCaseWithStart(String str, String searchStr, int startPos) {\n return StringUtils.indexOfIgnoreCase(str, searchStr, startPos);\n }\n\n /** Finds the last index within a String, handling null. This method uses {@link String#lastIndexOf(String)}. */\n public static int lastIndexOf(String str, String searchStr) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr);\n }\n\n /** Finds the last index within a String from a start position, handling null. This method uses {@link String#lastIndexOf(String, int)}. */\n public static int lastIndexOfWithStart(String str, String searchChar, int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar, startPos);\n }\n\n /** Case in-sensitive find of the last index within a String from the specified position. */\n public static int lastIndexOfIgnoreCase(String str, String searchStr) {\n return StringUtils.lastIndexOfIgnoreCase(str, searchStr, 0);\n }\n\n /** Case in-sensitive find of the last index within a String from the specified position. */\n public static int lastIndexOfIgnoreCaseWithStart(String str, String searchStr, int startPos) {\n return StringUtils.lastIndexOfIgnoreCase(str, searchStr, startPos);\n }\n // Contains\n //-----------------------------------------------------------------------\n\n /** Checks if String contains a search String, handling null. This method uses {@link String#indexOf(String)}. */\n public static boolean contains(String str, String searchStr) {\n return StringUtils.contains(str, searchStr);\n }\n\n /** Checks if String contains a search String irrespective of case, handling null. Case-insensitivity is defined as by {@link String#equalsIgnoreCase(String)}. */\n public static boolean containsIgnoreCase(String str, String searchStr) {\n return StringUtils.containsIgnoreCase(str, searchStr);\n }\n\n /** Checks if the String contains any character in the given set of string. */\n public static boolean containsAny(String str, List searchStrArray) {\n if (StringUtils.isEmpty(str) || searchStrArray == null || searchStrArray.isEmpty()) {\n return false;\n }\n for (String item : searchStrArray) {\n if (contains(str, item)) {\n return true;\n }\n }\n return false;\n }\n\n /** Case in-sensitive Checks if the String contains any character in the given set of string. */\n public static boolean containsAnyIgnoreCase(String str, List searchStrArray) {\n if (StringUtils.isEmpty(str) || searchStrArray == null || searchStrArray.isEmpty()) {\n return false;\n }\n for (String item : searchStrArray) {\n if (containsIgnoreCase(str, item)) {\n return true;\n }\n }\n return false;\n }\n // trim/Sub/left/right\n //-----------------------------------------------------------------------\n\n /** 截断两边空格,如果为空返回为空。 */\n public static String trim(final String str) {\n return str == null ? null : str.trim();\n }\n\n /** Gets a substring from the specified String avoiding exceptions. */\n public static String sub(String str, int start, int end) {\n return StringUtils.substring(str, start, end);\n }\n\n /** Gets the leftmost len characters of a String. */\n public static String left(String str, int len) {\n return StringUtils.left(str, len);\n }\n\n /** Gets the rightmost len characters of a String. */\n public static String right(String str, int len) {\n return StringUtils.right(str, len);\n }\n // align/pading\n //-----------------------------------------------------------------------\n\n /** 字符串在指定长度下进行右对齐,空出来的字符使用padChar补齐。如果传入多个字符将会取第一个字符。 */\n public static String alignRight(String str, String padChar, int len) {\n if (str != null) {\n if (str.length() > len) {\n return str;\n }\n }\n char pad = padChar.length() == 0 ? ' ' : padChar.charAt(0);\n return StringUtils.rightPad(str, len, pad);\n }\n\n /** 字符串在指定长度下进行左对齐,空出来的字符使用padChar补齐。如果传入多个字符将会取第一个字符。 */\n public static String alignLeft(String str, String padChar, int len) {\n if (str != null) {\n if (str.length() > len) {\n return str;\n }\n }\n char pad = padChar.length() == 0 ? ' ' : padChar.charAt(0);\n return StringUtils.leftPad(str, len, pad);\n }\n\n /** 字符串在指定长度下进行剧中对齐,空出来的字符使用padChar补齐。如果传入多个字符将会取第一个字符。 */\n public static String alignCenter(String str, String padChar, int len) {\n if (str != null) {\n if (str.length() > len) {\n return str;\n }\n }\n char pad = padChar.length() == 0 ? ' ' : padChar.charAt(0);\n return StringUtils.center(str, len, pad);\n }\n // compare\n //-----------------------------------------------------------------------\n\n /**\n * Compares two strings lexicographically.\n * The comparison is based on the Unicode value of each character in\n * the strings. The character sequence represented by this\n * {@code String} object is compared lexicographically to the\n * character sequence represented by the argument string. The result is\n * a negative integer if this {@code String} object\n * lexicographically precedes the argument string. The result is a\n * positive integer if this {@code String} object lexicographically\n * follows the argument string. The result is zero if the strings\n * are equal; {@code compareTo} returns {@code 0} exactly when\n * the {@link #equals(Object)} method would return {@code true}.\n *

\n * This is the definition of lexicographic ordering. If two strings are\n * different, then either they have different characters at some index\n * that is a valid index for both strings, or their lengths are different,\n * or both. If they have different characters at one or more index\n * positions, let k be the smallest such index; then the string\n * whose character at position k has the smaller value, as\n * determined by using the < operator, lexicographically precedes the\n * other string. In this case, {@code compareTo} returns the\n * difference of the two character values at position {@code k} in\n * the two string -- that is, the value:\n *

\n     * this.charAt(k)-anotherString.charAt(k)\n     * 
\n * If there is no index position at which they differ, then the shorter\n * string lexicographically precedes the longer string. In this case,\n * {@code compareTo} returns the difference of the lengths of the\n * strings -- that is, the value:\n *
\n     * this.length()-anotherString.length()\n     * 
\n *\n * @param str1 the {@code String} to be compared.\n * @param str2 the {@code String} to be compared.\n * @return the value {@code 0} if the argument string is equal to\n * this string; a value less than {@code 0} if this string\n * is lexicographically less than the string argument; and a\n * value greater than {@code 0} if this string is\n * lexicographically greater than the string argument.\n */\n public static int compareString(String str1, String str2) {\n str1 = str1 == null ? \"\" : str1;\n str2 = str2 == null ? \"\" : str2;\n return str1.compareTo(str2);\n }\n\n /**\n * Compares two strings lexicographically, ignoring case\n * differences. This method returns an integer whose sign is that of\n * calling {@code compareTo} with normalized versions of the strings\n * where case differences have been eliminated by calling\n * {@code Character.toLowerCase(Character.toUpperCase(character))} on\n * each character.\n *

\n * Note that this method does not take locale into account,\n * and will result in an unsatisfactory ordering for certain locales.\n * The java.text package provides collators to allow\n * locale-sensitive ordering.\n *\n * @param str1 the {@code String} to be compared.\n * @param str2 the {@code String} to be compared.\n * @return a negative integer, zero, or a positive integer as the\n * specified String is greater than, equal to, or less\n * than this String, ignoring case considerations.\n * @see java.text.Collator#compare(String, String)\n * @since 1.2\n */\n public static int compareStringIgnoreCase(String str1, String str2) {\n str1 = str1 == null ? \"\" : str1;\n str2 = str2 == null ? \"\" : str2;\n return str1.compareToIgnoreCase(str2);\n }\n // other\n //-----------------------------------------------------------------------\n\n /**\n *

Splits the provided text into an array, separators specified.\n * This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *
\n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"abc def\", null) = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc def\", \" \")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\", \" \") = [\"abc\", \"def\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\") = [\"ab\", \"cd\", \"ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters, null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n */\n public static List split(String str, String separatorChars) {\n return Arrays.asList(StringUtils.split(str, separatorChars));\n }\n\n /** Joins the elements of the provided array into a single String containing the provided list of elements. */\n public static String join(List array, String separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array.toArray(), separator);\n }\n\n /** Checks if a String is empty (\"\") or null.*/\n public static boolean isEmpty(String str) {\n return str == null || str.length() == 0;\n }\n\n /** 忽略大小写比较相等 */\n public static boolean equalsIgnoreCase(String str1, String str2) {\n return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);\n }\n}\n", "file_name": "StringUdfSource.java", "human_label": "Find the last index of the searchStr in str, and return INDEXNOTFOUND if str is empty.", "level": "project_runnable", "lineno": "160", "name": "lastIndexOf", "oracle_context": "{ \"apis\" : \"[isEmpty]\", \"classes\" : \"[StringUtils]\", \"vars\" : \"[INDEX_NOT_FOUND]\" }", "package": "net.hasor.dataql.fx.basic", "project": "hasor-master" }, { "_id": "6367670b1a6d9265ec0179fe", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.io.OutputStream;\\nint threshold;\\nlong written;\\nboolean thresholdExceeded;\\nThresholdingOutputStream(int threshold);\\nwrite(byte b);\\nwrite(byte b,int off,int len);\\nflush();\\nclose();\\ngetThreshold();\\ngetByteCount();\\nisThresholdExceeded();\\ncheckThreshold(int count);\\nresetByteCount();\\ngetStream();\\nthresholdReached();\\nwrite(int b);\\n\", \"repo_level\" : \"\" }", "class_name": "ThresholdingOutputStream", "code": "@Override public void write(byte b[]) throws IOException {\n checkThreshold(b.length);\n getStream().write(b);\n written+=b.length;\n}\n", "docstring": "/** \n * Writes b.length bytes from the specified byte array to this output stream.\n * @param b The array of bytes to be written.\n * @exception IOException if an error occurs.\n */\n", "end_lineno": "91", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.io.output;\nimport java.io.IOException;\nimport java.io.OutputStream;\n\n/**\n * An output stream which triggers an event when a specified number of bytes of\n * data have been written to it. The event can be used, for example, to throw\n * an exception if a maximum has been reached, or to switch the underlying\n * stream type when the threshold is exceeded.\n *

\n * This class overrides all OutputStream methods. However, these\n * overrides ultimately call the corresponding methods in the underlying output\n * stream implementation.\n *

\n * NOTE: This implementation may trigger the event before the threshold\n * is actually reached, since it triggers when a pending write operation would\n * cause the threshold to be exceeded.\n *\n * @version $Id: ThresholdingOutputStream.java 1307462 2012-03-30 15:13:11Z ggregory $\n */\npublic abstract class ThresholdingOutputStream extends OutputStream {\n // ----------------------------------------------------------- Data members\n /**\n * The threshold at which the event will be triggered.\n */\n private final int threshold;\n /**\n * The number of bytes written to the output stream.\n */\n private long written;\n /**\n * Whether or not the configured threshold has been exceeded.\n */\n private boolean thresholdExceeded;\n // ----------------------------------------------------------- Constructors\n\n /**\n * Constructs an instance of this class which will trigger an event at the\n * specified threshold.\n *\n * @param threshold The number of bytes at which to trigger an event.\n */\n public ThresholdingOutputStream(int threshold) {\n this.threshold = threshold;\n }\n // --------------------------------------------------- OutputStream methods\n\n /**\n * Writes the specified byte to this output stream.\n *\n * @param b The byte to be written.\n *\n * @exception IOException if an error occurs.\n */\n @Override\n public void write(int b) throws IOException {\n checkThreshold(1);\n getStream().write(b);\n written++;\n }\n\n /**\n * Writes b.length bytes from the specified byte array to this\n * output stream.\n *\n * @param b The array of bytes to be written.\n *\n * @exception IOException if an error occurs.\n */\n @Override\n public void write(byte b[]) throws IOException {\n checkThreshold(b.length);\n getStream().write(b);\n written += b.length;\n }\n\n /**\n * Writes len bytes from the specified byte array starting at\n * offset off to this output stream.\n *\n * @param b The byte array from which the data will be written.\n * @param off The start offset in the byte array.\n * @param len The number of bytes to write.\n *\n * @exception IOException if an error occurs.\n */\n @Override\n public void write(byte b[], int off, int len) throws IOException {\n checkThreshold(len);\n getStream().write(b, off, len);\n written += len;\n }\n\n /**\n * Flushes this output stream and forces any buffered output bytes to be\n * written out.\n *\n * @exception IOException if an error occurs.\n */\n @Override\n public void flush() throws IOException {\n getStream().flush();\n }\n\n /**\n * Closes this output stream and releases any system resources associated\n * with this stream.\n *\n * @exception IOException if an error occurs.\n */\n @Override\n public void close() throws IOException {\n try {\n flush();\n } catch (IOException ignored) {\n // ignore\n }\n getStream().close();\n }\n // --------------------------------------------------------- Public methods\n\n /**\n * Returns the threshold, in bytes, at which an event will be triggered.\n *\n * @return The threshold point, in bytes.\n */\n public int getThreshold() {\n return threshold;\n }\n\n /**\n * Returns the number of bytes that have been written to this output stream.\n *\n * @return The number of bytes written.\n */\n public long getByteCount() {\n return written;\n }\n\n /**\n * Determines whether or not the configured threshold has been exceeded for\n * this output stream.\n *\n * @return {@code true} if the threshold has been reached;\n * {@code false} otherwise.\n */\n public boolean isThresholdExceeded() {\n return written > threshold;\n }\n // ------------------------------------------------------ Protected methods\n\n /**\n * Checks to see if writing the specified number of bytes would cause the\n * configured threshold to be exceeded. If so, triggers an event to allow\n * a concrete implementation to take action on this.\n *\n * @param count The number of bytes about to be written to the underlying\n * output stream.\n *\n * @exception IOException if an error occurs.\n */\n protected void checkThreshold(int count) throws IOException {\n if (!thresholdExceeded && written + count > threshold) {\n thresholdExceeded = true;\n thresholdReached();\n }\n }\n\n /**\n * Resets the byteCount to zero. You can call this from \n * {@link #thresholdReached()} if you want the event to be triggered again. \n */\n protected void resetByteCount() {\n this.thresholdExceeded = false;\n this.written = 0;\n }\n // ------------------------------------------------------- Abstract methods\n\n /**\n * Returns the underlying output stream, to which the corresponding\n * OutputStream methods in this class will ultimately delegate.\n *\n * @return The underlying output stream.\n *\n * @exception IOException if an error occurs.\n */\n protected abstract OutputStream getStream() throws IOException;\n\n /**\n * Indicates that the configured threshold has been reached, and that a\n * subclass should take whatever action necessary on this event. This may\n * include changing the underlying output stream.\n *\n * @exception IOException if an error occurs.\n */\n protected abstract void thresholdReached() throws IOException;\n}\n", "file_name": "ThresholdingOutputStream.java", "human_label": "Write the given byte array b into the output stream that this class represents.", "level": "class_runnable", "lineno": "78", "name": "write", "oracle_context": "{ \"apis\" : \"[checkThreshold, getStream]\", \"classes\" : \"[]\", \"vars\" : \"[length, written]\" }", "package": "net.hasor.utils.io.output", "project": "hasor-master" }, { "_id": "636767df1a6d9265ec01873c", "all_context": "{ \"class_level\" : \"import lombok.Getter;\\nimport org.apache.skywalking.oap.server.core.Const;\\nlong point;\\nPointOfTime(long point);\\n\", \"repo_level\" : \"public interface Const { }\\n\" }", "class_name": "PointOfTime", "code": "public String id(String entityId){\n if (entityId == null) {\n return String.valueOf(point);\n }\n else {\n return point + Const.ID_CONNECTOR + entityId;\n }\n}\n", "docstring": "/** \n * @return the row id\n */\n", "end_lineno": "45", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.core.query;\n\nimport lombok.Getter;\nimport org.apache.skywalking.oap.server.core.Const;\n\n/**\n * PointOfTime represents any point of time based on different precisions.\n */\n@Getter\npublic class PointOfTime {\n private long point;\n\n public PointOfTime(long point) {\n this.point = point;\n }\n\n /**\n * @return the row id\n */\n public String id(String entityId) {\n // null means scope = all or unexpected entity.\n if (entityId == null) {\n return String.valueOf(point);\n } else {\n return point + Const.ID_CONNECTOR + entityId;\n }\n }\n}", "file_name": "PointOfTime.java", "human_label": "Return the id by concatenating the point and the entity id with id connector.", "level": "project_runnable", "lineno": "35", "name": "id", "oracle_context": "{ \"apis\" : \"[valueOf]\", \"classes\" : \"[Const]\", \"vars\" : \"[ID_CONNECTOR, point]\" }", "package": "org.apache.skywalking.oap.server.core.query", "project": "skywalking-master" }, { "_id": "636766f91a6d9265ec01777f", "all_context": "{ \"class_level\" : \"BooleanUtils();\\nisTrue(Boolean bool);\\nisNotTrue(Boolean bool);\\nisFalse(Boolean bool);\\nisNotFalse(Boolean bool);\\ntoBooleanObject(boolean bool);\\ntoBoolean(Boolean bool);\\ntoBooleanDefaultIfNull(Boolean bool,boolean valueIfNull);\\ntoBoolean(int value);\\ntoBooleanObject(int value);\\ntoBooleanObject(Integer value);\\ntoBoolean(int value,int trueValue,int falseValue);\\ntoBoolean(Integer value,Integer trueValue,Integer falseValue);\\ntoBooleanObject(int value,int trueValue,int falseValue,int nullValue);\\ntoBooleanObject(Integer value,Integer trueValue,Integer falseValue,Integer nullValue);\\ntoInteger(boolean bool);\\ntoInteger(boolean bool,int trueValue,int falseValue);\\ntoInteger(Boolean bool,int trueValue,int falseValue,int nullValue);\\ntoIntegerObject(boolean bool,Integer trueValue,Integer falseValue);\\ntoIntegerObject(Boolean bool,Integer trueValue,Integer falseValue,Integer nullValue);\\ntoBooleanObject(String str);\\ntoBooleanObject(String str,String trueString,String falseString,String nullString);\\ntoBoolean(String str);\\ntoBoolean(String str,String trueString,String falseString);\\ntoStringTrueFalse(Boolean bool);\\ntoStringOnOff(Boolean bool);\\ntoStringYesNo(Boolean bool);\\ntoString(Boolean bool,String trueString,String falseString,String nullString);\\ntoStringTrueFalse(boolean bool);\\ntoStringOnOff(boolean bool);\\ntoStringYesNo(boolean bool);\\ntoString(boolean bool,String trueString,String falseString);\\nxor(boolean[] array);\\nxor(Boolean[] array);\\nisBooleanType(Class targetType);\\nnegate(Boolean bool);\\n\", \"repo_level\" : \"\" }", "class_name": "BooleanUtils", "code": "public static boolean toBoolean(Boolean bool){\n if (bool == null) {\n return false;\n }\n return bool.booleanValue() ? true : false;\n}\n", "docstring": "/** \n *

Converts a Boolean to a boolean handling null by returning false.

 BooleanUtils.toBoolean(Boolean.TRUE)  = true BooleanUtils.toBoolean(Boolean.FALSE) = false BooleanUtils.toBoolean(null)          = false 
\n * @param bool the boolean to convert\n * @return true or false, null returns false\n */\n", "end_lineno": "184", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\n/**\n *

Operations on boolean primitives and Boolean objects.

\n *\n *

This class tries to handle null input gracefully.\n * An exception will not be thrown for a null input.\n * Each method documents its behaviour in more detail.

\n *\n *

#ThreadSafe#

\n * @author Apache Software Foundation\n * @author Matthew Hawthorne\n * @author Gary Gregory\n * @since 2.0\n * @version $Id: BooleanUtils.java 1057037 2011-01-09 21:35:32Z niallp $\n */\npublic class BooleanUtils {\n /**\n *

BooleanUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as BooleanUtils.toBooleanObject(true);.

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public BooleanUtils() {\n super();\n }\n // Boolean utilities\n //--------------------------------------------------------------------------\n\n /**\n *

Negates the specified boolean.

\n *\n *

If null is passed in, null will be returned.

\n *\n *
\n     *   BooleanUtils.negate(Boolean.TRUE)  = Boolean.FALSE;\n     *   BooleanUtils.negate(Boolean.FALSE) = Boolean.TRUE;\n     *   BooleanUtils.negate(null)          = null;\n     * 
\n *\n * @param bool the Boolean to negate, may be null\n * @return the negated Boolean, or null if null input\n */\n public static Boolean negate(Boolean bool) {\n if (bool == null) {\n return null;\n }\n return (bool.booleanValue() ? Boolean.FALSE : Boolean.TRUE);\n }\n // boolean Boolean methods\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if a Boolean value is true,\n * handling null by returning false.

\n *\n *
\n     *   BooleanUtils.isTrue(Boolean.TRUE)  = true\n     *   BooleanUtils.isTrue(Boolean.FALSE) = false\n     *   BooleanUtils.isTrue(null)          = false\n     * 
\n *\n * @param bool the boolean to check, null returns false\n * @return true only if the input is non-null and true\n * @since 2.1\n */\n public static boolean isTrue(Boolean bool) {\n if (bool == null) {\n return false;\n }\n return bool.booleanValue() ? true : false;\n }\n\n /**\n *

Checks if a Boolean value is not true,\n * handling null by returning true.

\n *\n *
\n     *   BooleanUtils.isNotTrue(Boolean.TRUE)  = false\n     *   BooleanUtils.isNotTrue(Boolean.FALSE) = true\n     *   BooleanUtils.isNotTrue(null)          = true\n     * 
\n *\n * @param bool the boolean to check, null returns true\n * @return true if the input is null or false\n * @since 2.3\n */\n public static boolean isNotTrue(Boolean bool) {\n return !isTrue(bool);\n }\n\n /**\n *

Checks if a Boolean value is false,\n * handling null by returning false.

\n *\n *
\n     *   BooleanUtils.isFalse(Boolean.TRUE)  = false\n     *   BooleanUtils.isFalse(Boolean.FALSE) = true\n     *   BooleanUtils.isFalse(null)          = false\n     * 
\n *\n * @param bool the boolean to check, null returns false\n * @return true only if the input is non-null and false\n * @since 2.1\n */\n public static boolean isFalse(Boolean bool) {\n if (bool == null) {\n return false;\n }\n return bool.booleanValue() ? false : true;\n }\n\n /**\n *

Checks if a Boolean value is not false,\n * handling null by returning true.

\n *\n *
\n     *   BooleanUtils.isNotFalse(Boolean.TRUE)  = true\n     *   BooleanUtils.isNotFalse(Boolean.FALSE) = false\n     *   BooleanUtils.isNotFalse(null)          = true\n     * 
\n *\n * @param bool the boolean to check, null returns true\n * @return true if the input is null or true\n * @since 2.3\n */\n public static boolean isNotFalse(Boolean bool) {\n return !isFalse(bool);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Boolean factory that avoids creating new Boolean objecs all the time.

\n *\n *

This method was added to JDK1.4 but is available here for earlier JDKs.

\n *\n *
\n     *   BooleanUtils.toBooleanObject(false) = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(true)  = Boolean.TRUE\n     * 
\n *\n * @param bool the boolean to convert\n * @return Boolean.TRUE or Boolean.FALSE as appropriate\n */\n public static Boolean toBooleanObject(boolean bool) {\n return bool ? Boolean.TRUE : Boolean.FALSE;\n }\n\n /**\n *

Converts a Boolean to a boolean handling null\n * by returning false.

\n *\n *
\n     *   BooleanUtils.toBoolean(Boolean.TRUE)  = true\n     *   BooleanUtils.toBoolean(Boolean.FALSE) = false\n     *   BooleanUtils.toBoolean(null)          = false\n     * 
\n *\n * @param bool the boolean to convert\n * @return true or false, \n * null returns false\n */\n public static boolean toBoolean(Boolean bool) {\n if (bool == null) {\n return false;\n }\n return bool.booleanValue() ? true : false;\n }\n\n /**\n *

Converts a Boolean to a boolean handling null.

\n *\n *
\n     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false) = true\n     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true) = false\n     *   BooleanUtils.toBooleanDefaultIfNull(null, true)          = true\n     * 
\n *\n * @param bool the boolean to convert\n * @param valueIfNull the boolean value to return if null\n * @return true or false\n */\n public static boolean toBooleanDefaultIfNull(Boolean bool, boolean valueIfNull) {\n if (bool == null) {\n return valueIfNull;\n }\n return bool.booleanValue() ? true : false;\n }\n // Integer to Boolean methods\n //-----------------------------------------------------------------------\n\n /**\n *

Converts an int to a boolean using the convention that zero\n * is false.

\n *\n *
\n     *   BooleanUtils.toBoolean(0) = false\n     *   BooleanUtils.toBoolean(1) = true\n     *   BooleanUtils.toBoolean(2) = true\n     * 
\n *\n * @param value the int to convert\n * @return true if non-zero, false\n * if zero\n */\n public static boolean toBoolean(int value) {\n return value == 0 ? false : true;\n }\n\n /**\n *

Converts an int to a Boolean using the convention that zero\n * is false.

\n *\n *
\n     *   BooleanUtils.toBoolean(0) = Boolean.FALSE\n     *   BooleanUtils.toBoolean(1) = Boolean.TRUE\n     *   BooleanUtils.toBoolean(2) = Boolean.TRUE\n     * 
\n *\n * @param value the int to convert\n * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero,\n * null if null\n */\n public static Boolean toBooleanObject(int value) {\n return value == 0 ? Boolean.FALSE : Boolean.TRUE;\n }\n\n /**\n *

Converts an Integer to a Boolean using the convention that zero\n * is false.

\n *\n *

null will be converted to null.

\n *\n *
\n     *   BooleanUtils.toBoolean(new Integer(0))    = Boolean.FALSE\n     *   BooleanUtils.toBoolean(new Integer(1))    = Boolean.TRUE\n     *   BooleanUtils.toBoolean(new Integer(null)) = null\n     * 
\n *\n * @param value the Integer to convert\n * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero,\n * null if null input\n */\n public static Boolean toBooleanObject(Integer value) {\n if (value == null) {\n return null;\n }\n return value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE;\n }\n\n /**\n *

Converts an int to a boolean specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toBoolean(0, 1, 0) = false\n     *   BooleanUtils.toBoolean(1, 1, 0) = true\n     *   BooleanUtils.toBoolean(2, 1, 2) = false\n     *   BooleanUtils.toBoolean(2, 2, 0) = true\n     * 
\n *\n * @param value the Integer to convert\n * @param trueValue the value to match for true\n * @param falseValue the value to match for false\n * @return true or false\n * @throws IllegalArgumentException if no match\n */\n public static boolean toBoolean(int value, int trueValue, int falseValue) {\n if (value == trueValue) {\n return true;\n } else if (value == falseValue) {\n return false;\n }\n // no match\n throw new IllegalArgumentException(\"The Integer did not match either specified value\");\n }\n\n /**\n *

Converts an Integer to a boolean specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toBoolean(new Integer(0), new Integer(1), new Integer(0)) = false\n     *   BooleanUtils.toBoolean(new Integer(1), new Integer(1), new Integer(0)) = true\n     *   BooleanUtils.toBoolean(new Integer(2), new Integer(1), new Integer(2)) = false\n     *   BooleanUtils.toBoolean(new Integer(2), new Integer(2), new Integer(0)) = true\n     *   BooleanUtils.toBoolean(null, null, new Integer(0))                     = true\n     * 
\n *\n * @param value the Integer to convert\n * @param trueValue the value to match for true,\n * may be null\n * @param falseValue the value to match for false,\n * may be null\n * @return true or false\n * @throws IllegalArgumentException if no match\n */\n public static boolean toBoolean(Integer value, Integer trueValue, Integer falseValue) {\n if (value == null) {\n if (trueValue == null) {\n return true;\n } else if (falseValue == null) {\n return false;\n }\n } else if (value.equals(trueValue)) {\n return true;\n } else if (value.equals(falseValue)) {\n return false;\n }\n // no match\n throw new IllegalArgumentException(\"The Integer did not match either specified value\");\n }\n\n /**\n *

Converts an int to a Boolean specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toBooleanObject(0, 0, 2, 3) = Boolean.TRUE\n     *   BooleanUtils.toBooleanObject(2, 1, 2, 3) = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(3, 1, 2, 3) = null\n     * 
\n *\n * @param value the Integer to convert\n * @param trueValue the value to match for true\n * @param falseValue the value to match for false\n * @param nullValue the value to to match for null\n * @return Boolean.TRUE, Boolean.FALSE, or null\n * @throws IllegalArgumentException if no match\n */\n public static Boolean toBooleanObject(int value, int trueValue, int falseValue, int nullValue) {\n if (value == trueValue) {\n return Boolean.TRUE;\n } else if (value == falseValue) {\n return Boolean.FALSE;\n } else if (value == nullValue) {\n return null;\n }\n // no match\n throw new IllegalArgumentException(\"The Integer did not match any specified value\");\n }\n\n /**\n *

Converts an Integer to a Boolean specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toBooleanObject(new Integer(0), new Integer(0), new Integer(2), new Integer(3)) = Boolean.TRUE\n     *   BooleanUtils.toBooleanObject(new Integer(2), new Integer(1), new Integer(2), new Integer(3)) = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(new Integer(3), new Integer(1), new Integer(2), new Integer(3)) = null\n     * 
\n *\n * @param value the Integer to convert\n * @param trueValue the value to match for true,\n * may be null\n * @param falseValue the value to match for false,\n * may be null\n * @param nullValue the value to to match for null,\n * may be null\n * @return Boolean.TRUE, Boolean.FALSE, or null\n * @throws IllegalArgumentException if no match\n */\n public static Boolean toBooleanObject(Integer value, Integer trueValue, Integer falseValue, Integer nullValue) {\n if (value == null) {\n if (trueValue == null) {\n return Boolean.TRUE;\n } else if (falseValue == null) {\n return Boolean.FALSE;\n } else if (nullValue == null) {\n return null;\n }\n } else if (value.equals(trueValue)) {\n return Boolean.TRUE;\n } else if (value.equals(falseValue)) {\n return Boolean.FALSE;\n } else if (value.equals(nullValue)) {\n return null;\n }\n // no match\n throw new IllegalArgumentException(\"The Integer did not match any specified value\");\n }\n // Boolean to Integer methods\n //-----------------------------------------------------------------------\n\n /**\n *

Converts a boolean to an int using the convention that\n * zero is false.

\n *\n *
\n     *   BooleanUtils.toInteger(true)  = 1\n     *   BooleanUtils.toInteger(false) = 0\n     * 
\n *\n * @param bool the boolean to convert\n * @return one if true, zero if false\n */\n public static int toInteger(boolean bool) {\n return bool ? 1 : 0;\n }\n\n /**\n *

Converts a boolean to an int specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toInteger(true, 1, 0)  = 1\n     *   BooleanUtils.toInteger(false, 1, 0) = 0\n     * 
\n *\n * @param bool the to convert\n * @param trueValue the value to return if true\n * @param falseValue the value to return if false\n * @return the appropriate value\n */\n public static int toInteger(boolean bool, int trueValue, int falseValue) {\n return bool ? trueValue : falseValue;\n }\n\n /**\n *

Converts a Boolean to an int specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toInteger(Boolean.TRUE, 1, 0, 2)  = 1\n     *   BooleanUtils.toInteger(Boolean.FALSE, 1, 0, 2) = 0\n     *   BooleanUtils.toInteger(null, 1, 0, 2)          = 2\n     * 
\n *\n * @param bool the Boolean to convert\n * @param trueValue the value to return if true\n * @param falseValue the value to return if false\n * @param nullValue the value to return if null\n * @return the appropriate value\n */\n public static int toInteger(Boolean bool, int trueValue, int falseValue, int nullValue) {\n if (bool == null) {\n return nullValue;\n }\n return bool.booleanValue() ? trueValue : falseValue;\n }\n\n /**\n *

Converts a boolean to an Integer specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toIntegerObject(true, new Integer(1), new Integer(0))  = new Integer(1)\n     *   BooleanUtils.toIntegerObject(false, new Integer(1), new Integer(0)) = new Integer(0)\n     * 
\n *\n * @param bool the to convert\n * @param trueValue the value to return if true,\n * may be null\n * @param falseValue the value to return if false,\n * may be null\n * @return the appropriate value\n */\n public static Integer toIntegerObject(boolean bool, Integer trueValue, Integer falseValue) {\n return bool ? trueValue : falseValue;\n }\n\n /**\n *

Converts a Boolean to an Integer specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toIntegerObject(Boolean.TRUE, new Integer(1), new Integer(0), new Integer(2))  = new Integer(1)\n     *   BooleanUtils.toIntegerObject(Boolean.FALSE, new Integer(1), new Integer(0), new Integer(2)) = new Integer(0)\n     *   BooleanUtils.toIntegerObject(null, new Integer(1), new Integer(0), new Integer(2))          = new Integer(2)\n     * 
\n *\n * @param bool the Boolean to convert\n * @param trueValue the value to return if true,\n * may be null\n * @param falseValue the value to return if false,\n * may be null\n * @param nullValue the value to return if null,\n * may be null\n * @return the appropriate value\n */\n public static Integer toIntegerObject(Boolean bool, Integer trueValue, Integer falseValue, Integer nullValue) {\n if (bool == null) {\n return nullValue;\n }\n return bool.booleanValue() ? trueValue : falseValue;\n }\n // String to Boolean methods\n //-----------------------------------------------------------------------\n\n /**\n *

Converts a String to a Boolean.

\n *\n *

'true', 'on' or 'yes'\n * (case insensitive) will return true.\n * 'false', 'off' or 'no'\n * (case insensitive) will return false.\n * Otherwise, null is returned.

\n *\n *
\n     *   BooleanUtils.toBooleanObject(null)    = null\n     *   BooleanUtils.toBooleanObject(\"true\")  = Boolean.TRUE\n     *   BooleanUtils.toBooleanObject(\"false\") = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(\"on\")    = Boolean.TRUE\n     *   BooleanUtils.toBooleanObject(\"ON\")    = Boolean.TRUE\n     *   BooleanUtils.toBooleanObject(\"off\")   = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(\"oFf\")   = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(\"blue\")  = null\n     * 
\n *\n * @param str the String to check\n * @return the Boolean value of the string,\n * null if no match or null input\n */\n public static Boolean toBooleanObject(String str) {\n // Previously used equalsIgnoreCase, which was fast for interned 'true'.\n // Non interned 'true' matched 15 times slower.\n // \n // Optimisation provides same performance as before for interned 'true'.\n // Similar performance for null, 'false', and other strings not length 2/3/4.\n // 'true'/'TRUE' match 4 times slower, 'tRUE'/'True' 7 times slower.\n if (str == null) {\n return null;\n }\n if (\"true\".equals(str)) {\n return Boolean.TRUE;\n }\n switch (str.length()) {\n case 1: {\n char ch0 = str.charAt(0);\n if ((ch0 == 'y' || ch0 == 'Y') || (ch0 == 't' || ch0 == 'T')) {\n return Boolean.TRUE;\n }\n if ((ch0 == 'n' || ch0 == 'N') || (ch0 == 'f' || ch0 == 'F')) {\n return Boolean.FALSE;\n }\n break;\n }\n case 2: {\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n if ((ch0 == 'o' || ch0 == 'O') && (ch1 == 'n' || ch1 == 'N')) {\n return Boolean.TRUE;\n }\n if ((ch0 == 'n' || ch0 == 'N') && (ch1 == 'o' || ch1 == 'O')) {\n return Boolean.FALSE;\n }\n break;\n }\n case 3: {\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n char ch2 = str.charAt(2);\n if ((ch0 == 'y' || ch0 == 'Y') && (ch1 == 'e' || ch1 == 'E') && (ch2 == 's' || ch2 == 'S')) {\n return Boolean.TRUE;\n }\n if ((ch0 == 'o' || ch0 == 'O') && (ch1 == 'f' || ch1 == 'F') && (ch2 == 'f' || ch2 == 'F')) {\n return Boolean.FALSE;\n }\n break;\n }\n case 4: {\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n char ch2 = str.charAt(2);\n char ch3 = str.charAt(3);\n if ((ch0 == 't' || ch0 == 'T') && (ch1 == 'r' || ch1 == 'R') && (ch2 == 'u' || ch2 == 'U') && (ch3 == 'e' || ch3 == 'E')) {\n return Boolean.TRUE;\n }\n break;\n }\n case 5: {\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n char ch2 = str.charAt(2);\n char ch3 = str.charAt(3);\n char ch4 = str.charAt(4);\n if ((ch0 == 'f' || ch0 == 'F') && (ch1 == 'a' || ch1 == 'A') && (ch2 == 'l' || ch2 == 'L') && (ch3 == 's' || ch3 == 'S') && (ch4 == 'e' || ch4 == 'E')) {\n return Boolean.FALSE;\n }\n break;\n }\n }\n return null;\n }\n\n /**\n *

Converts a String to a Boolean throwing an exception if no match.

\n *\n *
\n     *   BooleanUtils.toBooleanObject(\"true\", \"true\", \"false\", \"null\")  = Boolean.TRUE\n     *   BooleanUtils.toBooleanObject(\"false\", \"true\", \"false\", \"null\") = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(\"null\", \"true\", \"false\", \"null\")  = null\n     * 
\n *\n * @param str the String to check\n * @param trueString the String to match for true\n * (case sensitive), may be null\n * @param falseString the String to match for false\n * (case sensitive), may be null\n * @param nullString the String to match for null\n * (case sensitive), may be null\n * @return the Boolean value of the string,\n * null if either the String matches nullString\n * or if null input and nullString is\n * null\n * @throws IllegalArgumentException if the String doesn't match\n */\n public static Boolean toBooleanObject(String str, String trueString, String falseString, String nullString) {\n if (str == null) {\n if (trueString == null) {\n return Boolean.TRUE;\n } else if (falseString == null) {\n return Boolean.FALSE;\n } else if (nullString == null) {\n return null;\n }\n } else if (str.equals(trueString)) {\n return Boolean.TRUE;\n } else if (str.equals(falseString)) {\n return Boolean.FALSE;\n } else if (str.equals(nullString)) {\n return null;\n }\n // no match\n throw new IllegalArgumentException(\"The String did not match any specified value\");\n }\n // String to boolean methods\n //-----------------------------------------------------------------------\n\n /**\n *

Converts a String to a boolean (optimised for performance).

\n *\n *

'true', 'on' or 'yes'\n * (case insensitive) will return true. Otherwise,\n * false is returned.

\n *\n *

This method performs 4 times faster (JDK1.4) than\n * Boolean.valueOf(String). However, this method accepts\n * 'on' and 'yes' as true values.\n *\n *

\n     *   BooleanUtils.toBoolean(null)    = false\n     *   BooleanUtils.toBoolean(\"true\")  = true\n     *   BooleanUtils.toBoolean(\"TRUE\")  = true\n     *   BooleanUtils.toBoolean(\"tRUe\")  = true\n     *   BooleanUtils.toBoolean(\"on\")    = true\n     *   BooleanUtils.toBoolean(\"yes\")   = true\n     *   BooleanUtils.toBoolean(\"false\") = false\n     *   BooleanUtils.toBoolean(\"x gti\") = false\n     * 
\n *\n * @param str the String to check\n * @return the boolean value of the string, false if no match or the String is null\n */\n public static boolean toBoolean(String str) {\n return toBoolean(toBooleanObject(str));\n }\n\n /**\n *

Converts a String to a Boolean throwing an exception if no match found.

\n *\n *

null is returned if there is no match.

\n *\n *
\n     *   BooleanUtils.toBoolean(\"true\", \"true\", \"false\")  = true\n     *   BooleanUtils.toBoolean(\"false\", \"true\", \"false\") = false\n     * 
\n *\n * @param str the String to check\n * @param trueString the String to match for true\n * (case sensitive), may be null\n * @param falseString the String to match for false\n * (case sensitive), may be null\n * @return the boolean value of the string\n * @throws IllegalArgumentException if the String doesn't match\n */\n public static boolean toBoolean(String str, String trueString, String falseString) {\n if (str == null) {\n if (trueString == null) {\n return true;\n } else if (falseString == null) {\n return false;\n }\n } else if (str.equals(trueString)) {\n return true;\n } else if (str.equals(falseString)) {\n return false;\n }\n // no match\n throw new IllegalArgumentException(\"The String did not match either specified value\");\n }\n // Boolean to String methods\n //-----------------------------------------------------------------------\n\n /**\n *

Converts a Boolean to a String returning 'true',\n * 'false', or null.

\n *\n *
\n     *   BooleanUtils.toStringTrueFalse(Boolean.TRUE)  = \"true\"\n     *   BooleanUtils.toStringTrueFalse(Boolean.FALSE) = \"false\"\n     *   BooleanUtils.toStringTrueFalse(null)          = null;\n     * 
\n *\n * @param bool the Boolean to check\n * @return 'true', 'false',\n * or null\n */\n public static String toStringTrueFalse(Boolean bool) {\n return toString(bool, \"true\", \"false\", null);\n }\n\n /**\n *

Converts a Boolean to a String returning 'on',\n * 'off', or null.

\n *\n *
\n     *   BooleanUtils.toStringOnOff(Boolean.TRUE)  = \"on\"\n     *   BooleanUtils.toStringOnOff(Boolean.FALSE) = \"off\"\n     *   BooleanUtils.toStringOnOff(null)          = null;\n     * 
\n *\n * @param bool the Boolean to check\n * @return 'on', 'off',\n * or null\n */\n public static String toStringOnOff(Boolean bool) {\n return toString(bool, \"on\", \"off\", null);\n }\n\n /**\n *

Converts a Boolean to a String returning 'yes',\n * 'no', or null.

\n *\n *
\n     *   BooleanUtils.toStringYesNo(Boolean.TRUE)  = \"yes\"\n     *   BooleanUtils.toStringYesNo(Boolean.FALSE) = \"no\"\n     *   BooleanUtils.toStringYesNo(null)          = null;\n     * 
\n *\n * @param bool the Boolean to check\n * @return 'yes', 'no',\n * or null\n */\n public static String toStringYesNo(Boolean bool) {\n return toString(bool, \"yes\", \"no\", null);\n }\n\n /**\n *

Converts a Boolean to a String returning one of the input Strings.

\n *\n *
\n     *   BooleanUtils.toString(Boolean.TRUE, \"true\", \"false\", null)   = \"true\"\n     *   BooleanUtils.toString(Boolean.FALSE, \"true\", \"false\", null)  = \"false\"\n     *   BooleanUtils.toString(null, \"true\", \"false\", null)           = null;\n     * 
\n *\n * @param bool the Boolean to check\n * @param trueString the String to return if true,\n * may be null\n * @param falseString the String to return if false,\n * may be null\n * @param nullString the String to return if null,\n * may be null\n * @return one of the three input Strings\n */\n public static String toString(Boolean bool, String trueString, String falseString, String nullString) {\n if (bool == null) {\n return nullString;\n }\n return bool.booleanValue() ? trueString : falseString;\n }\n // boolean to String methods\n //-----------------------------------------------------------------------\n\n /**\n *

Converts a boolean to a String returning 'true'\n * or 'false'.

\n *\n *
\n     *   BooleanUtils.toStringTrueFalse(true)   = \"true\"\n     *   BooleanUtils.toStringTrueFalse(false)  = \"false\"\n     * 
\n *\n * @param bool the Boolean to check\n * @return 'true', 'false',\n * or null\n */\n public static String toStringTrueFalse(boolean bool) {\n return toString(bool, \"true\", \"false\");\n }\n\n /**\n *

Converts a boolean to a String returning 'on'\n * or 'off'.

\n *\n *
\n     *   BooleanUtils.toStringOnOff(true)   = \"on\"\n     *   BooleanUtils.toStringOnOff(false)  = \"off\"\n     * 
\n *\n * @param bool the Boolean to check\n * @return 'on', 'off',\n * or null\n */\n public static String toStringOnOff(boolean bool) {\n return toString(bool, \"on\", \"off\");\n }\n\n /**\n *

Converts a boolean to a String returning 'yes'\n * or 'no'.

\n *\n *
\n     *   BooleanUtils.toStringYesNo(true)   = \"yes\"\n     *   BooleanUtils.toStringYesNo(false)  = \"no\"\n     * 
\n *\n * @param bool the Boolean to check\n * @return 'yes', 'no',\n * or null\n */\n public static String toStringYesNo(boolean bool) {\n return toString(bool, \"yes\", \"no\");\n }\n\n /**\n *

Converts a boolean to a String returning one of the input Strings.

\n *\n *
\n     *   BooleanUtils.toString(true, \"true\", \"false\")   = \"true\"\n     *   BooleanUtils.toString(false, \"true\", \"false\")  = \"false\"\n     * 
\n *\n * @param bool the Boolean to check\n * @param trueString the String to return if true,\n * may be null\n * @param falseString the String to return if false,\n * may be null\n * @return one of the two input Strings\n */\n public static String toString(boolean bool, String trueString, String falseString) {\n return bool ? trueString : falseString;\n }\n // xor methods\n // ----------------------------------------------------------------------\n\n /**\n *

Performs an xor on a set of booleans.

\n *\n *
\n     *   BooleanUtils.xor(new boolean[] { true, true })   = false\n     *   BooleanUtils.xor(new boolean[] { false, false }) = false\n     *   BooleanUtils.xor(new boolean[] { true, false })  = true\n     * 
\n *\n * @param array an array of booleans\n * @return true if the xor is successful.\n * @throws IllegalArgumentException if array is null\n * @throws IllegalArgumentException if array is empty.\n */\n public static boolean xor(boolean[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array is empty\");\n }\n // Loops through array, comparing each item\n int trueCount = 0;\n for (int i = 0; i < array.length; i++) {\n // If item is true, and trueCount is < 1, increments count\n // Else, xor fails\n if (array[i]) {\n if (trueCount < 1) {\n trueCount++;\n } else {\n return false;\n }\n }\n }\n // Returns true if there was exactly 1 true item\n return trueCount == 1;\n }\n\n /**\n *

Performs an xor on an array of Booleans.

\n *\n *
\n     *   BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE })   = Boolean.FALSE\n     *   BooleanUtils.xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) = Boolean.FALSE\n     *   BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE })  = Boolean.TRUE\n     * 
\n *\n * @param array an array of Booleans\n * @return true if the xor is successful.\n * @throws IllegalArgumentException if array is null\n * @throws IllegalArgumentException if array is empty.\n * @throws IllegalArgumentException if array contains a null\n */\n public static Boolean xor(Boolean[] array) {\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array is empty\");\n }\n boolean[] primitive = null;\n try {\n primitive = ArrayUtils.toPrimitive(array);\n } catch (NullPointerException ex) {\n throw new IllegalArgumentException(\"The array must not contain any null elements\");\n }\n return xor(primitive) ? Boolean.TRUE : Boolean.FALSE;\n }\n\n //\n public static boolean isBooleanType(Class targetType) {\n return targetType.equals(Boolean.class) || targetType.equals(Boolean.TYPE);\n }\n}\n", "file_name": "BooleanUtils.java", "human_label": "Convert a Boolean to a boolean handling null by returning false.", "level": "self_contained", "lineno": "165", "name": "toBoolean", "oracle_context": "{ \"apis\" : \"[booleanValue]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "6367675f1a6d9265ec0180d3", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.util.*;\\nimport java.util.*;\\nint NULL_NODE;\\nMap forwardMapping;\\nMap backwardMapping;\\nGraph graph1;\\nGraph graph2;\\nIsomorphicGraphMapping(GraphOrdering g1,GraphOrdering g2,int[] core1,int[] core2);\\nIsomorphicGraphMapping(Map forwardMapping,Map backwardMapping,Graph graph1,Graph graph2);\\ngetVertexCorrespondence(V v,boolean forward);\\ngetEdgeCorrespondence(E e,boolean forward);\\ngetForwardMapping();\\ngetBackwardMapping();\\ngetMappingDomain();\\ngetMappingRange();\\nhasEdgeCorrespondence(E e);\\nequals(Object o);\\nhashCode();\\ntoString();\\nisValidIsomorphism();\\nisEqualMapping(GraphMapping rel);\\ncompose(IsomorphicGraphMapping otherMapping);\\nidentity(Graph graph);\\nhasVertexCorrespondence(V v);\\n\", \"repo_level\" : \"\" }", "class_name": "IsomorphicGraphMapping", "code": "public static IsomorphicGraphMapping identity(Graph graph){\n Map fMap=CollectionUtil.newHashMapWithExpectedSize(graph.vertexSet().size());\n Map bMap=CollectionUtil.newHashMapWithExpectedSize(graph.vertexSet().size());\n for ( V v : graph.vertexSet()) {\n fMap.put(v,v);\n bMap.put(v,v);\n }\n return new IsomorphicGraphMapping<>(fMap,bMap,graph,graph);\n}\n", "docstring": "/** \n * Computes an identity automorphism (i.e. a self-mapping of a graph in which each vertex also maps to itself).\n * @param graph the input graph\n * @param < V > the graph vertex type\n * @param < E > the graph edge type\n * @return a mapping from graph to graph\n */\n", "end_lineno": "358", "file_content": "/*\n * (C) Copyright 2015-2021, by Fabian Späh and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.isomorphism;\n\nimport org.jgrapht.*;\nimport org.jgrapht.util.*;\n\nimport java.util.*;\n\n/**\n * This class represents a GraphMapping between two (subgraph)isomorphic graphs. In the subgraph\n * isomorphic case, the second one is assumed to be a subgraph of the first one.\n *\n * @author Fabian Späh\n * @author Alexandru Valeanu\n *\n * @param the type of the vertices\n * @param the type of the edges\n */\npublic class IsomorphicGraphMapping\n implements\n GraphMapping\n{\n\n public static final int NULL_NODE = -1;\n\n private final Map forwardMapping;\n private final Map backwardMapping;\n\n private final Graph graph1;\n private final Graph graph2;\n\n /**\n * Construct a new isomorphic graph mapping\n * \n * @param g1 the first graph\n * @param g2 the second graph which is a possible subgraph of g1\n * @param core1 the mapping as array (forwards)\n * @param core2 the mapping as array (backwards)\n */\n public IsomorphicGraphMapping(\n GraphOrdering g1, GraphOrdering g2, int[] core1, int[] core2)\n {\n this.graph1 = g1.getGraph();\n this.graph2 = g2.getGraph();\n\n this.forwardMapping =\n CollectionUtil.newHashMapWithExpectedSize(this.graph1.vertexSet().size());\n this.backwardMapping =\n CollectionUtil.newHashMapWithExpectedSize(this.graph1.vertexSet().size());\n\n for (V v : graph1.vertexSet()) {\n int vNumber = g1.getVertexNumber(v);\n int uNumber = core1[vNumber];\n\n if (uNumber != NULL_NODE) {\n forwardMapping.put(v, g2.getVertex(uNumber));\n }\n }\n\n for (V v : graph2.vertexSet()) {\n int vNumber = g2.getVertexNumber(v);\n int uNumber = core2[vNumber];\n\n if (uNumber != NULL_NODE) {\n backwardMapping.put(v, g1.getVertex(uNumber));\n }\n }\n }\n\n /**\n * Construct a new isomorphic graph mapping.\n *\n * @param forwardMapping the mapping from graph1 to graph2\n * @param backwardMapping the mapping from graph2 to graph1 (inverse of forwardMapping)\n * @param graph1 the first graph\n * @param graph2 the second graph\n * \n */\n public IsomorphicGraphMapping(\n Map forwardMapping, Map backwardMapping, Graph graph1, Graph graph2)\n {\n this.forwardMapping = Objects.requireNonNull(forwardMapping);\n this.backwardMapping = Objects.requireNonNull(backwardMapping);\n\n this.graph1 = Objects.requireNonNull(graph1);\n this.graph2 = Objects.requireNonNull(graph2);\n }\n\n @Override\n public V getVertexCorrespondence(V v, boolean forward)\n {\n if (forward)\n return forwardMapping.get(v);\n else\n return backwardMapping.get(v);\n }\n\n @Override\n public E getEdgeCorrespondence(E e, boolean forward)\n {\n Graph fromGraph;\n Graph toGraph;\n\n if (forward) {\n fromGraph = graph1;\n toGraph = graph2;\n\n } else {\n fromGraph = graph2;\n toGraph = graph1;\n }\n\n V u = fromGraph.getEdgeSource(e);\n V v = fromGraph.getEdgeTarget(e);\n\n V uu = getVertexCorrespondence(u, forward);\n if (uu == null) {\n return null;\n }\n\n V vv = getVertexCorrespondence(v, forward);\n if (vv == null) {\n return null;\n }\n\n return toGraph.getEdge(uu, vv);\n }\n\n /**\n * Get an unmodifiable version of the forward mapping function.\n *\n * @return the unmodifiable forward mapping function\n */\n public Map getForwardMapping()\n {\n return Collections.unmodifiableMap(forwardMapping);\n }\n\n /**\n * Get an unmodifiable version of the backward mapping function.\n *\n * @return the unmodifiable backward mapping function\n */\n public Map getBackwardMapping()\n {\n return Collections.unmodifiableMap(backwardMapping);\n }\n\n /**\n * Get the active domain of the isomorphism.\n *\n * @return the set of vertices $v$ for which the mapping is defined\n */\n public Set getMappingDomain()\n {\n return Collections.unmodifiableSet(forwardMapping.keySet());\n }\n\n /**\n * Get the range of the isomorphism.\n *\n * @return the set of vertices $v$ for which a preimage exists\n */\n public Set getMappingRange()\n {\n return Collections.unmodifiableSet(backwardMapping.keySet());\n }\n\n /**\n * Checks if a vertex $v$ from the first graph has a corresponding vertex in the second graph\n *\n * @param v the vertex\n * @return is there a corresponding vertex to $v$ in the subgraph\n */\n public boolean hasVertexCorrespondence(V v)\n {\n return getVertexCorrespondence(v, true) != null;\n }\n\n /**\n * Checks if a edge e from the first graph has a corresponding edge in the second graph\n *\n * @param e the edge\n * @return is there a corresponding edge to $e$ in the subgraph\n */\n public boolean hasEdgeCorrespondence(E e)\n {\n return getEdgeCorrespondence(e, true) != null;\n }\n\n @Override\n public boolean equals(Object o)\n {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n IsomorphicGraphMapping that = (IsomorphicGraphMapping) o;\n return Objects.equals(forwardMapping, that.forwardMapping)\n && Objects.equals(backwardMapping, that.backwardMapping) && graph1 == that.graph1\n && graph2 == that.graph2;\n }\n\n @Override\n public int hashCode()\n {\n return Objects\n .hash(\n forwardMapping, backwardMapping, System.identityHashCode(graph1),\n System.identityHashCode(graph2));\n }\n\n @Override\n public String toString()\n {\n StringBuilder str = new StringBuilder(\"[\");\n Set vertexSet = graph1.vertexSet();\n Map vertexMap = new TreeMap<>();\n\n for (V v : vertexSet) {\n vertexMap.put(v.toString(), v);\n }\n\n int i = 0;\n for (Map.Entry entry : vertexMap.entrySet()) {\n V u = getVertexCorrespondence(entry.getValue(), true);\n str\n .append((i++ == 0) ? \"\" : \" \").append(entry.getKey()).append(\"=\")\n .append((u == null) ? \"~~\" : u);\n }\n\n return str + \"]\";\n }\n\n /**\n * Determines whether this mapping is indeed a valid isomorphic mapping between the first graph\n * and the second graph. Note that this method will return false for a homomorphism returned by\n * a subgraph isomorphism inspector unless the resulting mapping happens to be bijective as well\n * (mapping all of the vertices and edges from the first graph to the second graph and vice\n * versa).\n *\n * @return true iff this mapping is a valid isomorphism between the two graphs\n */\n public boolean isValidIsomorphism()\n {\n for (V v : graph1.vertexSet()) {\n if (!forwardMapping.containsKey(v) || !graph2.containsVertex(forwardMapping.get(v)))\n return false;\n }\n\n for (V v : graph2.vertexSet()) {\n if (!backwardMapping.containsKey(v) || !graph1.containsVertex(backwardMapping.get(v)))\n return false;\n }\n\n for (E edge : graph1.edgeSet()) {\n E e = getEdgeCorrespondence(edge, true);\n V u = graph1.getEdgeSource(e);\n V v = graph1.getEdgeTarget(e);\n\n if (!graph2.containsEdge(u, v))\n return false;\n }\n\n for (E edge : graph2.edgeSet()) {\n E e = getEdgeCorrespondence(edge, false);\n V u = graph2.getEdgeSource(e);\n V v = graph2.getEdgeTarget(e);\n\n if (!graph1.containsEdge(u, v))\n return false;\n }\n\n return true;\n }\n\n /**\n * Checks for equality. Assuming both are mappings on the same graphs.\n *\n * @param rel the corresponding mapping\n * @return do both relations map to the same vertices\n */\n public boolean isEqualMapping(GraphMapping rel)\n {\n for (V v : graph2.vertexSet()) {\n if (!getVertexCorrespondence(v, false).equals(rel.getVertexCorrespondence(v, false))) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Computes the composition of two isomorphisms. Let $f : V_{G_1} \\rightarrow V_{G_2}$ be an\n * isomorphism from $V_{G_1}$ to $V_{G_2}$ and $g : V_{G_2} \\rightarrow V_{G_3}$ one from\n * $V_{G_2}$ to $V_{G_3}$.\n *\n * This method computes an isomorphism $h : V_{G_1} \\rightarrow V_{G_3}$ from $V_{G_1}$ to\n * $V_{G_3}$.\n *\n * Note: The composition $g ∘ f$ can be built only if $f$'s codomain equals $g$'s domain; this\n * implementation only requires that the former is a subset of the latter.\n *\n * @param otherMapping the other isomorphism (i.e. function $g$)\n * @return the composition of the two isomorphism\n */\n public IsomorphicGraphMapping compose(IsomorphicGraphMapping otherMapping)\n {\n Map fMap = CollectionUtil.newHashMapWithExpectedSize(forwardMapping.size());\n Map bMap = CollectionUtil.newHashMapWithExpectedSize(forwardMapping.size());\n\n for (V v : graph1.vertexSet()) {\n V u = otherMapping.getVertexCorrespondence(forwardMapping.get(v), true);\n fMap.put(v, u);\n bMap.put(u, v);\n }\n\n return new IsomorphicGraphMapping<>(fMap, bMap, graph1, otherMapping.graph2);\n }\n\n /**\n * Computes an identity automorphism (i.e. a self-mapping of a graph in which each vertex also\n * maps to itself).\n *\n * @param graph the input graph\n * @param the graph vertex type\n * @param the graph edge type\n * @return a mapping from graph to graph\n */\n public static IsomorphicGraphMapping identity(Graph graph)\n {\n Map fMap = CollectionUtil.newHashMapWithExpectedSize(graph.vertexSet().size());\n Map bMap = CollectionUtil.newHashMapWithExpectedSize(graph.vertexSet().size());\n\n for (V v : graph.vertexSet()) {\n fMap.put(v, v);\n bMap.put(v, v);\n }\n\n return new IsomorphicGraphMapping<>(fMap, bMap, graph, graph);\n }\n}\n", "file_name": "IsomorphicGraphMapping.java", "human_label": "Compute and return an identity automorphism for the given graph.", "level": "project_runnable", "lineno": "338", "name": "identity", "oracle_context": "{ \"apis\" : \"[newHashMapWithExpectedSize, size, vertexSet, put, IsomorphicGraphMapping]\", \"classes\" : \"[Map]\", \"vars\" : \"[]\" }", "package": "org.jgrapht.alg.isomorphism", "project": "jgrapht-master" }, { "_id": "636766fe1a6d9265ec017833", "all_context": "{ \"class_level\" : \"import java.io.*;\\nimport java.util.Collection;\\nimport java.util.List;\\nreadFileToString(File file);\\nreadFileToByteArray(File file);\\nreadLines(File file,String encoding);\\nreadLines(File file);\\nlineIterator(File file,String encoding);\\nlineIterator(File file);\\nwriteStringToFile(File file,String data,String encoding);\\nwriteStringToFile(File file,String data,String encoding,boolean append);\\nwriteStringToFile(File file,String data);\\nwriteStringToFile(File file,String data,boolean append);\\nwrite(File file,CharSequence data);\\nwrite(File file,CharSequence data,boolean append);\\nwrite(File file,CharSequence data,String encoding);\\nwrite(File file,CharSequence data,String encoding,boolean append);\\nwriteByteArrayToFile(File file,byte[] data);\\nwriteByteArrayToFile(File file,byte[] data,boolean append);\\nwriteLines(File file,String encoding,Collection lines);\\nwriteLines(File file,String encoding,Collection lines,boolean append);\\nwriteLines(File file,Collection lines);\\nwriteLines(File file,Collection lines,boolean append);\\nwriteLines(File file,String encoding,Collection lines,String lineEnding);\\nwriteLines(File file,String encoding,Collection lines,String lineEnding,boolean append);\\nwriteLines(File file,Collection lines,String lineEnding);\\nwriteLines(File file,Collection lines,String lineEnding,boolean append);\\nopenInputStream(File file);\\nopenOutputStream(File file);\\nopenOutputStream(File file,boolean append);\\ndeleteDirectory(File directory);\\ncleanDirectory(File directory);\\ndeleteQuietly(File file);\\ndeleteDirectoryOnExit(File directory);\\ncleanDirectoryOnExit(File directory);\\nisSymlink(File file);\\nforceDelete(File file);\\nforceDeleteOnExit(File file);\\nreadFileToString(File file,String encoding);\\n\", \"repo_level\" : \"\" }", "class_name": "FileUtils", "code": "public static void forceDeleteOnExit(File file) throws IOException {\n if (file.isDirectory()) {\n deleteDirectoryOnExit(file);\n }\n else {\n file.deleteOnExit();\n }\n}\n", "docstring": "/** \n * Schedules a file to be deleted when JVM exits. If file is directory delete it and all sub-directories.\n * @param file file or directory to delete, must not be {@code null}\n * @throws NullPointerException if the file is {@code null}\n * @throws IOException in case deletion is unsuccessful\n */\n", "end_lineno": "783", "file_content": "/*\n * Copyright 2008-2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.io;\nimport java.io.*;\nimport java.util.Collection;\nimport java.util.List;\n\n/**\n * 文件工具\n * @version : 2011-6-3\n * @author 赵永春 (zyc@hasor.net)\n */\npublic abstract class FileUtils {\n /**\n * Reads the contents of a file into a String.\n * The file is always closed.\n *\n * @param file the file to read, must not be null\n * @param encoding the encoding to use, null means platform default\n * @return the file contents, never null\n * @throws IOException in case of an I/O error\n * @throws UnsupportedEncodingException if the encoding is not supported by the VM\n */\n public static String readFileToString(File file, String encoding) throws IOException {\n InputStream in = null;\n try {\n in = openInputStream(file);\n return IOUtils.toString(in, encoding);\n } finally {\n IOUtils.closeQuietly(in);\n }\n }\n\n /**\n * Reads the contents of a file into a String using the default encoding for the VM. \n * The file is always closed.\n *\n * @param file the file to read, must not be null\n * @return the file contents, never null\n * @throws IOException in case of an I/O error\n * @since Commons IO 1.3.1\n */\n public static String readFileToString(File file) throws IOException {\n return readFileToString(file, null);\n }\n\n /**\n * Reads the contents of a file into a byte array.\n * The file is always closed.\n *\n * @param file the file to read, must not be null\n * @return the file contents, never null\n * @throws IOException in case of an I/O error\n * @since Commons IO 1.1\n */\n public static byte[] readFileToByteArray(File file) throws IOException {\n InputStream in = null;\n try {\n in = openInputStream(file);\n return IOUtils.toByteArray(in, file.length());\n } finally {\n IOUtils.closeQuietly(in);\n }\n }\n\n /**\n * Reads the contents of a file line by line to a List of Strings.\n * The file is always closed.\n *\n * @param file the file to read, must not be null\n * @param encoding the encoding to use, null means platform default\n * @return the list of Strings representing each line in the file, never null\n * @throws IOException in case of an I/O error\n * @throws UnsupportedEncodingException if the encoding is not supported by the VM\n * @since Commons IO 1.1\n */\n public static List readLines(File file, String encoding) throws IOException {\n InputStream in = null;\n try {\n in = openInputStream(file);\n return IOUtils.readLines(in, encoding);\n } finally {\n IOUtils.closeQuietly(in);\n }\n }\n\n /**\n * Reads the contents of a file line by line to a List of Strings using the default encoding for the VM.\n * The file is always closed.\n *\n * @param file the file to read, must not be null\n * @return the list of Strings representing each line in the file, never null\n * @throws IOException in case of an I/O error\n * @since Commons IO 1.3\n */\n public static List readLines(File file) throws IOException {\n return readLines(file, null);\n }\n\n /**\n * Returns an Iterator for the lines in a File.\n *

\n * This method opens an InputStream for the file.\n * When you have finished with the iterator you should close the stream\n * to free internal resources. This can be done by calling the\n * {@link LineIterator#close()} or\n * {@link LineIterator#closeQuietly(LineIterator)} method.\n *

\n * The recommended usage pattern is:\n *

\n     * LineIterator it = FileUtils.lineIterator(file, \"UTF-8\");\n     * try {\n     *   while (it.hasNext()) {\n     *     String line = it.nextLine();\n     *     /// do something with line\n     *   }\n     * } finally {\n     *   LineIterator.closeQuietly(iterator);\n     * }\n     * 
\n *

\n * If an exception occurs during the creation of the iterator, the\n * underlying stream is closed.\n *\n * @param file the file to open for input, must not be null\n * @param encoding the encoding to use, null means platform default\n * @return an Iterator of the lines in the file, never null\n * @throws IOException in case of an I/O error (file closed)\n * @since Commons IO 1.2\n */\n public static LineIterator lineIterator(File file, String encoding) throws IOException {\n InputStream in = null;\n try {\n in = openInputStream(file);\n return IOUtils.lineIterator(in, encoding);\n } catch (IOException ex) {\n IOUtils.closeQuietly(in);\n throw ex;\n } catch (RuntimeException ex) {\n IOUtils.closeQuietly(in);\n throw ex;\n }\n }\n\n /**\n * Returns an Iterator for the lines in a File using the default encoding for the VM.\n *\n * @param file the file to open for input, must not be null\n * @return an Iterator of the lines in the file, never null\n * @throws IOException in case of an I/O error (file closed)\n * @since Commons IO 1.3\n * @see #lineIterator(File, String)\n */\n public static LineIterator lineIterator(File file) throws IOException {\n return lineIterator(file, null);\n }\n //-----------------------------------------------------------------------\n\n /**\n * Writes a String to a file creating the file if it does not exist.\n *\n * NOTE: As from v1.3, the parent directories of the file will be created\n * if they do not exist.\n *\n * @param file the file to write\n * @param data the content to write to the file\n * @param encoding the encoding to use, null means platform default\n * @throws IOException in case of an I/O error\n * @throws UnsupportedEncodingException if the encoding is not supported by the VM\n */\n public static void writeStringToFile(File file, String data, String encoding) throws IOException {\n writeStringToFile(file, data, encoding, false);\n }\n\n /**\n * Writes a String to a file creating the file if it does not exist.\n *\n * @param file the file to write\n * @param data the content to write to the file\n * @param encoding the encoding to use, null means platform default\n * @param append if true, then the String will be added to the\n * end of the file rather than overwriting\n * @throws IOException in case of an I/O error\n * @throws UnsupportedEncodingException if the encoding is not supported by the VM\n * @since Commons IO 2.1\n */\n public static void writeStringToFile(File file, String data, String encoding, boolean append) throws IOException {\n OutputStream out = null;\n try {\n out = openOutputStream(file, append);\n IOUtils.write(data, out, encoding);\n } finally {\n IOUtils.closeQuietly(out);\n }\n }\n\n /**\n * Writes a String to a file creating the file if it does not exist using the default encoding for the VM.\n *\n * @param file the file to write\n * @param data the content to write to the file\n * @throws IOException in case of an I/O error\n */\n public static void writeStringToFile(File file, String data) throws IOException {\n writeStringToFile(file, data, null, false);\n }\n\n /**\n * Writes a String to a file creating the file if it does not exist using the default encoding for the VM.\n *\n * @param file the file to write\n * @param data the content to write to the file\n * @param append if true, then the String will be added to the\n * end of the file rather than overwriting\n * @throws IOException in case of an I/O error\n * @since Commons IO 2.1\n */\n public static void writeStringToFile(File file, String data, boolean append) throws IOException {\n writeStringToFile(file, data, null, append);\n }\n\n /**\n * Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM.\n *\n * @param file the file to write\n * @param data the content to write to the file\n * @throws IOException in case of an I/O error\n * @since Commons IO 2.0\n */\n public static void write(File file, CharSequence data) throws IOException {\n write(file, data, null, false);\n }\n\n /**\n * Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM.\n *\n * @param file the file to write\n * @param data the content to write to the file\n * @param append if true, then the data will be added to the\n * end of the file rather than overwriting\n * @throws IOException in case of an I/O error\n * @since Commons IO 2.1\n */\n public static void write(File file, CharSequence data, boolean append) throws IOException {\n write(file, data, null, append);\n }\n\n /**\n * Writes a CharSequence to a file creating the file if it does not exist.\n *\n * @param file the file to write\n * @param data the content to write to the file\n * @param encoding the encoding to use, null means platform default\n * @throws IOException in case of an I/O error\n * @throws UnsupportedEncodingException if the encoding is not supported by the VM\n * @since Commons IO 2.0\n */\n public static void write(File file, CharSequence data, String encoding) throws IOException {\n write(file, data, encoding, false);\n }\n\n /**\n * Writes a CharSequence to a file creating the file if it does not exist.\n *\n * @param file the file to write\n * @param data the content to write to the file\n * @param encoding the encoding to use, null means platform default\n * @param append if true, then the data will be added to the\n * end of the file rather than overwriting\n * @throws IOException in case of an I/O error\n * @throws UnsupportedEncodingException if the encoding is not supported by the VM\n * @since IO 2.1\n */\n public static void write(File file, CharSequence data, String encoding, boolean append) throws IOException {\n String str = data == null ? null : data.toString();\n writeStringToFile(file, str, encoding, append);\n }\n\n /**\n * Writes a byte array to a file creating the file if it does not exist.\n *

\n * NOTE: As from v1.3, the parent directories of the file will be created\n * if they do not exist.\n *\n * @param file the file to write to\n * @param data the content to write to the file\n * @throws IOException in case of an I/O error\n * @since Commons IO 1.1\n */\n public static void writeByteArrayToFile(File file, byte[] data) throws IOException {\n writeByteArrayToFile(file, data, false);\n }\n\n /**\n * Writes a byte array to a file creating the file if it does not exist.\n *\n * @param file the file to write to\n * @param data the content to write to the file\n * @param append if true, then bytes will be added to the\n * end of the file rather than overwriting\n * @throws IOException in case of an I/O error\n * @since IO 2.1\n */\n public static void writeByteArrayToFile(File file, byte[] data, boolean append) throws IOException {\n OutputStream out = null;\n try {\n out = openOutputStream(file, append);\n out.write(data);\n } finally {\n IOUtils.closeQuietly(out);\n }\n }\n\n /**\n * Writes the toString() value of each item in a collection to\n * the specified File line by line.\n * The specified character encoding and the default line ending will be used.\n *

\n * NOTE: As from v1.3, the parent directories of the file will be created\n * if they do not exist.\n *\n * @param file the file to write to\n * @param encoding the encoding to use, null means platform default\n * @param lines the lines to write, null entries produce blank lines\n * @throws IOException in case of an I/O error\n * @throws UnsupportedEncodingException if the encoding is not supported by the VM\n * @since Commons IO 1.1\n */\n public static void writeLines(File file, String encoding, Collection lines) throws IOException {\n writeLines(file, encoding, lines, null, false);\n }\n\n /**\n * Writes the toString() value of each item in a collection to\n * the specified File line by line, optionally appending.\n * The specified character encoding and the default line ending will be used.\n *\n * @param file the file to write to\n * @param encoding the encoding to use, null means platform default\n * @param lines the lines to write, null entries produce blank lines\n * @param append if true, then the lines will be added to the\n * end of the file rather than overwriting\n * @throws IOException in case of an I/O error\n * @throws UnsupportedEncodingException if the encoding is not supported by the VM\n * @since Commons IO 2.1\n */\n public static void writeLines(File file, String encoding, Collection lines, boolean append) throws IOException {\n writeLines(file, encoding, lines, null, append);\n }\n\n /**\n * Writes the toString() value of each item in a collection to\n * the specified File line by line.\n * The default VM encoding and the default line ending will be used.\n *\n * @param file the file to write to\n * @param lines the lines to write, null entries produce blank lines\n * @throws IOException in case of an I/O error\n * @since Commons IO 1.3\n */\n public static void writeLines(File file, Collection lines) throws IOException {\n writeLines(file, null, lines, null, false);\n }\n\n /**\n * Writes the toString() value of each item in a collection to\n * the specified File line by line.\n * The default VM encoding and the default line ending will be used.\n *\n * @param file the file to write to\n * @param lines the lines to write, null entries produce blank lines\n * @param append if true, then the lines will be added to the\n * end of the file rather than overwriting\n * @throws IOException in case of an I/O error\n * @since Commons IO 2.1\n */\n public static void writeLines(File file, Collection lines, boolean append) throws IOException {\n writeLines(file, null, lines, null, append);\n }\n\n /**\n * Writes the toString() value of each item in a collection to\n * the specified File line by line.\n * The specified character encoding and the line ending will be used.\n *

\n * NOTE: As from v1.3, the parent directories of the file will be created\n * if they do not exist.\n *\n * @param file the file to write to\n * @param encoding the encoding to use, null means platform default\n * @param lines the lines to write, null entries produce blank lines\n * @param lineEnding the line separator to use, null is system default\n * @throws IOException in case of an I/O error\n * @throws UnsupportedEncodingException if the encoding is not supported by the VM\n * @since Commons IO 1.1\n */\n public static void writeLines(File file, String encoding, Collection lines, String lineEnding) throws IOException {\n writeLines(file, encoding, lines, lineEnding, false);\n }\n\n /**\n * Writes the toString() value of each item in a collection to\n * the specified File line by line.\n * The specified character encoding and the line ending will be used.\n *\n * @param file the file to write to\n * @param encoding the encoding to use, null means platform default\n * @param lines the lines to write, null entries produce blank lines\n * @param lineEnding the line separator to use, null is system default\n * @param append if true, then the lines will be added to the\n * end of the file rather than overwriting\n * @throws IOException in case of an I/O error\n * @throws UnsupportedEncodingException if the encoding is not supported by the VM\n * @since Commons IO 2.1\n */\n public static void writeLines(File file, String encoding, Collection lines, String lineEnding, boolean append) throws IOException {\n OutputStream out = null;\n try {\n out = openOutputStream(file, append);\n IOUtils.writeLines(lines, lineEnding, out, encoding);\n } finally {\n IOUtils.closeQuietly(out);\n }\n }\n\n /**\n * Writes the toString() value of each item in a collection to\n * the specified File line by line.\n * The default VM encoding and the specified line ending will be used.\n *\n * @param file the file to write to\n * @param lines the lines to write, null entries produce blank lines\n * @param lineEnding the line separator to use, null is system default\n * @throws IOException in case of an I/O error\n * @since Commons IO 1.3\n */\n public static void writeLines(File file, Collection lines, String lineEnding) throws IOException {\n writeLines(file, null, lines, lineEnding, false);\n }\n\n /**\n * Writes the toString() value of each item in a collection to\n * the specified File line by line.\n * The default VM encoding and the specified line ending will be used.\n *\n * @param file the file to write to\n * @param lines the lines to write, null entries produce blank lines\n * @param lineEnding the line separator to use, null is system default\n * @param append if true, then the lines will be added to the\n * end of the file rather than overwriting\n * @throws IOException in case of an I/O error\n * @since Commons IO 2.1\n */\n public static void writeLines(File file, Collection lines, String lineEnding, boolean append) throws IOException {\n writeLines(file, null, lines, lineEnding, append);\n }\n //-----------------------------------------------------------------------\n\n /**\n * Opens a {@link FileInputStream} for the specified file, providing better\n * error messages than simply calling new FileInputStream(file).\n *

\n * At the end of the method either the stream will be successfully opened,\n * or an exception will have been thrown.\n *

\n * An exception is thrown if the file does not exist.\n * An exception is thrown if the file object exists but is a directory.\n * An exception is thrown if the file exists but cannot be read.\n *\n * @param file the file to open for input, must not be null\n * @return a new {@link FileInputStream} for the specified file\n * @throws FileNotFoundException if the file does not exist\n * @throws IOException if the file object is a directory\n * @throws IOException if the file cannot be read\n * @since Commons IO 1.3\n */\n public static FileInputStream openInputStream(File file) throws IOException {\n if (file.exists()) {\n if (file.isDirectory()) {\n throw new IOException(\"File '\" + file + \"' exists but is a directory\");\n }\n if (file.canRead() == false) {\n throw new IOException(\"File '\" + file + \"' cannot be read\");\n }\n } else {\n throw new FileNotFoundException(\"File '\" + file + \"' does not exist\");\n }\n return new FileInputStream(file);\n }\n //-----------------------------------------------------------------------\n\n /**\n * Opens a {@link FileOutputStream} for the specified file, checking and\n * creating the parent directory if it does not exist.\n *

\n * At the end of the method either the stream will be successfully opened,\n * or an exception will have been thrown.\n *

\n * The parent directory will be created if it does not exist.\n * The file will be created if it does not exist.\n * An exception is thrown if the file object exists but is a directory.\n * An exception is thrown if the file exists but cannot be written to.\n * An exception is thrown if the parent directory cannot be created.\n *\n * @param file the file to open for output, must not be null\n * @return a new {@link FileOutputStream} for the specified file\n * @throws IOException if the file object is a directory\n * @throws IOException if the file cannot be written to\n * @throws IOException if a parent directory needs creating but that fails\n * @since Commons IO 1.3\n */\n public static FileOutputStream openOutputStream(File file) throws IOException {\n return openOutputStream(file, false);\n }\n\n /**\n * Opens a {@link FileOutputStream} for the specified file, checking and\n * creating the parent directory if it does not exist.\n *

\n * At the end of the method either the stream will be successfully opened,\n * or an exception will have been thrown.\n *

\n * The parent directory will be created if it does not exist.\n * The file will be created if it does not exist.\n * An exception is thrown if the file object exists but is a directory.\n * An exception is thrown if the file exists but cannot be written to.\n * An exception is thrown if the parent directory cannot be created.\n *\n * @param file the file to open for output, must not be null\n * @param append if true, then bytes will be added to the\n * end of the file rather than overwriting\n * @return a new {@link FileOutputStream} for the specified file\n * @throws IOException if the file object is a directory\n * @throws IOException if the file cannot be written to\n * @throws IOException if a parent directory needs creating but that fails\n * @since Commons IO 2.1\n */\n public static FileOutputStream openOutputStream(File file, boolean append) throws IOException {\n if (file.exists()) {\n if (file.isDirectory()) {\n throw new IOException(\"File '\" + file + \"' exists but is a directory\");\n }\n if (file.canWrite() == false) {\n throw new IOException(\"File '\" + file + \"' cannot be written to\");\n }\n } else {\n File parent = file.getParentFile();\n if (parent != null) {\n if (!parent.mkdirs() && !parent.isDirectory()) {\n throw new IOException(\"Directory '\" + parent + \"' could not be created\");\n }\n }\n }\n return new FileOutputStream(file, append);\n }\n //-----------------------------------------------------------------------\n\n /**\n * Deletes a directory recursively. \n *\n * @param directory directory to delete\n * @throws IOException in case deletion is unsuccessful\n */\n public static void deleteDirectory(File directory) throws IOException {\n if (!directory.exists()) {\n return;\n }\n if (!isSymlink(directory)) {\n cleanDirectory(directory);\n }\n if (!directory.delete()) {\n String message = \"Unable to delete directory \" + directory + \".\";\n throw new IOException(message);\n }\n }\n\n /**\n * Cleans a directory without deleting it.\n *\n * @param directory directory to clean\n * @throws IOException in case cleaning is unsuccessful\n */\n public static void cleanDirectory(File directory) throws IOException {\n if (!directory.exists()) {\n String message = directory + \" does not exist\";\n throw new IllegalArgumentException(message);\n }\n if (!directory.isDirectory()) {\n String message = directory + \" is not a directory\";\n throw new IllegalArgumentException(message);\n }\n File[] files = directory.listFiles();\n if (files == null) { // null if security restricted\n throw new IOException(\"Failed to list contents of \" + directory);\n }\n IOException exception = null;\n for (File file : files) {\n try {\n forceDelete(file);\n } catch (IOException ioe) {\n exception = ioe;\n }\n }\n if (null != exception) {\n throw exception;\n }\n }\n\n /**\n * Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.\n *

\n * The difference between File.delete() and this method are:\n *

    \n *
  • A directory to be deleted does not have to be empty.
  • \n *
  • No exceptions are thrown when a file or directory cannot be deleted.
  • \n *
\n *\n * @param file file or directory to delete, can be {@code null}\n * @return {@code true} if the file or directory was deleted, otherwise\n * {@code false}\n *\n * @since 1.4\n */\n public static boolean deleteQuietly(File file) {\n if (file == null) {\n return false;\n }\n try {\n if (file.isDirectory()) {\n cleanDirectory(file);\n }\n } catch (Exception ignored) {\n }\n try {\n return file.delete();\n } catch (Exception ignored) {\n return false;\n }\n }\n\n /**\n * Schedules a directory recursively for deletion on JVM exit.\n *\n * @param directory directory to delete, must not be {@code null}\n * @throws NullPointerException if the directory is {@code null}\n * @throws IOException in case deletion is unsuccessful\n */\n private static void deleteDirectoryOnExit(File directory) throws IOException {\n if (!directory.exists()) {\n return;\n }\n directory.deleteOnExit();\n if (!isSymlink(directory)) {\n cleanDirectoryOnExit(directory);\n }\n }\n\n /**\n * Cleans a directory without deleting it.\n *\n * @param directory directory to clean, must not be {@code null}\n * @throws NullPointerException if the directory is {@code null}\n * @throws IOException in case cleaning is unsuccessful\n */\n private static void cleanDirectoryOnExit(File directory) throws IOException {\n if (!directory.exists()) {\n String message = directory + \" does not exist\";\n throw new IllegalArgumentException(message);\n }\n if (!directory.isDirectory()) {\n String message = directory + \" is not a directory\";\n throw new IllegalArgumentException(message);\n }\n File[] files = directory.listFiles();\n if (files == null) { // null if security restricted\n throw new IOException(\"Failed to list contents of \" + directory);\n }\n IOException exception = null;\n for (File file : files) {\n try {\n forceDeleteOnExit(file);\n } catch (IOException ioe) {\n exception = ioe;\n }\n }\n if (null != exception) {\n throw exception;\n }\n }\n\n /**\n * Determines whether the specified file is a Symbolic Link rather than an actual file.\n *

\n * Will not return true if there is a Symbolic Link anywhere in the path,\n * only if the specific file is.\n *

\n * Note: the current implementation always returns {@code false} if the system\n * is detected as Windows using {@link FilenameUtils#isSystemWindows()}\n *\n * @param file the file to check\n * @return true if the file is a Symbolic Link\n * @throws IOException if an IO error occurs while checking the file\n * @since 2.0\n */\n public static boolean isSymlink(File file) throws IOException {\n if (file == null) {\n throw new NullPointerException(\"File must not be null\");\n }\n if (FilenameUtils.isSystemWindows()) {\n return false;\n }\n File fileInCanonicalDir = null;\n if (file.getParent() == null) {\n fileInCanonicalDir = file;\n } else {\n File canonicalDir = file.getParentFile().getCanonicalFile();\n fileInCanonicalDir = new File(canonicalDir, file.getName());\n }\n if (fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile())) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Deletes a file. If file is a directory, delete it and all sub-directories.\n *

\n * The difference between File.delete() and this method are:\n *

    \n *
  • A directory to be deleted does not have to be empty.
  • \n *
  • You get exceptions when a file or directory cannot be deleted.\n * (java.io.File methods returns a boolean)
  • \n *
\n *\n * @param file file or directory to delete, must not be {@code null}\n * @throws NullPointerException if the directory is {@code null}\n * @throws FileNotFoundException if the file was not found\n * @throws IOException in case deletion is unsuccessful\n */\n public static void forceDelete(File file) throws IOException {\n if (file.isDirectory()) {\n deleteDirectory(file);\n } else {\n boolean filePresent = file.exists();\n if (!file.delete()) {\n if (!filePresent) {\n throw new FileNotFoundException(\"File does not exist: \" + file);\n }\n String message = \"Unable to delete file: \" + file;\n throw new IOException(message);\n }\n }\n }\n\n /**\n * Schedules a file to be deleted when JVM exits.\n * If file is directory delete it and all sub-directories.\n *\n * @param file file or directory to delete, must not be {@code null}\n * @throws NullPointerException if the file is {@code null}\n * @throws IOException in case deletion is unsuccessful\n */\n public static void forceDeleteOnExit(File file) throws IOException {\n if (file.isDirectory()) {\n deleteDirectoryOnExit(file);\n } else {\n file.deleteOnExit();\n }\n }\n}", "file_name": "FileUtils.java", "human_label": "Delete the file or the whole directory when exiting.", "level": "class_runnable", "lineno": "769", "name": "forceDeleteOnExit", "oracle_context": "{ \"apis\" : \"[isDirectory, deleteDirectoryOnExit, deleteOnExit]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils.io", "project": "hasor-master" }, { "_id": "636767791a6d9265ec018257", "all_context": "{ \"class_level\" : \"import java.awt.BorderLayout;\\nimport java.awt.Color;\\nimport java.awt.Component;\\nimport java.awt.Dimension;\\nimport java.awt.FlowLayout;\\nimport java.awt.Font;\\nimport java.awt.GraphicsEnvironment;\\nimport java.awt.Toolkit;\\nimport java.awt.event.ActionEvent;\\nimport java.awt.event.ActionListener;\\nimport java.awt.event.WindowAdapter;\\nimport java.awt.event.WindowEvent;\\nimport java.io.File;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport java.net.MalformedURLException;\\nimport java.net.URL;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Iterator;\\nimport java.util.List;\\nimport java.util.Map;\\nimport java.util.StringTokenizer;\\nimport java.util.Vector;\\nimport javax.swing.BorderFactory;\\nimport javax.swing.ImageIcon;\\nimport javax.swing.JButton;\\nimport javax.swing.JCheckBoxMenuItem;\\nimport javax.swing.JColorChooser;\\nimport javax.swing.JComboBox;\\nimport javax.swing.JFileChooser;\\nimport javax.swing.JFrame;\\nimport javax.swing.JLabel;\\nimport javax.swing.JMenu;\\nimport javax.swing.JMenuBar;\\nimport javax.swing.JMenuItem;\\nimport javax.swing.JOptionPane;\\nimport javax.swing.JPanel;\\nimport javax.swing.JScrollPane;\\nimport javax.swing.JSplitPane;\\nimport javax.swing.JTextArea;\\nimport javax.swing.JToolBar;\\nimport javax.swing.KeyStroke;\\nimport javax.swing.SwingUtilities;\\nimport org.apache.log4j.lf5.LogLevel;\\nimport org.apache.log4j.lf5.LogRecord;\\nimport org.apache.log4j.lf5.LogRecordFilter;\\nimport org.apache.log4j.lf5.util.DateFormatManager;\\nimport org.apache.log4j.lf5.util.LogFileParser;\\nimport org.apache.log4j.lf5.viewer.categoryexplorer.CategoryExplorerTree;\\nimport org.apache.log4j.lf5.viewer.categoryexplorer.CategoryPath;\\nimport org.apache.log4j.lf5.viewer.configure.ConfigurationManager;\\nimport org.apache.log4j.lf5.viewer.configure.MRUFileManager;\\nString DETAILED_VIEW;\\nJFrame _logMonitorFrame;\\nint _logMonitorFrameWidth;\\nint _logMonitorFrameHeight;\\nLogTable _table;\\nCategoryExplorerTree _categoryExplorerTree;\\nString _searchText;\\nString _NDCTextFilter;\\nLogLevel _leastSevereDisplayedLogLevel;\\nJScrollPane _logTableScrollPane;\\nJLabel _statusLabel;\\nObject _lock;\\nJComboBox _fontSizeCombo;\\nint _fontSize;\\nString _fontName;\\nString _currentView;\\nboolean _loadSystemFonts;\\nboolean _trackTableScrollPane;\\nDimension _lastTableViewportSize;\\nboolean _callSystemExitOnClose;\\nList _displayedLogBrokerProperties;\\nMap _logLevelMenuItems;\\nMap _logTableColumnMenuItems;\\nList _levels;\\nList _columns;\\nboolean _isDisposed;\\nConfigurationManager _configurationManager;\\nMRUFileManager _mruFileManager;\\nFile _fileLocation;\\nLogBrokerMonitor _monitor;\\nLogBrokerMonitor(List logLevels);\\nrun();\\nshow();\\ndispose();\\nhide();\\ngetDateFormatManager();\\nsetDateFormatManager(DateFormatManager dfm);\\ngetCallSystemExitOnClose();\\nsetCallSystemExitOnClose(boolean callSystemExitOnClose);\\naddMessage(LogRecord lr);\\nsetMaxNumberOfLogRecords(int maxNumberOfLogRecords);\\ngetBaseFrame();\\nsetTitle(String title);\\nsetFrameSize(int width,int height);\\nsetFontSize(int fontSize);\\naddDisplayedProperty(Object messageLine);\\ngetLogLevelMenuItems();\\ngetLogTableColumnMenuItems();\\ngetTableColumnMenuItem(LogTableColumn column);\\ngetCategoryExplorerTree();\\ngetNDCTextFilter();\\nsetNDCLogRecordFilter(String textFilter);\\nsetSearchText(String text);\\nsetNDCTextFilter(String text);\\nsortByNDC();\\nfindSearchText();\\ngetFirstSelectedRow();\\nselectRow(int foundRow);\\nfindRecord(int startRow,String searchText,List records);\\nmatches(LogRecord record,String text);\\nrefresh(JTextArea textArea);\\nrefreshDetailTextArea();\\nclearDetailTextArea();\\nchangeFontSizeCombo(JComboBox box,int requestedSize);\\nsetFontSizeSilently(int fontSize);\\nsetFontSize(Component component,int fontSize);\\nupdateFrameSize();\\npause(int millis);\\ninitComponents();\\ncreateLogRecordFilter();\\npasses(LogRecord record);\\ncreateNDCLogRecordFilter(String text);\\nupdateStatusLabel();\\ngetRecordsDisplayedMessage();\\naddTableModelProperties();\\ntoString();\\ngetStatusText(int displayedRows,int totalRows);\\nmakeLogTableListenToCategoryExplorer();\\nactionPerformed(ActionEvent e);\\ncreateStatusArea();\\ncreateDetailTextArea();\\ncreateMenuBar();\\ncreateLogLevelMenu();\\ncreateAllLogLevelsMenuItem();\\ncreateNoLogLevelsMenuItem();\\ncreateLogLevelColorMenu();\\ncreateResetLogLevelColorMenuItem();\\nselectAllLogLevels(boolean selected);\\ngetMenuItem(LogLevel level);\\ncreateSubMenuItem(LogLevel level);\\nshowLogLevelColorChangeDialog(JMenuItem result,LogLevel level);\\ncreateMenuItem(LogLevel level);\\ncreateViewMenu();\\ngetLogTableColumnMenuItem(LogTableColumn column);\\ncreateLogTableColumnMenuItem(LogTableColumn column);\\nupdateView();\\ncreateAllLogTableColumnsMenuItem();\\ncreateNoLogTableColumnsMenuItem();\\nselectAllLogTableColumns(boolean selected);\\ncreateFileMenu();\\ncreateOpenMI();\\ncreateOpenURLMI();\\ncreateCloseMI();\\ncreateMRUFileListMI(JMenu menu);\\ncreateExitMI();\\ncreateConfigureMenu();\\ncreateConfigureSave();\\ncreateConfigureReset();\\ncreateConfigureMaxRecords();\\nsaveConfiguration();\\nresetConfiguration();\\nsetMaxRecordConfiguration();\\ncreateHelpMenu();\\ncreateHelpProperties();\\nshowPropertiesDialog(String title);\\ncreateEditMenu();\\ncreateEditFindNextMI();\\ncreateEditFindMI();\\ncreateEditSortNDCMI();\\ncreateEditRestoreAllNDCMI();\\ncreateToolBar();\\nsetView(String viewString,LogTable table);\\ncreateLogLevelCombo();\\nsetLeastSevereDisplayedLogLevel(LogLevel level);\\ntrackTableScrollPane();\\ncenterFrame(JFrame frame);\\nrequestOpen();\\nrequestOpenURL();\\nupdateMRUList();\\nrequestClose();\\nrequestOpenMRU(ActionEvent e);\\nrequestExit();\\ncloseAfterConfirm();\\ngetLogLevels();\\ngetLogTableColumns();\\nloadLogFile(File file);\\nloadLogFile(URL url);\\nLogBrokerMonitorWindowAdaptor(LogBrokerMonitor monitor);\\nwindowClosing(WindowEvent ev);\\nshow(int delay);\\n\", \"repo_level\" : \"public interface LogLevel {public String getLabel();\\npublic boolean encompasses(LogLevel level);\\nstatic LogLevel valueOf(String level);\\nstatic LogLevel register(LogLevel logLevel);\\nstatic void register(LogLevel[] logLevels);\\nstatic void register(List logLevels);\\npublic boolean equals(Object o);\\npublic int hashCode();\\npublic String toString();\\npublic void setLogLevelColorMap(LogLevel level,Color color);\\nstatic void resetLogLevelColorMap();\\nstatic List getLog4JLevels();\\nstatic List getJdk14Levels();\\nstatic List getAllDefaultLevels();\\nstatic Map getLogLevelColorMap();\\nprotected int getPrecedence();\\n }\\npublic interface LogRecord {public LogLevel getLevel();\\npublic void setLevel(LogLevel level);\\nabstract boolean isSevereLevel();\\npublic boolean hasThrown();\\npublic boolean isFatal();\\npublic String getCategory();\\npublic void setCategory(String category);\\npublic String getMessage();\\npublic void setMessage(String message);\\npublic long getSequenceNumber();\\npublic void setSequenceNumber(long number);\\npublic long getMillis();\\npublic void setMillis(long millis);\\npublic String getThreadDescription();\\npublic void setThreadDescription(String threadDescription);\\npublic String getThrownStackTrace();\\npublic void setThrownStackTrace(String trace);\\npublic Throwable getThrown();\\npublic void setThrown(Throwable thrown);\\npublic String toString();\\npublic String getNDC();\\npublic void setNDC(String ndc);\\npublic String getLocation();\\npublic void setLocation(String location);\\nsynchronized void resetSequenceNumber();\\nsynchronized long getNextId();\\n }\\npublic interface LogRecordFilter {public boolean passes(LogRecord record);\\n }\\npublic interface DateFormatManager {synchronized TimeZone getTimeZone();\\nsynchronized void setTimeZone(TimeZone timeZone);\\nsynchronized Locale getLocale();\\nsynchronized void setLocale(Locale locale);\\nsynchronized String getPattern();\\nsynchronized void setPattern(String pattern);\\nsynchronized String getOutputFormat();\\nsynchronized void setOutputFormat(String pattern);\\nsynchronized DateFormat getDateFormatInstance();\\nsynchronized void setDateFormatInstance(DateFormat dateFormat);\\npublic String format(Date date);\\npublic String format(Date date,String pattern);\\npublic Date parse(String date);\\npublic Date parse(String date,String pattern);\\n }\\npublic interface LogFileParser {public void parse(LogBrokerMonitor monitor);\\npublic void run();\\npublic void run();\\nprotected void displayError(String message);\\n }\\npublic interface CategoryExplorerTree {public CategoryExplorerModel getExplorerModel();\\npublic String getToolTipText(MouseEvent e);\\nprotected void init();\\nprotected void expandRootNode();\\nprotected void ensureRootExpansion();\\npublic void treeNodesInserted(TreeModelEvent e);\\n }\\npublic interface CategoryPath {public int size();\\npublic boolean isEmpty();\\npublic void removeAllCategoryElements();\\npublic void addCategoryElement(CategoryElement categoryElement);\\npublic CategoryElement categoryElementAt(int index);\\npublic String toString();\\n }\\npublic interface ConfigurationManager {public void save();\\npublic void reset();\\nstatic String treePathToString(TreePath path);\\nprotected void load();\\nprotected void processRecordFilter(Document doc);\\nprotected void processCategories(Document doc);\\nprotected void processLogLevels(Document doc);\\nprotected void processLogLevelColors(Document doc);\\nprotected void processLogTableColumns(Document doc);\\nprotected String getValue(NamedNodeMap map,String attr);\\nprotected void collapseTree();\\nprotected void selectAllNodes();\\nprotected void store(String s);\\nprotected void deleteConfigurationFile();\\nprotected String getFilename();\\n }\\npublic interface MRUFileManager {public void save();\\npublic int size();\\npublic Object getFile(int index);\\npublic InputStream getInputStream(int index);\\npublic void set(File file);\\npublic void set(URL url);\\npublic String[] getMRUFileList();\\npublic void moveToTop(int index);\\nstatic void createConfigurationDirectory();\\nprotected InputStream getInputStream(File file);\\nprotected InputStream getInputStream(URL url);\\nprotected void setMRU(Object o);\\nprotected void load();\\nprotected String getFilename();\\nprotected void setMaxSize(int maxSize);\\n }\\n\" }", "class_name": "LogBrokerMonitor", "code": "public void addMessage(final LogRecord lr){\n if (_isDisposed == true) {\n return;\n }\n SwingUtilities.invokeLater(new Runnable(){\n public void run(){\n _categoryExplorerTree.getExplorerModel().addLogRecord(lr);\n _table.getFilteredLogTableModel().addLogRecord(lr);\n updateStatusLabel();\n }\n }\n);\n}\n", "docstring": "/** \n * Add a log record message to be displayed in the LogTable. This method is thread-safe as it posts requests to the SwingThread rather than processing directly.\n */\n", "end_lineno": "265", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.log4j.lf5.viewer;\n\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Component;\nimport java.awt.Dimension;\nimport java.awt.FlowLayout;\nimport java.awt.Font;\nimport java.awt.GraphicsEnvironment;\nimport java.awt.Toolkit;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.StringTokenizer;\nimport java.util.Vector;\n\nimport javax.swing.BorderFactory;\nimport javax.swing.ImageIcon;\nimport javax.swing.JButton;\nimport javax.swing.JCheckBoxMenuItem;\nimport javax.swing.JColorChooser;\nimport javax.swing.JComboBox;\nimport javax.swing.JFileChooser;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JMenu;\nimport javax.swing.JMenuBar;\nimport javax.swing.JMenuItem;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JSplitPane;\nimport javax.swing.JTextArea;\nimport javax.swing.JToolBar;\nimport javax.swing.KeyStroke;\nimport javax.swing.SwingUtilities;\n\nimport org.apache.log4j.lf5.LogLevel;\nimport org.apache.log4j.lf5.LogRecord;\nimport org.apache.log4j.lf5.LogRecordFilter;\nimport org.apache.log4j.lf5.util.DateFormatManager;\nimport org.apache.log4j.lf5.util.LogFileParser;\nimport org.apache.log4j.lf5.viewer.categoryexplorer.CategoryExplorerTree;\nimport org.apache.log4j.lf5.viewer.categoryexplorer.CategoryPath;\nimport org.apache.log4j.lf5.viewer.configure.ConfigurationManager;\nimport org.apache.log4j.lf5.viewer.configure.MRUFileManager;\n\n/**\n * LogBrokerMonitor\n *.\n * @author Michael J. Sikorsky\n * @author Robert Shaw\n * @author Brad Marlborough\n * @author Richard Wan\n * @author Brent Sprecher\n * @author Richard Hurst\n */\n\n// Contributed by ThoughtWorks Inc.\n\npublic class LogBrokerMonitor {\n //--------------------------------------------------------------------------\n // Constants:\n //--------------------------------------------------------------------------\n\n public static final String DETAILED_VIEW = \"Detailed\";\n// public static final String STANDARD_VIEW = \"Standard\";\n// public static final String COMPACT_VIEW = \"Compact\";\n //--------------------------------------------------------------------------\n // Protected Variables:\n //--------------------------------------------------------------------------\n protected JFrame _logMonitorFrame;\n protected int _logMonitorFrameWidth = 550;\n protected int _logMonitorFrameHeight = 500;\n protected LogTable _table;\n protected CategoryExplorerTree _categoryExplorerTree;\n protected String _searchText;\n protected String _NDCTextFilter = \"\";\n protected LogLevel _leastSevereDisplayedLogLevel = LogLevel.DEBUG;\n\n protected JScrollPane _logTableScrollPane;\n protected JLabel _statusLabel;\n protected Object _lock = new Object();\n protected JComboBox _fontSizeCombo;\n\n protected int _fontSize = 10;\n protected String _fontName = \"Dialog\";\n protected String _currentView = DETAILED_VIEW;\n\n protected boolean _loadSystemFonts = false;\n protected boolean _trackTableScrollPane = true;\n protected Dimension _lastTableViewportSize;\n protected boolean _callSystemExitOnClose = false;\n protected List _displayedLogBrokerProperties = new Vector();\n\n protected Map _logLevelMenuItems = new HashMap();\n protected Map _logTableColumnMenuItems = new HashMap();\n\n protected List _levels = null;\n protected List _columns = null;\n protected boolean _isDisposed = false;\n\n protected ConfigurationManager _configurationManager = null;\n protected MRUFileManager _mruFileManager = null;\n protected File _fileLocation = null;\n\n //--------------------------------------------------------------------------\n // Private Variables:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Constructors:\n //--------------------------------------------------------------------------\n\n /**\n * Construct a LogBrokerMonitor.\n */\n public LogBrokerMonitor(List logLevels) {\n\n _levels = logLevels;\n _columns = LogTableColumn.getLogTableColumns();\n // This allows us to use the LogBroker in command line tools and\n // have the option for it to shutdown.\n\n String callSystemExitOnClose =\n System.getProperty(\"monitor.exit\");\n if (callSystemExitOnClose == null) {\n callSystemExitOnClose = \"false\";\n }\n callSystemExitOnClose = callSystemExitOnClose.trim().toLowerCase();\n\n if (callSystemExitOnClose.equals(\"true\")) {\n _callSystemExitOnClose = true;\n }\n\n initComponents();\n\n\n _logMonitorFrame.addWindowListener(\n new LogBrokerMonitorWindowAdaptor(this));\n\n }\n\n //--------------------------------------------------------------------------\n // Public Methods:\n //--------------------------------------------------------------------------\n\n /**\n * Show the frame for the LogBrokerMonitor. Dispatched to the\n * swing thread.\n */\n public void show(final int delay) {\n if (_logMonitorFrame.isVisible()) {\n return;\n }\n // This request is very low priority, let other threads execute first.\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n Thread.yield();\n pause(delay);\n _logMonitorFrame.setVisible(true);\n }\n });\n }\n\n public void show() {\n show(0);\n }\n\n /**\n * Dispose of the frame for the LogBrokerMonitor.\n */\n public void dispose() {\n _logMonitorFrame.dispose();\n _isDisposed = true;\n\n if (_callSystemExitOnClose == true) {\n System.exit(0);\n }\n }\n\n /**\n * Hide the frame for the LogBrokerMonitor.\n */\n public void hide() {\n _logMonitorFrame.setVisible(false);\n }\n\n /**\n * Get the DateFormatManager for formatting dates.\n */\n public DateFormatManager getDateFormatManager() {\n return _table.getDateFormatManager();\n }\n\n /**\n * Set the date format manager for formatting dates.\n */\n public void setDateFormatManager(DateFormatManager dfm) {\n _table.setDateFormatManager(dfm);\n }\n\n /**\n * Get the value of whether or not System.exit() will be called\n * when the LogBrokerMonitor is closed.\n */\n public boolean getCallSystemExitOnClose() {\n return _callSystemExitOnClose;\n }\n\n /**\n * Set the value of whether or not System.exit() will be called\n * when the LogBrokerMonitor is closed.\n */\n public void setCallSystemExitOnClose(boolean callSystemExitOnClose) {\n _callSystemExitOnClose = callSystemExitOnClose;\n }\n\n /**\n * Add a log record message to be displayed in the LogTable.\n * This method is thread-safe as it posts requests to the SwingThread\n * rather than processing directly.\n */\n public void addMessage(final LogRecord lr) {\n if (_isDisposed == true) {\n // If the frame has been disposed of, do not log any more\n // messages.\n return;\n }\n\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n _categoryExplorerTree.getExplorerModel().addLogRecord(lr);\n _table.getFilteredLogTableModel().addLogRecord(lr); // update table\n updateStatusLabel(); // show updated counts\n }\n });\n }\n\n public void setMaxNumberOfLogRecords(int maxNumberOfLogRecords) {\n _table.getFilteredLogTableModel().setMaxNumberOfLogRecords(maxNumberOfLogRecords);\n }\n\n public JFrame getBaseFrame() {\n return _logMonitorFrame;\n }\n\n public void setTitle(String title) {\n _logMonitorFrame.setTitle(title + \" - LogFactor5\");\n }\n\n public void setFrameSize(int width, int height) {\n Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();\n if (0 < width && width < screen.width) {\n _logMonitorFrameWidth = width;\n }\n if (0 < height && height < screen.height) {\n _logMonitorFrameHeight = height;\n }\n updateFrameSize();\n }\n\n public void setFontSize(int fontSize) {\n changeFontSizeCombo(_fontSizeCombo, fontSize);\n // setFontSizeSilently(actualFontSize); - changeFontSizeCombo fires event\n // refreshDetailTextArea();\n }\n\n public void addDisplayedProperty(Object messageLine) {\n _displayedLogBrokerProperties.add(messageLine);\n }\n\n public Map getLogLevelMenuItems() {\n return _logLevelMenuItems;\n }\n\n public Map getLogTableColumnMenuItems() {\n return _logTableColumnMenuItems;\n }\n\n public JCheckBoxMenuItem getTableColumnMenuItem(LogTableColumn column) {\n return getLogTableColumnMenuItem(column);\n }\n\n public CategoryExplorerTree getCategoryExplorerTree() {\n return _categoryExplorerTree;\n }\n\n // Added in version 1.2 - gets the value of the NDC text filter\n // This value is set back to null each time the Monitor is initialized.\n public String getNDCTextFilter() {\n return _NDCTextFilter;\n }\n\n // Added in version 1.2 - sets the NDC Filter based on\n // a String passed in by the user. This value is persisted\n // in the XML Configuration file.\n public void setNDCLogRecordFilter(String textFilter) {\n _table.getFilteredLogTableModel().\n setLogRecordFilter(createNDCLogRecordFilter(textFilter));\n }\n //--------------------------------------------------------------------------\n // Protected Methods:\n //--------------------------------------------------------------------------\n\n protected void setSearchText(String text) {\n _searchText = text;\n }\n\n // Added in version 1.2 - Sets the text filter for the NDC\n protected void setNDCTextFilter(String text) {\n // if no value is set, set it to a blank string\n // otherwise use the value provided\n if (text == null) {\n _NDCTextFilter = \"\";\n } else {\n _NDCTextFilter = text;\n }\n }\n\n // Added in version 1.2 - Uses a different filter that sorts\n // based on an NDC string passed in by the user. If the string\n // is null or is an empty string, we do nothing.\n protected void sortByNDC() {\n String text = _NDCTextFilter;\n if (text == null || text.length() == 0) {\n return;\n }\n\n // Use new NDC filter\n _table.getFilteredLogTableModel().\n setLogRecordFilter(createNDCLogRecordFilter(text));\n }\n\n protected void findSearchText() {\n String text = _searchText;\n if (text == null || text.length() == 0) {\n return;\n }\n int startRow = getFirstSelectedRow();\n int foundRow = findRecord(\n startRow,\n text,\n _table.getFilteredLogTableModel().getFilteredRecords()\n );\n selectRow(foundRow);\n }\n\n protected int getFirstSelectedRow() {\n return _table.getSelectionModel().getMinSelectionIndex();\n }\n\n protected void selectRow(int foundRow) {\n if (foundRow == -1) {\n String message = _searchText + \" not found.\";\n JOptionPane.showMessageDialog(\n _logMonitorFrame,\n message,\n \"Text not found\",\n JOptionPane.INFORMATION_MESSAGE\n );\n return;\n }\n LF5SwingUtils.selectRow(foundRow, _table, _logTableScrollPane);\n }\n\n protected int findRecord(\n int startRow,\n String searchText,\n List records\n ) {\n if (startRow < 0) {\n startRow = 0; // start at first element if no rows are selected\n } else {\n startRow++; // start after the first selected row\n }\n int len = records.size();\n\n for (int i = startRow; i < len; i++) {\n if (matches((LogRecord) records.get(i), searchText)) {\n return i; // found a record\n }\n }\n // wrap around to beginning if when we reach the end with no match\n len = startRow;\n for (int i = 0; i < len; i++) {\n if (matches((LogRecord) records.get(i), searchText)) {\n return i; // found a record\n }\n }\n // nothing found\n return -1;\n }\n\n /**\n * Check to see if the any records contain the search string.\n * Searching now supports NDC messages and date.\n */\n protected boolean matches(LogRecord record, String text) {\n String message = record.getMessage();\n String NDC = record.getNDC();\n\n if (message == null && NDC == null || text == null) {\n return false;\n }\n if (message.toLowerCase().indexOf(text.toLowerCase()) == -1 &&\n NDC.toLowerCase().indexOf(text.toLowerCase()) == -1) {\n return false;\n }\n\n return true;\n }\n\n /**\n * When the fontsize of a JTextArea is changed, the word-wrapped lines\n * may become garbled. This method clears and resets the text of the\n * text area.\n */\n protected void refresh(JTextArea textArea) {\n String text = textArea.getText();\n textArea.setText(\"\");\n textArea.setText(text);\n }\n\n protected void refreshDetailTextArea() {\n refresh(_table._detailTextArea);\n }\n\n protected void clearDetailTextArea() {\n _table._detailTextArea.setText(\"\");\n }\n\n /**\n * Changes the font selection in the combo box and returns the\n * size actually selected.\n * @return -1 if unable to select an appropriate font\n */\n protected int changeFontSizeCombo(JComboBox box, int requestedSize) {\n int len = box.getItemCount();\n int currentValue;\n Object currentObject;\n Object selectedObject = box.getItemAt(0);\n int selectedValue = Integer.parseInt(String.valueOf(selectedObject));\n for (int i = 0; i < len; i++) {\n currentObject = box.getItemAt(i);\n currentValue = Integer.parseInt(String.valueOf(currentObject));\n if (selectedValue < currentValue && currentValue <= requestedSize) {\n selectedValue = currentValue;\n selectedObject = currentObject;\n }\n }\n box.setSelectedItem(selectedObject);\n return selectedValue;\n }\n\n /**\n * Does not update gui or cause any events to be fired.\n */\n protected void setFontSizeSilently(int fontSize) {\n _fontSize = fontSize;\n setFontSize(_table._detailTextArea, fontSize);\n selectRow(0);\n setFontSize(_table, fontSize);\n }\n\n protected void setFontSize(Component component, int fontSize) {\n Font oldFont = component.getFont();\n Font newFont =\n new Font(oldFont.getFontName(), oldFont.getStyle(), fontSize);\n component.setFont(newFont);\n }\n\n protected void updateFrameSize() {\n _logMonitorFrame.setSize(_logMonitorFrameWidth, _logMonitorFrameHeight);\n centerFrame(_logMonitorFrame);\n }\n\n protected void pause(int millis) {\n try {\n Thread.sleep(millis);\n } catch (InterruptedException e) {\n\n }\n }\n\n protected void initComponents() {\n //\n // Configure the Frame.\n //\n _logMonitorFrame = new JFrame(\"LogFactor5\");\n\n _logMonitorFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);\n\n String resource =\n \"/org/apache/log4j/lf5/viewer/images/lf5_small_icon.gif\";\n URL lf5IconURL = getClass().getResource(resource);\n\n if (lf5IconURL != null) {\n _logMonitorFrame.setIconImage(new ImageIcon(lf5IconURL).getImage());\n }\n updateFrameSize();\n\n //\n // Configure the LogTable.\n //\n JTextArea detailTA = createDetailTextArea();\n JScrollPane detailTAScrollPane = new JScrollPane(detailTA);\n _table = new LogTable(detailTA);\n setView(_currentView, _table);\n _table.setFont(new Font(_fontName, Font.PLAIN, _fontSize));\n _logTableScrollPane = new JScrollPane(_table);\n\n if (_trackTableScrollPane) {\n _logTableScrollPane.getVerticalScrollBar().addAdjustmentListener(\n new TrackingAdjustmentListener()\n );\n }\n\n\n // Configure the SplitPane between the LogTable & DetailTextArea\n //\n\n JSplitPane tableViewerSplitPane = new JSplitPane();\n tableViewerSplitPane.setOneTouchExpandable(true);\n tableViewerSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);\n tableViewerSplitPane.setLeftComponent(_logTableScrollPane);\n tableViewerSplitPane.setRightComponent(detailTAScrollPane);\n // Make sure to do this last..\n //tableViewerSplitPane.setDividerLocation(1.0); Doesn't work\n //the same under 1.2.x & 1.3\n // \"350\" is a magic number that provides the correct default\n // behaviour under 1.2.x & 1.3. For example, bumping this\n // number to 400, causes the pane to be completely open in 1.2.x\n // and closed in 1.3\n tableViewerSplitPane.setDividerLocation(350);\n\n //\n // Configure the CategoryExplorer\n //\n\n _categoryExplorerTree = new CategoryExplorerTree();\n\n _table.getFilteredLogTableModel().setLogRecordFilter(createLogRecordFilter());\n\n JScrollPane categoryExplorerTreeScrollPane =\n new JScrollPane(_categoryExplorerTree);\n categoryExplorerTreeScrollPane.setPreferredSize(new Dimension(130, 400));\n\n // Load most recently used file list\n _mruFileManager = new MRUFileManager();\n\n //\n // Configure the SplitPane between the CategoryExplorer & (LogTable/Detail)\n //\n\n JSplitPane splitPane = new JSplitPane();\n splitPane.setOneTouchExpandable(true);\n splitPane.setRightComponent(tableViewerSplitPane);\n splitPane.setLeftComponent(categoryExplorerTreeScrollPane);\n // Do this last.\n splitPane.setDividerLocation(130);\n //\n // Add the MenuBar, StatusArea, CategoryExplorer|LogTable to the\n // LogMonitorFrame.\n //\n _logMonitorFrame.getRootPane().setJMenuBar(createMenuBar());\n _logMonitorFrame.getContentPane().add(splitPane, BorderLayout.CENTER);\n _logMonitorFrame.getContentPane().add(createToolBar(),\n BorderLayout.NORTH);\n _logMonitorFrame.getContentPane().add(createStatusArea(),\n BorderLayout.SOUTH);\n\n makeLogTableListenToCategoryExplorer();\n addTableModelProperties();\n\n //\n // Configure ConfigurationManager\n //\n _configurationManager = new ConfigurationManager(this, _table);\n\n }\n\n protected LogRecordFilter createLogRecordFilter() {\n LogRecordFilter result = new LogRecordFilter() {\n public boolean passes(LogRecord record) {\n CategoryPath path = new CategoryPath(record.getCategory());\n return\n getMenuItem(record.getLevel()).isSelected() &&\n _categoryExplorerTree.getExplorerModel().isCategoryPathActive(path);\n }\n };\n return result;\n }\n\n // Added in version 1.2 - Creates a new filter that sorts records based on\n // an NDC string passed in by the user.\n protected LogRecordFilter createNDCLogRecordFilter(String text) {\n _NDCTextFilter = text;\n LogRecordFilter result = new LogRecordFilter() {\n public boolean passes(LogRecord record) {\n String NDC = record.getNDC();\n CategoryPath path = new CategoryPath(record.getCategory());\n if (NDC == null || _NDCTextFilter == null) {\n return false;\n } else if (NDC.toLowerCase().indexOf(_NDCTextFilter.toLowerCase()) == -1) {\n return false;\n } else {\n return getMenuItem(record.getLevel()).isSelected() &&\n _categoryExplorerTree.getExplorerModel().isCategoryPathActive(path);\n }\n }\n };\n\n return result;\n }\n\n\n protected void updateStatusLabel() {\n _statusLabel.setText(getRecordsDisplayedMessage());\n }\n\n protected String getRecordsDisplayedMessage() {\n FilteredLogTableModel model = _table.getFilteredLogTableModel();\n return getStatusText(model.getRowCount(), model.getTotalRowCount());\n }\n\n protected void addTableModelProperties() {\n final FilteredLogTableModel model = _table.getFilteredLogTableModel();\n\n addDisplayedProperty(new Object() {\n public String toString() {\n return getRecordsDisplayedMessage();\n }\n });\n addDisplayedProperty(new Object() {\n public String toString() {\n return \"Maximum number of displayed LogRecords: \"\n + model._maxNumberOfLogRecords;\n }\n });\n }\n\n protected String getStatusText(int displayedRows, int totalRows) {\n StringBuffer result = new StringBuffer();\n result.append(\"Displaying: \");\n result.append(displayedRows);\n result.append(\" records out of a total of: \");\n result.append(totalRows);\n result.append(\" records.\");\n return result.toString();\n }\n\n protected void makeLogTableListenToCategoryExplorer() {\n ActionListener listener = new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n _table.getFilteredLogTableModel().refresh();\n updateStatusLabel();\n }\n };\n _categoryExplorerTree.getExplorerModel().addActionListener(listener);\n }\n\n protected JPanel createStatusArea() {\n JPanel statusArea = new JPanel();\n JLabel status =\n new JLabel(\"No log records to display.\");\n _statusLabel = status;\n status.setHorizontalAlignment(JLabel.LEFT);\n\n statusArea.setBorder(BorderFactory.createEtchedBorder());\n statusArea.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));\n statusArea.add(status);\n\n return (statusArea);\n }\n\n protected JTextArea createDetailTextArea() {\n JTextArea detailTA = new JTextArea();\n detailTA.setFont(new Font(\"Monospaced\", Font.PLAIN, 14));\n detailTA.setTabSize(3);\n detailTA.setLineWrap(true);\n detailTA.setWrapStyleWord(false);\n return (detailTA);\n }\n\n protected JMenuBar createMenuBar() {\n JMenuBar menuBar = new JMenuBar();\n menuBar.add(createFileMenu());\n menuBar.add(createEditMenu());\n menuBar.add(createLogLevelMenu());\n menuBar.add(createViewMenu());\n menuBar.add(createConfigureMenu());\n menuBar.add(createHelpMenu());\n\n return (menuBar);\n }\n\n protected JMenu createLogLevelMenu() {\n JMenu result = new JMenu(\"Log Level\");\n result.setMnemonic('l');\n Iterator levels = getLogLevels();\n while (levels.hasNext()) {\n result.add(getMenuItem((LogLevel) levels.next()));\n }\n\n result.addSeparator();\n result.add(createAllLogLevelsMenuItem());\n result.add(createNoLogLevelsMenuItem());\n result.addSeparator();\n result.add(createLogLevelColorMenu());\n result.add(createResetLogLevelColorMenuItem());\n\n return result;\n }\n\n protected JMenuItem createAllLogLevelsMenuItem() {\n JMenuItem result = new JMenuItem(\"Show all LogLevels\");\n result.setMnemonic('s');\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n selectAllLogLevels(true);\n _table.getFilteredLogTableModel().refresh();\n updateStatusLabel();\n }\n });\n return result;\n }\n\n protected JMenuItem createNoLogLevelsMenuItem() {\n JMenuItem result = new JMenuItem(\"Hide all LogLevels\");\n result.setMnemonic('h');\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n selectAllLogLevels(false);\n _table.getFilteredLogTableModel().refresh();\n updateStatusLabel();\n }\n });\n return result;\n }\n\n protected JMenu createLogLevelColorMenu() {\n JMenu colorMenu = new JMenu(\"Configure LogLevel Colors\");\n colorMenu.setMnemonic('c');\n Iterator levels = getLogLevels();\n while (levels.hasNext()) {\n colorMenu.add(createSubMenuItem((LogLevel) levels.next()));\n }\n\n return colorMenu;\n }\n\n protected JMenuItem createResetLogLevelColorMenuItem() {\n JMenuItem result = new JMenuItem(\"Reset LogLevel Colors\");\n result.setMnemonic('r');\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n // reset the level colors in the map\n LogLevel.resetLogLevelColorMap();\n\n // refresh the table\n _table.getFilteredLogTableModel().refresh();\n }\n });\n return result;\n }\n\n protected void selectAllLogLevels(boolean selected) {\n Iterator levels = getLogLevels();\n while (levels.hasNext()) {\n getMenuItem((LogLevel) levels.next()).setSelected(selected);\n }\n }\n\n protected JCheckBoxMenuItem getMenuItem(LogLevel level) {\n JCheckBoxMenuItem result = (JCheckBoxMenuItem) (_logLevelMenuItems.get(level));\n if (result == null) {\n result = createMenuItem(level);\n _logLevelMenuItems.put(level, result);\n }\n return result;\n }\n\n protected JMenuItem createSubMenuItem(LogLevel level) {\n final JMenuItem result = new JMenuItem(level.toString());\n final LogLevel logLevel = level;\n result.setMnemonic(level.toString().charAt(0));\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n showLogLevelColorChangeDialog(result, logLevel);\n }\n });\n\n return result;\n\n }\n\n protected void showLogLevelColorChangeDialog(JMenuItem result, LogLevel level) {\n JMenuItem menuItem = result;\n Color newColor = JColorChooser.showDialog(\n _logMonitorFrame,\n \"Choose LogLevel Color\",\n result.getForeground());\n\n if (newColor != null) {\n // set the color for the record\n level.setLogLevelColorMap(level, newColor);\n _table.getFilteredLogTableModel().refresh();\n }\n\n }\n\n protected JCheckBoxMenuItem createMenuItem(LogLevel level) {\n JCheckBoxMenuItem result = new JCheckBoxMenuItem(level.toString());\n result.setSelected(true);\n result.setMnemonic(level.toString().charAt(0));\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n _table.getFilteredLogTableModel().refresh();\n updateStatusLabel();\n }\n });\n return result;\n }\n\n // view menu\n protected JMenu createViewMenu() {\n JMenu result = new JMenu(\"View\");\n result.setMnemonic('v');\n Iterator columns = getLogTableColumns();\n while (columns.hasNext()) {\n result.add(getLogTableColumnMenuItem((LogTableColumn) columns.next()));\n }\n\n result.addSeparator();\n result.add(createAllLogTableColumnsMenuItem());\n result.add(createNoLogTableColumnsMenuItem());\n return result;\n }\n\n protected JCheckBoxMenuItem getLogTableColumnMenuItem(LogTableColumn column) {\n JCheckBoxMenuItem result = (JCheckBoxMenuItem) (_logTableColumnMenuItems.get(column));\n if (result == null) {\n result = createLogTableColumnMenuItem(column);\n _logTableColumnMenuItems.put(column, result);\n }\n return result;\n }\n\n protected JCheckBoxMenuItem createLogTableColumnMenuItem(LogTableColumn column) {\n JCheckBoxMenuItem result = new JCheckBoxMenuItem(column.toString());\n\n result.setSelected(true);\n result.setMnemonic(column.toString().charAt(0));\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n // update list of columns and reset the view\n List selectedColumns = updateView();\n _table.setView(selectedColumns);\n }\n });\n return result;\n }\n\n protected List updateView() {\n ArrayList updatedList = new ArrayList();\n Iterator columnIterator = _columns.iterator();\n while (columnIterator.hasNext()) {\n LogTableColumn column = (LogTableColumn) columnIterator.next();\n JCheckBoxMenuItem result = getLogTableColumnMenuItem(column);\n // check and see if the checkbox is checked\n if (result.isSelected()) {\n updatedList.add(column);\n }\n }\n\n return updatedList;\n }\n\n protected JMenuItem createAllLogTableColumnsMenuItem() {\n JMenuItem result = new JMenuItem(\"Show all Columns\");\n result.setMnemonic('s');\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n selectAllLogTableColumns(true);\n // update list of columns and reset the view\n List selectedColumns = updateView();\n _table.setView(selectedColumns);\n }\n });\n return result;\n }\n\n protected JMenuItem createNoLogTableColumnsMenuItem() {\n JMenuItem result = new JMenuItem(\"Hide all Columns\");\n result.setMnemonic('h');\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n selectAllLogTableColumns(false);\n // update list of columns and reset the view\n List selectedColumns = updateView();\n _table.setView(selectedColumns);\n }\n });\n return result;\n }\n\n protected void selectAllLogTableColumns(boolean selected) {\n Iterator columns = getLogTableColumns();\n while (columns.hasNext()) {\n getLogTableColumnMenuItem((LogTableColumn) columns.next()).setSelected(selected);\n }\n }\n\n protected JMenu createFileMenu() {\n JMenu fileMenu = new JMenu(\"File\");\n fileMenu.setMnemonic('f');\n JMenuItem exitMI;\n fileMenu.add(createOpenMI());\n fileMenu.add(createOpenURLMI());\n fileMenu.addSeparator();\n fileMenu.add(createCloseMI());\n createMRUFileListMI(fileMenu);\n fileMenu.addSeparator();\n fileMenu.add(createExitMI());\n return fileMenu;\n }\n\n /**\n * Menu item added to allow log files to be opened with\n * the LF5 GUI.\n */\n protected JMenuItem createOpenMI() {\n JMenuItem result = new JMenuItem(\"Open...\");\n result.setMnemonic('o');\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n requestOpen();\n }\n });\n return result;\n }\n\n /**\n * Menu item added to allow log files loaded from a URL\n * to be opened by the LF5 GUI.\n */\n protected JMenuItem createOpenURLMI() {\n JMenuItem result = new JMenuItem(\"Open URL...\");\n result.setMnemonic('u');\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n requestOpenURL();\n }\n });\n return result;\n }\n\n protected JMenuItem createCloseMI() {\n JMenuItem result = new JMenuItem(\"Close\");\n result.setMnemonic('c');\n result.setAccelerator(KeyStroke.getKeyStroke(\"control Q\"));\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n requestClose();\n }\n });\n return result;\n }\n\n /**\n * Creates a Most Recently Used file list to be\n * displayed in the File menu\n */\n protected void createMRUFileListMI(JMenu menu) {\n\n String[] files = _mruFileManager.getMRUFileList();\n\n if (files != null) {\n menu.addSeparator();\n for (int i = 0; i < files.length; i++) {\n JMenuItem result = new JMenuItem((i + 1) + \" \" + files[i]);\n result.setMnemonic(i + 1);\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n requestOpenMRU(e);\n }\n });\n menu.add(result);\n }\n }\n }\n\n protected JMenuItem createExitMI() {\n JMenuItem result = new JMenuItem(\"Exit\");\n result.setMnemonic('x');\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n requestExit();\n }\n });\n return result;\n }\n\n protected JMenu createConfigureMenu() {\n JMenu configureMenu = new JMenu(\"Configure\");\n configureMenu.setMnemonic('c');\n configureMenu.add(createConfigureSave());\n configureMenu.add(createConfigureReset());\n configureMenu.add(createConfigureMaxRecords());\n\n return configureMenu;\n }\n\n protected JMenuItem createConfigureSave() {\n JMenuItem result = new JMenuItem(\"Save\");\n result.setMnemonic('s');\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n saveConfiguration();\n }\n });\n\n return result;\n }\n\n protected JMenuItem createConfigureReset() {\n JMenuItem result = new JMenuItem(\"Reset\");\n result.setMnemonic('r');\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n resetConfiguration();\n }\n });\n\n return result;\n }\n\n protected JMenuItem createConfigureMaxRecords() {\n JMenuItem result = new JMenuItem(\"Set Max Number of Records\");\n result.setMnemonic('m');\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n setMaxRecordConfiguration();\n }\n });\n\n return result;\n }\n\n\n protected void saveConfiguration() {\n _configurationManager.save();\n }\n\n protected void resetConfiguration() {\n _configurationManager.reset();\n }\n\n protected void setMaxRecordConfiguration() {\n LogFactor5InputDialog inputDialog = new LogFactor5InputDialog(\n getBaseFrame(), \"Set Max Number of Records\", \"\", 10);\n\n String temp = inputDialog.getText();\n\n if (temp != null) {\n try {\n setMaxNumberOfLogRecords(Integer.parseInt(temp));\n } catch (NumberFormatException e) {\n LogFactor5ErrorDialog error = new LogFactor5ErrorDialog(\n getBaseFrame(),\n \"'\" + temp + \"' is an invalid parameter.\\nPlease try again.\");\n setMaxRecordConfiguration();\n }\n }\n }\n\n\n protected JMenu createHelpMenu() {\n JMenu helpMenu = new JMenu(\"Help\");\n helpMenu.setMnemonic('h');\n helpMenu.add(createHelpProperties());\n return helpMenu;\n }\n\n protected JMenuItem createHelpProperties() {\n final String title = \"LogFactor5 Properties\";\n final JMenuItem result = new JMenuItem(title);\n result.setMnemonic('l');\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n showPropertiesDialog(title);\n }\n });\n return result;\n }\n\n protected void showPropertiesDialog(String title) {\n JOptionPane.showMessageDialog(\n _logMonitorFrame,\n _displayedLogBrokerProperties.toArray(),\n title,\n JOptionPane.PLAIN_MESSAGE\n );\n }\n\n protected JMenu createEditMenu() {\n JMenu editMenu = new JMenu(\"Edit\");\n editMenu.setMnemonic('e');\n editMenu.add(createEditFindMI());\n editMenu.add(createEditFindNextMI());\n editMenu.addSeparator();\n editMenu.add(createEditSortNDCMI());\n editMenu.add(createEditRestoreAllNDCMI());\n return editMenu;\n }\n\n protected JMenuItem createEditFindNextMI() {\n JMenuItem editFindNextMI = new JMenuItem(\"Find Next\");\n editFindNextMI.setMnemonic('n');\n editFindNextMI.setAccelerator(KeyStroke.getKeyStroke(\"F3\"));\n editFindNextMI.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n findSearchText();\n }\n });\n return editFindNextMI;\n }\n\n protected JMenuItem createEditFindMI() {\n JMenuItem editFindMI = new JMenuItem(\"Find\");\n editFindMI.setMnemonic('f');\n editFindMI.setAccelerator(KeyStroke.getKeyStroke(\"control F\"));\n\n editFindMI.addActionListener(\n new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n String inputValue =\n JOptionPane.showInputDialog(\n _logMonitorFrame,\n \"Find text: \",\n \"Search Record Messages\",\n JOptionPane.QUESTION_MESSAGE\n );\n setSearchText(inputValue);\n findSearchText();\n }\n }\n\n );\n return editFindMI;\n }\n\n // Added version 1.2 - Allows users to Sort Log Records by an\n // NDC text filter. A new LogRecordFilter was created to\n // sort the records.\n protected JMenuItem createEditSortNDCMI() {\n JMenuItem editSortNDCMI = new JMenuItem(\"Sort by NDC\");\n editSortNDCMI.setMnemonic('s');\n editSortNDCMI.addActionListener(\n new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n String inputValue =\n JOptionPane.showInputDialog(\n _logMonitorFrame,\n \"Sort by this NDC: \",\n \"Sort Log Records by NDC\",\n JOptionPane.QUESTION_MESSAGE\n );\n setNDCTextFilter(inputValue);\n sortByNDC();\n _table.getFilteredLogTableModel().refresh();\n updateStatusLabel();\n }\n }\n\n );\n return editSortNDCMI;\n }\n\n // Added in version 1.2 - Resets the LogRecordFilter back to default\n // filter.\n protected JMenuItem createEditRestoreAllNDCMI() {\n JMenuItem editRestoreAllNDCMI = new JMenuItem(\"Restore all NDCs\");\n editRestoreAllNDCMI.setMnemonic('r');\n editRestoreAllNDCMI.addActionListener(\n new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n _table.getFilteredLogTableModel().setLogRecordFilter(createLogRecordFilter());\n // reset the text filter\n setNDCTextFilter(\"\");\n _table.getFilteredLogTableModel().refresh();\n updateStatusLabel();\n }\n }\n );\n return editRestoreAllNDCMI;\n }\n\n protected JToolBar createToolBar() {\n JToolBar tb = new JToolBar();\n tb.putClientProperty(\"JToolBar.isRollover\", Boolean.TRUE);\n JComboBox fontCombo = new JComboBox();\n JComboBox fontSizeCombo = new JComboBox();\n _fontSizeCombo = fontSizeCombo;\n\n ClassLoader cl = this.getClass().getClassLoader();\n if(cl == null) {\n cl = ClassLoader.getSystemClassLoader();\n }\n URL newIconURL = cl.getResource(\"org/apache/log4j/lf5/viewer/\" +\n \"images/channelexplorer_new.gif\");\n\n ImageIcon newIcon = null;\n\n if (newIconURL != null) {\n newIcon = new ImageIcon(newIconURL);\n }\n\n JButton newButton = new JButton(\"Clear Log Table\");\n\n if (newIcon != null) {\n newButton.setIcon(newIcon);\n }\n\n newButton.setToolTipText(\"Clear Log Table.\");\n //newButton.setBorder(BorderFactory.createEtchedBorder());\n\n newButton.addActionListener(\n new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n _table.clearLogRecords();\n _categoryExplorerTree.getExplorerModel().resetAllNodeCounts();\n updateStatusLabel();\n clearDetailTextArea();\n LogRecord.resetSequenceNumber();\n }\n }\n );\n\n Toolkit tk = Toolkit.getDefaultToolkit();\n // This will actually grab all the fonts\n\n String[] fonts;\n\n if (_loadSystemFonts) {\n fonts = GraphicsEnvironment.\n getLocalGraphicsEnvironment().getAvailableFontFamilyNames();\n } else {\n fonts = tk.getFontList();\n }\n\n for (int j = 0; j < fonts.length; j++) {\n fontCombo.addItem(fonts[j]);\n }\n\n fontCombo.setSelectedItem(_fontName);\n\n fontCombo.addActionListener(\n\n new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n JComboBox box = (JComboBox) e.getSource();\n String font = (String) box.getSelectedItem();\n _table.setFont(new Font(font, Font.PLAIN, _fontSize));\n _fontName = font;\n }\n }\n );\n\n fontSizeCombo.addItem(\"8\");\n fontSizeCombo.addItem(\"9\");\n fontSizeCombo.addItem(\"10\");\n fontSizeCombo.addItem(\"12\");\n fontSizeCombo.addItem(\"14\");\n fontSizeCombo.addItem(\"16\");\n fontSizeCombo.addItem(\"18\");\n fontSizeCombo.addItem(\"24\");\n\n fontSizeCombo.setSelectedItem(String.valueOf(_fontSize));\n fontSizeCombo.addActionListener(\n new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n JComboBox box = (JComboBox) e.getSource();\n String size = (String) box.getSelectedItem();\n int s = Integer.valueOf(size).intValue();\n\n setFontSizeSilently(s);\n refreshDetailTextArea();\n _fontSize = s;\n }\n }\n );\n\n tb.add(new JLabel(\" Font: \"));\n tb.add(fontCombo);\n tb.add(fontSizeCombo);\n tb.addSeparator();\n tb.addSeparator();\n tb.add(newButton);\n\n newButton.setAlignmentY(0.5f);\n newButton.setAlignmentX(0.5f);\n\n fontCombo.setMaximumSize(fontCombo.getPreferredSize());\n fontSizeCombo.setMaximumSize(\n fontSizeCombo.getPreferredSize());\n\n return (tb);\n }\n\n// protected void setView(String viewString, LogTable table) {\n// if (STANDARD_VIEW.equals(viewString)) {\n// table.setStandardView();\n// } else if (COMPACT_VIEW.equals(viewString)) {\n// table.setCompactView();\n// } else if (DETAILED_VIEW.equals(viewString)) {\n// table.setDetailedView();\n// } else {\n// String message = viewString + \"does not match a supported view.\";\n// throw new IllegalArgumentException(message);\n// }\n// _currentView = viewString;\n// }\n\n protected void setView(String viewString, LogTable table) {\n if (DETAILED_VIEW.equals(viewString)) {\n table.setDetailedView();\n } else {\n String message = viewString + \"does not match a supported view.\";\n throw new IllegalArgumentException(message);\n }\n _currentView = viewString;\n }\n\n protected JComboBox createLogLevelCombo() {\n JComboBox result = new JComboBox();\n Iterator levels = getLogLevels();\n while (levels.hasNext()) {\n result.addItem(levels.next());\n }\n result.setSelectedItem(_leastSevereDisplayedLogLevel);\n\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n JComboBox box = (JComboBox) e.getSource();\n LogLevel level = (LogLevel) box.getSelectedItem();\n setLeastSevereDisplayedLogLevel(level);\n }\n });\n result.setMaximumSize(result.getPreferredSize());\n return result;\n }\n\n protected void setLeastSevereDisplayedLogLevel(LogLevel level) {\n if (level == null || _leastSevereDisplayedLogLevel == level) {\n return; // nothing to do\n }\n _leastSevereDisplayedLogLevel = level;\n _table.getFilteredLogTableModel().refresh();\n updateStatusLabel();\n }\n\n /**\n * Ensures that the Table's ScrollPane Viewport will \"track\" with updates\n * to the Table. When the vertical scroll bar is at its bottom anchor\n * and tracking is enabled then viewport will stay at the bottom most\n * point of the component. The purpose of this feature is to allow\n * a developer to watch the table as messages arrive and not have to\n * scroll after each new message arrives. When the vertical scroll bar\n * is at any other location, then no tracking will happen.\n * @deprecated tracking is now done automatically.\n */\n protected void trackTableScrollPane() {\n // do nothing\n }\n\n protected void centerFrame(JFrame frame) {\n Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();\n Dimension comp = frame.getSize();\n\n frame.setLocation(((screen.width - comp.width) / 2),\n ((screen.height - comp.height) / 2));\n\n }\n\n /**\n * Uses a JFileChooser to select a file to opened with the\n * LF5 GUI.\n */\n protected void requestOpen() {\n JFileChooser chooser;\n\n if (_fileLocation == null) {\n chooser = new JFileChooser();\n } else {\n chooser = new JFileChooser(_fileLocation);\n }\n\n int returnVal = chooser.showOpenDialog(_logMonitorFrame);\n if (returnVal == JFileChooser.APPROVE_OPTION) {\n File f = chooser.getSelectedFile();\n if (loadLogFile(f)) {\n _fileLocation = chooser.getSelectedFile();\n _mruFileManager.set(f);\n updateMRUList();\n }\n }\n }\n\n /**\n * Uses a Dialog box to accept a URL to a file to be opened\n * with the LF5 GUI.\n */\n protected void requestOpenURL() {\n LogFactor5InputDialog inputDialog = new LogFactor5InputDialog(\n getBaseFrame(), \"Open URL\", \"URL:\");\n String temp = inputDialog.getText();\n\n if (temp != null) {\n if (temp.indexOf(\"://\") == -1) {\n temp = \"http://\" + temp;\n }\n\n try {\n URL url = new URL(temp);\n if (loadLogFile(url)) {\n _mruFileManager.set(url);\n updateMRUList();\n }\n } catch (MalformedURLException e) {\n LogFactor5ErrorDialog error = new LogFactor5ErrorDialog(\n getBaseFrame(), \"Error reading URL.\");\n }\n }\n }\n\n /**\n * Removes old file list and creates a new file list\n * with the updated MRU list.\n */\n protected void updateMRUList() {\n JMenu menu = _logMonitorFrame.getJMenuBar().getMenu(0);\n menu.removeAll();\n menu.add(createOpenMI());\n menu.add(createOpenURLMI());\n menu.addSeparator();\n menu.add(createCloseMI());\n createMRUFileListMI(menu);\n menu.addSeparator();\n menu.add(createExitMI());\n }\n\n protected void requestClose() {\n setCallSystemExitOnClose(false);\n closeAfterConfirm();\n }\n\n /**\n * Opens a file in the MRU list.\n */\n protected void requestOpenMRU(ActionEvent e) {\n String file = e.getActionCommand();\n StringTokenizer st = new StringTokenizer(file);\n String num = st.nextToken().trim();\n file = st.nextToken(\"\\n\");\n\n try {\n int index = Integer.parseInt(num) - 1;\n\n InputStream in = _mruFileManager.getInputStream(index);\n LogFileParser lfp = new LogFileParser(in);\n lfp.parse(this);\n\n _mruFileManager.moveToTop(index);\n updateMRUList();\n\n } catch (Exception me) {\n LogFactor5ErrorDialog error = new LogFactor5ErrorDialog(\n getBaseFrame(), \"Unable to load file \" + file);\n }\n\n }\n\n protected void requestExit() {\n _mruFileManager.save();\n setCallSystemExitOnClose(true);\n closeAfterConfirm();\n }\n\n protected void closeAfterConfirm() {\n StringBuffer message = new StringBuffer();\n\n if (_callSystemExitOnClose == false) {\n message.append(\"Are you sure you want to close the logging \");\n message.append(\"console?\\n\");\n message.append(\"(Note: This will not shut down the Virtual Machine,\\n\");\n message.append(\"or the Swing event thread.)\");\n } else {\n message.append(\"Are you sure you want to exit?\\n\");\n message.append(\"This will shut down the Virtual Machine.\\n\");\n }\n\n String title =\n \"Are you sure you want to dispose of the Logging Console?\";\n\n if (_callSystemExitOnClose == true) {\n title = \"Are you sure you want to exit?\";\n }\n int value = JOptionPane.showConfirmDialog(\n _logMonitorFrame,\n message.toString(),\n title,\n JOptionPane.OK_CANCEL_OPTION,\n JOptionPane.QUESTION_MESSAGE,\n null\n );\n\n if (value == JOptionPane.OK_OPTION) {\n dispose();\n }\n }\n\n protected Iterator getLogLevels() {\n return _levels.iterator();\n }\n\n protected Iterator getLogTableColumns() {\n return _columns.iterator();\n }\n\n /**\n * Loads and parses a log file.\n */\n protected boolean loadLogFile(File file) {\n boolean ok = false;\n try {\n LogFileParser lfp = new LogFileParser(file);\n lfp.parse(this);\n ok = true;\n } catch (IOException e) {\n LogFactor5ErrorDialog error = new LogFactor5ErrorDialog(\n getBaseFrame(), \"Error reading \" + file.getName());\n }\n\n return ok;\n }\n\n /**\n * Loads a parses a log file running on a server.\n */\n protected boolean loadLogFile(URL url) {\n boolean ok = false;\n try {\n LogFileParser lfp = new LogFileParser(url.openStream());\n lfp.parse(this);\n ok = true;\n } catch (IOException e) {\n LogFactor5ErrorDialog error = new LogFactor5ErrorDialog(\n getBaseFrame(), \"Error reading URL:\" + url.getFile());\n }\n return ok;\n }\n //--------------------------------------------------------------------------\n // Private Methods:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Nested Top-Level Classes or Interfaces:\n //--------------------------------------------------------------------------\n\n class LogBrokerMonitorWindowAdaptor extends WindowAdapter {\n protected LogBrokerMonitor _monitor;\n\n public LogBrokerMonitorWindowAdaptor(LogBrokerMonitor monitor) {\n _monitor = monitor;\n }\n\n public void windowClosing(WindowEvent ev) {\n _monitor.requestClose();\n }\n }\n}\n\n\n", "file_name": "LogBrokerMonitor.java", "human_label": "Add a log record message to be displayed in the LogTable, with the SwingUtilities.", "level": "project_runnable", "lineno": "246", "name": "addMessage", "oracle_context": "{ \"apis\" : \"[invokeLater, addLogRecord, getExplorerModel, getFilteredLogTableModel, updateStatusLabel, run]\", \"classes\" : \"[]\", \"vars\" : \"[_isDisposed, _categoryExplorerTree, _table]\" }", "package": "org.apache.log4j.lf5.viewer", "project": "logging-log4j1-main" }, { "_id": "636767641a6d9265ec01817d", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.util.*;\\nimport java.util.*;\\nint sizeA;\\nint sizeB;\\nSet partitionA;\\nSet partitionB;\\nCompleteBipartiteGraphGenerator(int partitionA,int partitionB);\\nCompleteBipartiteGraphGenerator(Set partitionA,Set partitionB);\\n\", \"repo_level\" : \"\" }", "class_name": "CompleteBipartiteGraphGenerator", "code": "@Override public void generateGraph(Graph target,Map resultMap){\n for (int i=0; i < sizeA; i++) {\n partitionA.add(target.addVertex());\n }\n for (int i=0; i < sizeB; i++) {\n partitionB.add(target.addVertex());\n }\n for ( V u : partitionA) {\n for ( V v : partitionB) {\n target.addEdge(u,v);\n }\n }\n}\n", "docstring": "/** \n * Construct a complete bipartite graph\n */\n", "end_lineno": "100", "file_content": "/*\n * (C) Copyright 2008-2021, by Andrew Newell and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.generate;\n\nimport org.jgrapht.*;\nimport org.jgrapht.util.*;\n\nimport java.util.*;\n\n/**\n * Generates a complete bipartite\n * graph of any size. This is a graph with two partitions; two vertices will contain an edge if\n * and only if they belong to different partitions.\n *\n * @param the graph vertex type\n * @param the graph edge type\n *\n * @author Andrew Newell\n */\npublic class CompleteBipartiteGraphGenerator\n implements\n GraphGenerator\n{\n private final int sizeA, sizeB;\n private final Set partitionA, partitionB;\n\n /**\n * Creates a new CompleteBipartiteGraphGenerator object.\n *\n * @param partitionA number of vertices in the first partition\n * @param partitionB number of vertices in the second partition\n */\n public CompleteBipartiteGraphGenerator(int partitionA, int partitionB)\n {\n if (partitionA < 0 || partitionB < 0) {\n throw new IllegalArgumentException(\"partition sizes must be non-negative\");\n }\n this.sizeA = partitionA;\n this.sizeB = partitionB;\n this.partitionA = CollectionUtil.newLinkedHashSetWithExpectedSize(sizeA);\n this.partitionB = CollectionUtil.newLinkedHashSetWithExpectedSize(sizeB);\n }\n\n /**\n * Creates a new CompleteBipartiteGraphGenerator object. A complete bipartite graph is generated\n * on the vertices provided between the vertices provided in the two partitions. Note that\n * all vertices in both {@code partitionA} and {@code partitionB} must be present in the\n * graph or an exception will be thrown during the invocation of\n * {@link #generateGraph(Graph, Map)}\n *\n * @param partitionA first partition\n * @param partitionB second partition\n */\n public CompleteBipartiteGraphGenerator(Set partitionA, Set partitionB)\n {\n if (partitionA.isEmpty() || partitionB.isEmpty()) {\n throw new IllegalArgumentException(\"partitions must be non-empty\");\n }\n this.sizeA = 0;\n this.sizeB = 0;\n this.partitionA = partitionA;\n this.partitionB = partitionB;\n }\n\n /**\n * Construct a complete bipartite graph\n */\n @Override\n public void generateGraph(Graph target, Map resultMap)\n {\n // Create vertices in each of the partitions\n for (int i = 0; i < sizeA; i++) {\n partitionA.add(target.addVertex());\n }\n for (int i = 0; i < sizeB; i++) {\n partitionB.add(target.addVertex());\n }\n\n // Add an edge for each pair of vertices in different partitions\n for (V u : partitionA) {\n for (V v : partitionB) {\n target.addEdge(u, v);\n }\n }\n }\n}\n", "file_name": "CompleteBipartiteGraphGenerator.java", "human_label": "Construct a complete bipartite graph from partitions A and B.", "level": "class_runnable", "lineno": "80", "name": "generateGraph", "oracle_context": "{ \"apis\" : \"[add, addVertex, addEdge]\", \"classes\" : \"[]\", \"vars\" : \"[sizeA, partitionA, sizeB, partitionB]\" }", "package": "org.jgrapht.generate", "project": "jgrapht-master" }, { "_id": "636766ff1a6d9265ec017851", "all_context": "{ \"class_level\" : \"import net.hasor.web.upload.util.Streams;\\nimport java.io.*;\\nimport static java.lang.String.format;\\nimport static net.hasor.web.upload.FileUploadException.UploadErrorCodes.*;\\nbyte CR;\\nbyte LF;\\nbyte DASH;\\nint HEADER_PART_SIZE_MAX;\\nint DEFAULT_BUFSIZE;\\nbyte[] HEADER_SEPARATOR;\\nbyte[] FIELD_SEPARATOR;\\nbyte[] STREAM_TERMINATOR;\\nbyte[] BOUNDARY_PREFIX;\\nInputStream input;\\nint boundaryLength;\\nint keepRegion;\\nbyte[] boundary;\\nint bufSize;\\nbyte[] buffer;\\nint head;\\nint tail;\\nString headerEncoding;\\nlong total;\\nint pad;\\nint pos;\\nboolean closed;\\nint BYTE_POSITIVE_OFFSET;\\nMultipartStream(InputStream input,byte[] boundary,int bufSize);\\nMultipartStream(InputStream input,byte[] boundary);\\ngetHeaderEncoding();\\nsetHeaderEncoding(String encoding);\\nreadBoundary();\\nsetBoundary(byte[] boundary);\\nreadHeaders();\\nreadBodyData(OutputStream output);\\nnewInputStream();\\ndiscardBodyData();\\nskipPreamble();\\narrayequals(byte[] a,byte[] b,int count);\\nfindByte(byte value,int pos);\\nfindSeparator();\\nItemInputStream();\\ngetBytesRead();\\navailable();\\nread();\\nread(byte[] b,int off,int len);\\nclose();\\nclose(boolean pCloseUnderlying);\\nskip(long bytes);\\nmakeAvailable();\\nisClosed();\\nreadByte();\\n\", \"repo_level\" : \"public interface Streams {static long copy(InputStream inputStream,OutputStream outputStream,boolean closeOutputStream);\\nstatic long copy(InputStream inputStream,OutputStream outputStream,boolean closeOutputStream,byte[] buffer);\\nstatic String asString(InputStream inputStream);\\nstatic String asString(InputStream inputStream,String encoding);\\nstatic String checkFileName(String fileName);\\n }\\n\" }", "class_name": "MultipartStream", "code": "protected int findByte(byte value,int pos){\n for (int i=pos; i < tail; i++) {\n if (buffer[i] == value) {\n return i;\n }\n }\n return -1;\n}\n", "docstring": "/** \n * Searches for a byte of specified value in the buffer, starting at the specified position.\n * @param value The value to find.\n * @param pos The starting position for searching.\n * @return The position of byte found, counting from beginning of thebuffer, or -1 if not found.\n */\n", "end_lineno": "396", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.web.upload;\nimport net.hasor.web.upload.util.Streams;\n\nimport java.io.*;\n\nimport static java.lang.String.format;\nimport static net.hasor.web.upload.FileUploadException.UploadErrorCodes.*;\n\n/**\n *

Low level API for processing file uploads.\n *\n *

This class can be used to process data streams conforming to MIME\n * 'multipart' format as defined in\n * RFC 1867. Arbitrarily\n * large amounts of data in the stream can be processed under constant\n * memory usage.\n *\n *

The format of the stream is defined in the following way:
\n *\n * \n * multipart-body := preamble 1*encapsulation close-delimiter epilogue
\n * encapsulation := delimiter body CRLF
\n * delimiter := \"--\" boundary CRLF
\n * close-delimiter := \"--\" boundary \"--\"
\n * preamble := <ignore>
\n * epilogue := <ignore>
\n * body := header-part CRLF body-part
\n * header-part := 1*header CRLF
\n * header := header-name \":\" header-value
\n * header-name := <printable ascii characters except \":\">
\n * header-value := <any ascii characters except CR & LF>
\n * body-data := <arbitrary data>
\n *
\n *\n *

Note that body-data can contain another mulipart entity. There\n * is limited support for single pass processing of such nested\n * streams. The nested stream is required to have a\n * boundary token of the same length as the parent stream (see {@link\n * #setBoundary(byte[])}).\n *\n *

Here is an example of usage of this class.
\n *\n *

\n *   try {\n *     MultipartStream multipartStream = new MultipartStream(input, boundary);\n *     boolean nextPart = multipartStream.skipPreamble();\n *     OutputStream output;\n *     while(nextPart) {\n *       String header = multipartStream.readHeaders();\n *       // process headers\n *       // create some output stream\n *       multipartStream.readBodyData(output);\n *       nextPart = multipartStream.readBoundary();\n *     }\n *   } catch(MultipartStream.MalformedStreamException e) {\n *     // the stream failed to follow required syntax\n *   } catch(IOException e) {\n *     // a read or write error occurred\n *   }\n * 
\n *\n * @version $Id: MultipartStream.java 1745065 2016-05-22 14:56:37Z britter $\n */\nclass MultipartStream {\n // ----------------------------------------------------- Manifest constants\n /** The Carriage Return ASCII character value. */\n public static final byte CR = 0x0D;\n /** The Line Feed ASCII character value. */\n public static final byte LF = 0x0A;\n /** The dash (-) ASCII character value. */\n public static final byte DASH = 0x2D;\n /** The maximum length of header-part that will be processed (10 kilobytes = 10240 bytes.). */\n public static final int HEADER_PART_SIZE_MAX = 10240;\n /** The default length of the buffer used for processing a request. */\n protected static final int DEFAULT_BUFSIZE = 4096;\n /** A byte sequence that marks the end of header-part (CRLFCRLF). */\n protected static final byte[] HEADER_SEPARATOR = { CR, LF, CR, LF };\n /** A byte sequence that that follows a delimiter that will be followed by an encapsulation (CRLF). */\n protected static final byte[] FIELD_SEPARATOR = { CR, LF };\n /** A byte sequence that that follows a delimiter of the last encapsulation in the stream (--). */\n protected static final byte[] STREAM_TERMINATOR = { DASH, DASH };\n /** A byte sequence that precedes a boundary (CRLF--). */\n protected static final byte[] BOUNDARY_PREFIX = { CR, LF, DASH, DASH };\n // ----------------------------------------------------------- Data members\n /** The input stream from which data is read. */\n private final InputStream input;\n /** The length of the boundary token plus the leading CRLF--. */\n private int boundaryLength;\n /** The amount of data, in bytes, that must be kept in the buffer in order to detect delimiters reliably. */\n private int keepRegion;\n /** The byte sequence that partitions the stream. */\n private byte[] boundary;\n /** The length of the buffer used for processing the request. */\n private final int bufSize;\n /** The buffer used for processing the request. */\n private final byte[] buffer;\n /** The index of first valid character in the buffer.
0 <= head < bufSize */\n private int head;\n /** The index of last valid character in the buffer + 1.
0 <= tail <= bufSize */\n private int tail;\n /** The content encoding to use when reading headers. */\n private String headerEncoding;\n // ----------------------------------------------------------- Constructors\n\n /**\n *

Constructs a MultipartStream with a custom size buffer.\n *\n *

Note that the buffer must be at least big enough to contain the\n * boundary string, plus 4 characters for CR/LF and double dash, plus at\n * least one byte of data. Too small a buffer size setting will degrade\n * performance.\n *\n * @param input The InputStream to serve as a data source.\n * @param boundary The token used for dividing the stream into\n * encapsulations.\n * @param bufSize The size of the buffer to be used, in bytes.\n * @throws IllegalArgumentException If the buffer size is too small\n * @since 1.3.1\n */\n public MultipartStream(InputStream input, byte[] boundary, int bufSize) {\n if (boundary == null) {\n throw new IllegalArgumentException(\"boundary may not be null\");\n }\n // We prepend CR/LF to the boundary to chop trailing CR/LF from body-data tokens.\n this.boundaryLength = boundary.length + BOUNDARY_PREFIX.length;\n if (bufSize < this.boundaryLength + 1) {\n throw new IllegalArgumentException(\"The buffer size specified for the MultipartStream is too small\");\n }\n this.input = input;\n this.bufSize = Math.max(bufSize, boundaryLength * 2);\n this.buffer = new byte[this.bufSize];\n this.boundary = new byte[this.boundaryLength];\n this.keepRegion = this.boundary.length;\n System.arraycopy(BOUNDARY_PREFIX, 0, this.boundary, 0, BOUNDARY_PREFIX.length);\n System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length);\n head = 0;\n tail = 0;\n }\n\n /**\n *

Constructs a MultipartStream with a default size buffer.\n * @param input The InputStream to serve as a data source.\n * @param boundary The token used for dividing the stream into encapsulations.\n * @see #MultipartStream(InputStream, byte[], int)\n */\n MultipartStream(InputStream input, byte[] boundary) {\n this(input, boundary, DEFAULT_BUFSIZE);\n }\n // --------------------------------------------------------- Public methods\n\n /**\n * Retrieves the character encoding used when reading the headers of an\n * individual part. When not specified, or null, the platform default encoding is used.\n * @return The encoding used to read part headers.\n */\n public String getHeaderEncoding() {\n return headerEncoding;\n }\n\n /**\n * Specifies the character encoding to be used when reading the headers of\n * individual parts. When not specified, or null, the platform\n * default encoding is used.\n * @param encoding The encoding used to read part headers.\n */\n public void setHeaderEncoding(String encoding) {\n headerEncoding = encoding;\n }\n\n /**\n * Reads a byte from the buffer, and refills it as necessary.\n * @return The next byte from the input stream.\n * @throws IOException if there is no more data available.\n */\n public byte readByte() throws IOException {\n // Buffer depleted ?\n if (head == tail) {\n head = 0;\n // Refill.\n tail = input.read(buffer, head, bufSize);\n if (tail == -1) {\n // No more data available.\n throw new IOException(\"No more data is available\");\n }\n }\n return buffer[head++];\n }\n\n /**\n * Skips a boundary token, and checks whether more\n * encapsulations are contained in the stream.\n * @return true if there are more encapsulations in this stream; false otherwise.\n * @throws FileUploadException if the stream ends unexpectedly or fails to follow required syntax.\n */\n public boolean readBoundary() throws IOException {\n byte[] marker = new byte[2];\n boolean nextChunk = false;\n head += boundaryLength;\n marker[0] = readByte();\n if (marker[0] == LF) {\n // Work around IE5 Mac bug with input type=image.\n // Because the boundary delimiter, not including the trailing CRLF, \n // must not appear within any file (RFC 2046, section 5.1.1),\n // we know the missing CR is due to a buggy browser rather than a file \n // containing something similar to a boundary.\n return true;\n }\n marker[1] = readByte();\n if (arrayequals(marker, STREAM_TERMINATOR, 2)) {\n nextChunk = false;\n } else if (arrayequals(marker, FIELD_SEPARATOR, 2)) {\n nextChunk = true;\n } else {\n throw new FileUploadException(MalformedStreamException, \"Unexpected characters follow a boundary\");\n }\n return nextChunk;\n }\n\n /**\n *

Changes the boundary token used for partitioning the stream.\n *

This method allows single pass processing of nested multipart streams.\n *

The boundary token of the nested stream is required to be of the same length as the boundary token in parent stream.\n *

Restoring the parent stream boundary token after processing of a nested stream is left to the application.\n * @param boundary The boundary to be used for parsing of the nested stream.\n * @throws FileUploadException if the boundary has a different length than the one being currently parsed.\n */\n public void setBoundary(byte[] boundary) throws FileUploadException {\n if (boundary.length != boundaryLength - BOUNDARY_PREFIX.length) {\n throw new FileUploadException(IllegalBoundaryException, \"The length of a boundary token can not be changed\");\n }\n System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length);\n }\n\n /**\n *

Reads the header-part of the current\n * encapsulation.\n *

Headers are returned verbatim to the input stream, including the\n * trailing CRLF marker. Parsing is left to the application.\n *

TODO allow limiting maximum header size to protect against abuse.\n *\n * @return The header-part of the current encapsulation.\n * @throws FileUploadException if the stream ends unexpectedly.\n */\n public String readHeaders() throws IOException {\n int i = 0;\n byte b;\n // to support multi-byte characters\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n int size = 0;\n while (i < HEADER_SEPARATOR.length) {\n try {\n b = readByte();\n } catch (IOException e) {\n throw e;\n }\n if (++size > HEADER_PART_SIZE_MAX) {\n String logMEssage = format(\"Header section has more than %s bytes (maybe it is not properly terminated)\", Integer.valueOf(HEADER_PART_SIZE_MAX));\n throw new FileUploadException(MalformedStreamException, logMEssage);\n }\n if (b == HEADER_SEPARATOR[i]) {\n i++;\n } else {\n i = 0;\n }\n baos.write(b);\n }\n String headers = null;\n if (headerEncoding != null) {\n try {\n headers = baos.toString(headerEncoding);\n } catch (UnsupportedEncodingException e) {\n // Fall back to platform default if specified encoding is not supported.\n headers = baos.toString();\n }\n } else {\n headers = baos.toString();\n }\n return headers;\n }\n\n /**\n *

Reads body-data from the current encapsulation and writes its contents into the output Stream.\n *

Arbitrary large amounts of data can be processed by this method using a constant size buffer. \n * @param output The Stream to write data into. May be null, in which case this method is equivalent to {@link #discardBodyData()}.\n * @return the amount of data written.\n * @throws FileUploadException if the stream ends unexpectedly.\n * @throws IOException if an i/o error occurs.\n */\n public int readBodyData(OutputStream output) throws IOException {\n final InputStream istream = newInputStream();\n return (int) Streams.copy(istream, output, false);\n }\n\n /**\n * Creates a new {@link ItemInputStream}.\n * @return A new instance of {@link ItemInputStream}.\n */\n ItemInputStream newInputStream() {\n return new ItemInputStream();\n }\n\n /**\n *

Reads body-data from the current\n * encapsulation and discards it.\n *\n *

Use this method to skip encapsulations you don't need or don't understand.\n *\n * @return The amount of data discarded.\n * @throws FileUploadException if the stream ends unexpectedly.\n * @throws IOException if an i/o error occurs.\n */\n public int discardBodyData() throws IOException {\n return readBodyData(null);\n }\n\n /**\n * Finds the beginning of the first encapsulation.\n * @return true if an encapsulation was found in the stream.\n *\n * @throws IOException if an i/o error occurs.\n */\n public boolean skipPreamble() throws IOException {\n // First delimiter may be not preceeded with a CRLF.\n System.arraycopy(boundary, 2, boundary, 0, boundary.length - 2);\n boundaryLength = boundary.length - 2;\n try {\n // Discard all data up to the delimiter.\n discardBodyData();\n // Read boundary - if succeeded, the stream contains an encapsulation.\n return readBoundary();\n } catch (FileUploadException e) {\n if (e.getErrorCode() == MalformedStreamException) {\n return false;\n }\n throw e;\n } finally {\n // Restore delimiter.\n System.arraycopy(boundary, 0, boundary, 2, boundary.length - 2);\n boundaryLength = boundary.length;\n boundary[0] = CR;\n boundary[1] = LF;\n }\n }\n\n /**\n * Compares count first bytes in the arrays a and b.\n * @param a The first array to compare.\n * @param b The second array to compare.\n * @param count How many bytes should be compared.\n *\n * @return true if count first bytes in arrays\n * a and b are equal.\n */\n public static boolean arrayequals(byte[] a, byte[] b, int count) {\n for (int i = 0; i < count; i++) {\n if (a[i] != b[i]) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Searches for a byte of specified value in the buffer,\n * starting at the specified position.\n *\n * @param value The value to find.\n * @param pos The starting position for searching.\n *\n * @return The position of byte found, counting from beginning of the\n * buffer, or -1 if not found.\n */\n protected int findByte(byte value, int pos) {\n for (int i = pos; i < tail; i++) {\n if (buffer[i] == value) {\n return i;\n }\n }\n return -1;\n }\n\n /**\n * Searches for the boundary in the buffer\n * region delimited by head and tail.\n *\n * @return The position of the boundary found, counting from the\n * beginning of the buffer, or -1 if not found.\n */\n protected int findSeparator() {\n int first;\n int match = 0;\n int maxpos = tail - boundaryLength;\n for (first = head; first <= maxpos && match != boundaryLength; first++) {\n first = findByte(boundary[0], first);\n if (first == -1 || first > maxpos) {\n return -1;\n }\n for (match = 1; match < boundaryLength; match++) {\n if (buffer[first + match] != boundary[match]) {\n break;\n }\n }\n }\n if (match == boundaryLength) {\n return first - 1;\n }\n return -1;\n }\n\n /** An {@link InputStream} for reading an items contents. */\n public class ItemInputStream extends InputStream implements net.hasor.web.upload.util.Closeable {\n /** The number of bytes, which have been read so far. */\n private long total;\n /** The number of bytes, which must be hold, because they might be a part of the boundary. */\n private int pad;\n /** The current offset in the buffer. */\n private int pos;\n /** Whether the stream is already closed. */\n private boolean closed;\n\n /** Creates a new instance. */\n ItemInputStream() {\n findSeparator();\n }\n\n /** Called for finding the separator. */\n private void findSeparator() {\n pos = MultipartStream.this.findSeparator();\n if (pos == -1) {\n if (tail - head > keepRegion) {\n pad = keepRegion;\n } else {\n pad = tail - head;\n }\n }\n }\n\n /** Returns the number of bytes, which have been read by the stream.\n * @return Number of bytes, which have been read so far.\n */\n public long getBytesRead() {\n return total;\n }\n\n /**\n * Returns the number of bytes, which are currently available, without blocking.\n * @return Number of bytes in the buffer.\n */\n @Override\n public int available() {\n if (pos == -1) {\n return tail - head - pad;\n }\n return pos - head;\n }\n\n /** Offset when converting negative bytes to integers. */\n private static final int BYTE_POSITIVE_OFFSET = 256;\n\n /**\n * Returns the next byte in the stream.\n * @return The next byte in the stream, as a non-negative integer, or -1 for EOF.\n * @throws IOException An I/O error occurred.\n */\n @Override\n public int read() throws IOException {\n if (closed) {\n throw new FileUploadException(ItemSkippedException);\n }\n if (available() == 0 && makeAvailable() == 0) {\n return -1;\n }\n ++total;\n int b = buffer[head++];\n if (b >= 0) {\n return b;\n }\n return b + BYTE_POSITIVE_OFFSET;\n }\n\n /**\n * Reads bytes into the given buffer.\n * @param b The destination buffer, where to write to.\n * @param off Offset of the first byte in the buffer.\n * @param len Maximum number of bytes to read.\n * @return Number of bytes, which have been actually read, or -1 for EOF.\n * @throws IOException An I/O error occurred.\n */\n @Override\n public int read(byte[] b, int off, int len) throws IOException {\n if (closed) {\n throw new FileUploadException(ItemSkippedException);\n }\n if (len == 0) {\n return 0;\n }\n int res = available();\n if (res == 0) {\n res = makeAvailable();\n if (res == 0) {\n return -1;\n }\n }\n res = Math.min(res, len);\n System.arraycopy(buffer, head, b, off, res);\n head += res;\n total += res;\n return res;\n }\n\n /**\n * Closes the input stream.\n * @throws IOException An I/O error occurred.\n */\n @Override\n public void close() throws IOException {\n close(false);\n }\n\n /**\n * Closes the input stream.\n * @param pCloseUnderlying Whether to close the underlying stream (hard close)\n * @throws IOException An I/O error occurred.\n */\n public void close(boolean pCloseUnderlying) throws IOException {\n if (closed) {\n return;\n }\n if (pCloseUnderlying) {\n closed = true;\n input.close();\n } else {\n for (; ; ) {\n int av = available();\n if (av == 0) {\n av = makeAvailable();\n if (av == 0) {\n break;\n }\n }\n skip(av);\n }\n }\n closed = true;\n }\n\n /**\n * Skips the given number of bytes.\n * @param bytes Number of bytes to skip.\n * @return The number of bytes, which have actually been skipped.\n * @throws IOException An I/O error occurred.\n */\n @Override\n public long skip(long bytes) throws IOException {\n if (closed) {\n throw new FileUploadException(ItemSkippedException);\n }\n int av = available();\n if (av == 0) {\n av = makeAvailable();\n if (av == 0) {\n return 0;\n }\n }\n long res = Math.min(av, bytes);\n head += res;\n return res;\n }\n\n /**\n * Attempts to read more data.\n * @return Number of available bytes\n * @throws IOException An I/O error occurred.\n */\n private int makeAvailable() throws IOException {\n if (pos != -1) {\n return 0;\n }\n // Move the data to the beginning of the buffer.\n total += tail - head - pad;\n System.arraycopy(buffer, tail - pad, buffer, 0, pad);\n // Refill buffer with new data.\n head = 0;\n tail = pad;\n for (; ; ) {\n int bytesRead = input.read(buffer, tail, bufSize - tail);\n if (bytesRead == -1) {\n // The last pad amount is left in the buffer. Boundary can't be in there so signal an error condition.\n final String msg = \"Stream ended unexpectedly\";\n throw new FileUploadException(MalformedStreamException, msg);\n }\n tail += bytesRead;\n findSeparator();\n int av = available();\n if (av > 0 || pos != -1) {\n return av;\n }\n }\n }\n\n /**\n * Returns, whether the stream is closed.\n * @return True, if the stream is closed, otherwise false.\n */\n public boolean isClosed() {\n return closed;\n }\n }\n}", "file_name": "MultipartStream.java", "human_label": "Searche for a byte of the specified value in the buffer, starting at the specified position.", "level": "class_runnable", "lineno": "379", "name": "findByte", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[tail, buffer]\" }", "package": "net.hasor.web.upload", "project": "hasor-master" }, { "_id": "636767a41a6d9265ec018582", "all_context": "{ \"class_level\" : \"import java.io.DataInput;\\nimport java.io.DataOutput;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport java.io.OutputStream;\\nimport java.util.ArrayList;\\nimport java.util.List;\\nProtobufIOUtil();\\nnewPipe(byte[] data,int offset,int len);\\nbegin(Pipe.Schema pipeSchema);\\nend(Pipe.Schema pipeSchema,Input input,boolean cleanupOnly);\\nnewPipe(InputStream in);\\nmergeFrom(byte[] data,T message,Schema schema);\\nmergeFrom(byte[] data,int offset,int length,T message,Schema schema);\\nmergeFrom(InputStream in,T message,Schema schema);\\nmergeFrom(InputStream in,T message,Schema schema,LinkedBuffer buffer);\\nmergeDelimitedFrom(InputStream in,T message,Schema schema);\\nmergeDelimitedFrom(InputStream in,T message,Schema schema,LinkedBuffer buffer);\\nmergeDelimitedFrom(DataInput in,T message,Schema schema);\\ntoByteArray(T message,Schema schema,LinkedBuffer buffer);\\nwriteTo(LinkedBuffer buffer,T message,Schema schema);\\nwriteTo(OutputStream out,T message,Schema schema,LinkedBuffer buffer);\\nwriteDelimitedTo(OutputStream out,T message,Schema schema,LinkedBuffer buffer);\\nwriteDelimitedTo(DataOutput out,T message,Schema schema);\\nwriteListTo(OutputStream out,List messages,Schema schema,LinkedBuffer buffer);\\nparseListFrom(InputStream in,Schema schema);\\noptMergeDelimitedFrom(InputStream in,T message,Schema schema,LinkedBuffer buffer);\\noptMergeDelimitedFrom(InputStream in,T message,Schema schema,boolean drainRemainingBytesIfTooLarge,LinkedBuffer buffer);\\noptWriteDelimitedTo(OutputStream out,T message,Schema schema,LinkedBuffer buffer);\\nnewPipe(byte[] data);\\n\", \"repo_level\" : \"\" }", "class_name": "ProtobufIOUtil", "code": "public static int writeDelimitedTo(OutputStream out,T message,Schema schema,LinkedBuffer buffer) throws IOException {\n if (buffer.start != buffer.offset) throw new IllegalArgumentException(\"Buffer previously used and had not been reset.\");\n final ProtobufOutput output=new ProtobufOutput(buffer);\n schema.writeTo(output,message);\n final int size=output.getSize();\n ProtobufOutput.writeRawVarInt32Bytes(out,size);\n final int msgSize=LinkedBuffer.writeTo(out,buffer);\n assert size == msgSize;\n return size;\n}\n", "docstring": "/** \n * Serializes the {@code message}, prefixed with its length, into an {@link OutputStream}.\n * @return the size of the message\n */\n", "end_lineno": "256", "file_content": "//========================================================================\r\n//Copyright 2007-2010 David Yu dyuproject@gmail.com\r\n//------------------------------------------------------------------------\r\n//Licensed under the Apache License, Version 2.0 (the \"License\");\r\n//you may not use this file except in compliance with the License.\r\n//You may obtain a copy of the License at \r\n//http://www.apache.org/licenses/LICENSE-2.0\r\n//Unless required by applicable law or agreed to in writing, software\r\n//distributed under the License is distributed on an \"AS IS\" BASIS,\r\n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n//See the License for the specific language governing permissions and\r\n//limitations under the License.\r\n//========================================================================\r\n\r\npackage io.protostuff;\r\n\r\nimport java.io.DataInput;\r\nimport java.io.DataOutput;\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.io.OutputStream;\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\n/**\r\n * Protobuf ser/deser util for messages/objects.\r\n * \r\n * @author David Yu\r\n * @created Oct 5, 2010\r\n */\r\npublic final class ProtobufIOUtil\r\n{\r\n\r\n private ProtobufIOUtil()\r\n {\r\n }\r\n\r\n /**\r\n * Creates a protobuf pipe from a byte array.\r\n */\r\n public static Pipe newPipe(byte[] data)\r\n {\r\n return newPipe(data, 0, data.length);\r\n }\r\n\r\n /**\r\n * Creates a protobuf pipe from a byte array.\r\n */\r\n public static Pipe newPipe(byte[] data, int offset, int len)\r\n {\r\n final ByteArrayInput byteArrayInput = new ByteArrayInput(data, offset, len, false);\r\n return new Pipe()\r\n {\r\n @Override\r\n protected Input begin(Pipe.Schema pipeSchema) throws IOException\r\n {\r\n return byteArrayInput;\r\n }\r\n\r\n @Override\r\n protected void end(Pipe.Schema pipeSchema, Input input,\r\n boolean cleanupOnly) throws IOException\r\n {\r\n if (cleanupOnly)\r\n return;\r\n\r\n assert input == byteArrayInput;\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * Creates a protobuf pipe from an {@link InputStream}.\r\n */\r\n public static Pipe newPipe(final InputStream in)\r\n {\r\n final CodedInput codedInput = new CodedInput(in, false);\r\n return new Pipe()\r\n {\r\n @Override\r\n protected Input begin(Pipe.Schema pipeSchema) throws IOException\r\n {\r\n return codedInput;\r\n }\r\n\r\n @Override\r\n protected void end(Pipe.Schema pipeSchema, Input input,\r\n boolean cleanupOnly) throws IOException\r\n {\r\n if (cleanupOnly)\r\n return;\r\n\r\n assert input == codedInput;\r\n }\r\n };\r\n }\r\n\r\n /**\r\n * Merges the {@code message} with the byte array using the given {@code schema}.\r\n */\r\n public static void mergeFrom(byte[] data, T message, Schema schema)\r\n {\r\n IOUtil.mergeFrom(data, 0, data.length, message, schema, false);\r\n }\r\n\r\n /**\r\n * Merges the {@code message} with the byte array using the given {@code schema}.\r\n */\r\n public static void mergeFrom(byte[] data, int offset, int length, T message,\r\n Schema schema)\r\n {\r\n IOUtil.mergeFrom(data, offset, length, message, schema, false);\r\n }\r\n\r\n /**\r\n * Merges the {@code message} from the {@link InputStream} using the given {@code schema}.\r\n */\r\n public static void mergeFrom(InputStream in, T message, Schema schema)\r\n throws IOException\r\n {\r\n IOUtil.mergeFrom(in, message, schema, false);\r\n }\r\n\r\n /**\r\n * Merges the {@code message} from the {@link InputStream} using the given {@code schema}.\r\n *

\r\n * The {@code buffer}'s internal byte array will be used for reading the message.\r\n */\r\n public static void mergeFrom(InputStream in, T message, Schema schema,\r\n LinkedBuffer buffer) throws IOException\r\n {\r\n IOUtil.mergeFrom(in, buffer.buffer, message, schema, false);\r\n }\r\n\r\n /**\r\n * Merges the {@code message} (delimited) from the {@link InputStream} using the given {@code schema}.\r\n * \r\n * @return the size of the message\r\n */\r\n public static int mergeDelimitedFrom(InputStream in, T message, Schema schema)\r\n throws IOException\r\n {\r\n return IOUtil.mergeDelimitedFrom(in, message, schema, false);\r\n }\r\n\r\n /**\r\n * Merges the {@code message} (delimited) from the {@link InputStream} using the given {@code schema}.\r\n *

\r\n * The delimited message size must not be larger than the {@code buffer}'s size/capacity. {@link ProtobufException}\r\n * \"size limit exceeded\" is thrown otherwise.\r\n * \r\n * @return the size of the message\r\n */\r\n public static int mergeDelimitedFrom(InputStream in, T message, Schema schema,\r\n LinkedBuffer buffer) throws IOException\r\n {\r\n return IOUtil.mergeDelimitedFrom(in, buffer.buffer, message, schema, false);\r\n }\r\n\r\n /**\r\n * Used by the code generated messages that implement {@link java.io.Externalizable}. Merges from the\r\n * {@link DataInput}.\r\n * \r\n * @return the size of the message\r\n */\r\n public static int mergeDelimitedFrom(DataInput in, T message, Schema schema)\r\n throws IOException\r\n {\r\n return IOUtil.mergeDelimitedFrom(in, message, schema, false);\r\n }\r\n\r\n /**\r\n * Serializes the {@code message} into a byte array using the given schema.\r\n * \r\n * @return the byte array containing the data.\r\n */\r\n public static byte[] toByteArray(T message, Schema schema, LinkedBuffer buffer)\r\n {\r\n if (buffer.start != buffer.offset)\r\n throw new IllegalArgumentException(\"Buffer previously used and had not been reset.\");\r\n\r\n final ProtobufOutput output = new ProtobufOutput(buffer);\r\n try\r\n {\r\n schema.writeTo(output, message);\r\n }\r\n catch (IOException e)\r\n {\r\n throw new RuntimeException(\"Serializing to a byte array threw an IOException \" +\r\n \"(should never happen).\", e);\r\n }\r\n\r\n return output.toByteArray();\r\n }\r\n\r\n /**\r\n * Writes the {@code message} into the {@link LinkedBuffer} using the given schema.\r\n * \r\n * @return the size of the message\r\n */\r\n public static int writeTo(LinkedBuffer buffer, T message, Schema schema)\r\n {\r\n if (buffer.start != buffer.offset)\r\n throw new IllegalArgumentException(\"Buffer previously used and had not been reset.\");\r\n\r\n final ProtobufOutput output = new ProtobufOutput(buffer);\r\n try\r\n {\r\n schema.writeTo(output, message);\r\n }\r\n catch (IOException e)\r\n {\r\n throw new RuntimeException(\"Serializing to a LinkedBuffer threw an IOException \" +\r\n \"(should never happen).\", e);\r\n }\r\n\r\n return output.getSize();\r\n }\r\n\r\n /**\r\n * Serializes the {@code message} into an {@link OutputStream} using the given schema.\r\n * \r\n * @return the size of the message\r\n */\r\n public static int writeTo(OutputStream out, T message, Schema schema,\r\n LinkedBuffer buffer) throws IOException\r\n {\r\n if (buffer.start != buffer.offset)\r\n throw new IllegalArgumentException(\"Buffer previously used and had not been reset.\");\r\n\r\n final ProtobufOutput output = new ProtobufOutput(buffer);\r\n schema.writeTo(output, message);\r\n return LinkedBuffer.writeTo(out, buffer);\r\n }\r\n\r\n /**\r\n * Serializes the {@code message}, prefixed with its length, into an {@link OutputStream}.\r\n * \r\n * @return the size of the message\r\n */\r\n public static int writeDelimitedTo(OutputStream out, T message, Schema schema,\r\n LinkedBuffer buffer) throws IOException\r\n {\r\n if (buffer.start != buffer.offset)\r\n throw new IllegalArgumentException(\"Buffer previously used and had not been reset.\");\r\n\r\n final ProtobufOutput output = new ProtobufOutput(buffer);\r\n schema.writeTo(output, message);\r\n final int size = output.getSize();\r\n ProtobufOutput.writeRawVarInt32Bytes(out, size);\r\n final int msgSize = LinkedBuffer.writeTo(out, buffer);\r\n\r\n assert size == msgSize;\r\n\r\n return size;\r\n }\r\n\r\n /**\r\n * Used by the code generated messages that implement {@link java.io.Externalizable}. Writes to the\r\n * {@link DataOutput} .\r\n * \r\n * @return the size of the message.\r\n */\r\n public static int writeDelimitedTo(DataOutput out, T message, Schema schema)\r\n throws IOException\r\n {\r\n final LinkedBuffer buffer = new LinkedBuffer(LinkedBuffer.MIN_BUFFER_SIZE);\r\n final ProtobufOutput output = new ProtobufOutput(buffer);\r\n schema.writeTo(output, message);\r\n final int size = output.getSize();\r\n ProtobufOutput.writeRawVarInt32Bytes(out, size);\r\n\r\n final int msgSize = LinkedBuffer.writeTo(out, buffer);\r\n\r\n assert size == msgSize;\r\n\r\n return size;\r\n }\r\n\r\n /**\r\n * Serializes the {@code messages} (delimited) into an {@link OutputStream} using the given schema.\r\n * \r\n * @return the total size of the messages (excluding the length prefix varint)\r\n */\r\n public static int writeListTo(OutputStream out, List messages, Schema schema,\r\n LinkedBuffer buffer) throws IOException\r\n {\r\n if (buffer.start != buffer.offset)\r\n throw new IllegalArgumentException(\"Buffer previously used and had not been reset.\");\r\n\r\n final ProtobufOutput output = new ProtobufOutput(buffer);\r\n int totalSize = 0;\r\n for (T m : messages)\r\n {\r\n schema.writeTo(output, m);\r\n final int size = output.getSize();\r\n ProtobufOutput.writeRawVarInt32Bytes(out, size);\r\n final int msgSize = LinkedBuffer.writeTo(out, buffer);\r\n\r\n assert size == msgSize;\r\n\r\n totalSize += size;\r\n output.clear();\r\n }\r\n return totalSize;\r\n }\r\n\r\n /**\r\n * Parses the {@code messages} (delimited) from the {@link InputStream} using the given {@code schema}.\r\n * \r\n * @return the list containing the messages.\r\n */\r\n public static List parseListFrom(InputStream in, Schema schema) throws IOException\r\n {\r\n final ArrayList list = new ArrayList();\r\n byte[] buf = null;\r\n int biggestLen = 0;\r\n LimitedInputStream lin = null;\r\n for (int size = in.read(); size != -1; size = in.read())\r\n {\r\n final T message = schema.newMessage();\r\n list.add(message);\r\n final int len = size < 0x80 ? size : CodedInput.readRawVarint32(in, size);\r\n if (len != 0)\r\n {\r\n // not an empty message\r\n if (len > CodedInput.DEFAULT_BUFFER_SIZE)\r\n {\r\n // message too big\r\n if (lin == null)\r\n lin = new LimitedInputStream(in);\r\n final CodedInput input = new CodedInput(lin.limit(len), false);\r\n schema.mergeFrom(input, message);\r\n input.checkLastTagWas(0);\r\n continue;\r\n }\r\n\r\n if (biggestLen < len)\r\n {\r\n // cannot reuse buffer, allocate a bigger buffer\r\n // discard the last one for gc\r\n buf = new byte[len];\r\n biggestLen = len;\r\n }\r\n IOUtil.fillBufferFrom(in, buf, 0, len);\r\n final ByteArrayInput input = new ByteArrayInput(buf, 0, len, false);\r\n try\r\n {\r\n schema.mergeFrom(input, message);\r\n }\r\n catch (ArrayIndexOutOfBoundsException e)\r\n {\r\n throw ProtobufException.truncatedMessage(e);\r\n }\r\n input.checkLastTagWas(0);\r\n }\r\n }\r\n return list;\r\n }\r\n\r\n /**\r\n * Optimal/Optional mergeDelimitedFrom - If the message does not fit the buffer, no merge is done and this method\r\n * will return false.\r\n *

\r\n * This is strictly for reading a single message from the stream because the buffer is aggressively filled when\r\n * reading the delimited size (which could result into reading more bytes than it has to).\r\n *

\r\n * The remaining bytes will be drained (consumed and discared) when the message is too large.\r\n */\r\n public static boolean optMergeDelimitedFrom(InputStream in,\r\n T message, Schema schema,\r\n LinkedBuffer buffer) throws IOException\r\n {\r\n return optMergeDelimitedFrom(in, message, schema, true, buffer);\r\n }\r\n\r\n /**\r\n * Optimal/Optional mergeDelimitedFrom - If the message does not fit the buffer, no merge is done and this method\r\n * will return false.\r\n *

\r\n * This is strictly for reading a single message from the stream because the buffer is aggressively filled when\r\n * reading the delimited size (which could result into reading more bytes than it has to).\r\n */\r\n public static boolean optMergeDelimitedFrom(InputStream in,\r\n T message, Schema schema, boolean drainRemainingBytesIfTooLarge,\r\n LinkedBuffer buffer) throws IOException\r\n {\r\n if (buffer.start != buffer.offset)\r\n throw new IllegalArgumentException(\"Buffer previously used and had not been reset.\");\r\n\r\n final int size = IOUtil.fillBufferWithDelimitedMessageFrom(in,\r\n drainRemainingBytesIfTooLarge, buffer);\r\n\r\n if (size == 0)\r\n {\r\n // empty message\r\n return true;\r\n }\r\n\r\n if (buffer.start == buffer.offset)\r\n {\r\n // read offset not set ... message too large\r\n return false;\r\n }\r\n\r\n final ByteArrayInput input = new ByteArrayInput(buffer.buffer,\r\n buffer.offset, size, false);\r\n try\r\n {\r\n schema.mergeFrom(input, message);\r\n input.checkLastTagWas(0);\r\n }\r\n catch (ArrayIndexOutOfBoundsException e)\r\n {\r\n throw ProtobufException.truncatedMessage(e);\r\n }\r\n finally\r\n {\r\n // reset\r\n buffer.offset = buffer.start;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Optimal writeDelimitedTo - The varint32 prefix is written to the buffer instead of directly writing to\r\n * outputstream.\r\n * \r\n * @return the size of the message\r\n */\r\n public static int optWriteDelimitedTo(OutputStream out, T message,\r\n Schema schema, LinkedBuffer buffer) throws IOException\r\n {\r\n if (buffer.start != buffer.offset)\r\n throw new IllegalArgumentException(\"Buffer previously used and had not been reset.\");\r\n\r\n final ProtobufOutput output = new ProtobufOutput(buffer);\r\n\r\n // leave space for varint32\r\n buffer.offset = buffer.start + 5;\r\n output.size += 5;\r\n\r\n schema.writeTo(output, message);\r\n\r\n final int size = output.size - 5;\r\n\r\n final int delimOffset = IOUtil.putVarInt32AndGetOffset(size, buffer.buffer,\r\n buffer.start);\r\n\r\n // write to stream\r\n out.write(buffer.buffer, delimOffset, buffer.offset - delimOffset);\r\n\r\n // flush remaining\r\n if (buffer.next != null)\r\n LinkedBuffer.writeTo(out, buffer.next);\r\n\r\n return size;\r\n }\r\n}\r\n", "file_name": "ProtobufIOUtil.java", "human_label": "Use ProtobufOutput and the LinkedBuffer to write the message into the given OutputStream out, and return the message size.", "level": "project_runnable", "lineno": "236", "name": "writeDelimitedTo", "oracle_context": "{ \"apis\" : \"[writeTo, getSize, writeRawVarInt32Bytes]\", \"classes\" : \"[ProtobufOutput]\", \"vars\" : \"[start, offset]\" }", "package": "io.protostuff", "project": "protostuff-master" }, { "_id": "636767001a6d9265ec01787e", "all_context": "{ \"class_level\" : \"import net.hasor.utils.ArrayUtils;\\nimport net.hasor.utils.ClassUtils;\\nimport java.lang.reflect.AccessibleObject;\\nimport java.lang.reflect.Field;\\nimport java.lang.reflect.Modifier;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nboolean appendStatics;\\nboolean appendTransients;\\nString[] excludeFieldNames;\\nClass upToClass;\\ntoString(Object object,ToStringStyle style);\\ntoString(Object object,ToStringStyle style,boolean outputTransients);\\ntoString(Object object,ToStringStyle style,boolean outputTransients,boolean outputStatics);\\ntoString(Object object,ToStringStyle style,boolean outputTransients,boolean outputStatics,Class reflectUpToClass);\\ntoStringExclude(Object object,String excludeFieldName);\\ntoStringExclude(Object object,Collection excludeFieldNames);\\ntoNoNullStringArray(Collection collection);\\ntoNoNullStringArray(Object[] array);\\ntoStringExclude(Object object,String[] excludeFieldNames);\\nReflectionToStringBuilder(Object object);\\nReflectionToStringBuilder(Object object,ToStringStyle style);\\nReflectionToStringBuilder(Object object,ToStringStyle style,StringBuffer buffer);\\nReflectionToStringBuilder(Object object,ToStringStyle style,StringBuffer buffer,Class reflectUpToClass,boolean outputTransients,boolean outputStatics);\\naccept(Field field);\\nappendFieldsIn(Class clazz);\\ngetExcludeFieldNames();\\ngetUpToClass();\\ngetValue(Field field);\\nisAppendStatics();\\nisAppendTransients();\\nreflectionAppendArray(Object array);\\nsetAppendStatics(boolean appendStatics);\\nsetAppendTransients(boolean appendTransients);\\nsetExcludeFieldNames(String[] excludeFieldNamesParam);\\nsetUpToClass(Class clazz);\\ntoString();\\ntoString(Object object);\\n\", \"repo_level\" : \"public interface ArrayUtils {static Map toMap(Object[] array);\\nstatic Object[] clone(Object[] array);\\nstatic long[] clone(long[] array);\\nstatic int[] clone(int[] array);\\nstatic short[] clone(short[] array);\\nstatic char[] clone(char[] array);\\nstatic byte[] clone(byte[] array);\\nstatic double[] clone(double[] array);\\nstatic float[] clone(float[] array);\\nstatic boolean[] clone(boolean[] array);\\nstatic String[] clone(String[] array);\\nstatic Object[] nullToEmpty(Object[] array);\\nstatic String[] nullToEmpty(String[] array);\\nstatic long[] nullToEmpty(long[] array);\\nstatic int[] nullToEmpty(int[] array);\\nstatic short[] nullToEmpty(short[] array);\\nstatic char[] nullToEmpty(char[] array);\\nstatic byte[] nullToEmpty(byte[] array);\\nstatic double[] nullToEmpty(double[] array);\\nstatic float[] nullToEmpty(float[] array);\\nstatic boolean[] nullToEmpty(boolean[] array);\\nstatic Long[] nullToEmpty(Long[] array);\\nstatic Integer[] nullToEmpty(Integer[] array);\\nstatic Short[] nullToEmpty(Short[] array);\\nstatic Character[] nullToEmpty(Character[] array);\\nstatic Byte[] nullToEmpty(Byte[] array);\\nstatic Double[] nullToEmpty(Double[] array);\\nstatic Float[] nullToEmpty(Float[] array);\\nstatic Boolean[] nullToEmpty(Boolean[] array);\\nstatic Object[] subarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic long[] subarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic int[] subarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic short[] subarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic char[] subarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic byte[] subarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic double[] subarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic float[] subarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic boolean[] subarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic boolean isSameLength(Object[] array1,Object[] array2);\\nstatic boolean isSameLength(long[] array1,long[] array2);\\nstatic boolean isSameLength(int[] array1,int[] array2);\\nstatic boolean isSameLength(short[] array1,short[] array2);\\nstatic boolean isSameLength(char[] array1,char[] array2);\\nstatic boolean isSameLength(byte[] array1,byte[] array2);\\nstatic boolean isSameLength(double[] array1,double[] array2);\\nstatic boolean isSameLength(float[] array1,float[] array2);\\nstatic boolean isSameLength(boolean[] array1,boolean[] array2);\\nstatic int getLength(Object array);\\nstatic boolean isSameType(Object array1,Object array2);\\nstatic void reverse(Object[] array);\\nstatic void reverse(long[] array);\\nstatic void reverse(int[] array);\\nstatic void reverse(short[] array);\\nstatic void reverse(char[] array);\\nstatic void reverse(byte[] array);\\nstatic void reverse(double[] array);\\nstatic void reverse(float[] array);\\nstatic void reverse(boolean[] array);\\nstatic int indexOf(Object[] array,Object objectToFind);\\nstatic int indexOf(Object[] array,Object objectToFind,int startIndex);\\nstatic int lastIndexOf(Object[] array,Object objectToFind);\\nstatic int lastIndexOf(Object[] array,Object objectToFind,int startIndex);\\nstatic boolean contains(Object[] array,Object objectToFind);\\nstatic int indexOf(long[] array,long valueToFind);\\nstatic int indexOf(long[] array,long valueToFind,int startIndex);\\nstatic int lastIndexOf(long[] array,long valueToFind);\\nstatic int lastIndexOf(long[] array,long valueToFind,int startIndex);\\nstatic boolean contains(long[] array,long valueToFind);\\nstatic int indexOf(int[] array,int valueToFind);\\nstatic int indexOf(int[] array,int valueToFind,int startIndex);\\nstatic int lastIndexOf(int[] array,int valueToFind);\\nstatic int lastIndexOf(int[] array,int valueToFind,int startIndex);\\nstatic boolean contains(int[] array,int valueToFind);\\nstatic int indexOf(short[] array,short valueToFind);\\nstatic int indexOf(short[] array,short valueToFind,int startIndex);\\nstatic int lastIndexOf(short[] array,short valueToFind);\\nstatic int lastIndexOf(short[] array,short valueToFind,int startIndex);\\nstatic boolean contains(short[] array,short valueToFind);\\nstatic int indexOf(char[] array,char valueToFind);\\nstatic int indexOf(char[] array,char valueToFind,int startIndex);\\nstatic int lastIndexOf(char[] array,char valueToFind);\\nstatic int lastIndexOf(char[] array,char valueToFind,int startIndex);\\nstatic boolean contains(char[] array,char valueToFind);\\nstatic int indexOf(byte[] array,byte valueToFind);\\nstatic int indexOf(byte[] array,byte valueToFind,int startIndex);\\nstatic int lastIndexOf(byte[] array,byte valueToFind);\\nstatic int lastIndexOf(byte[] array,byte valueToFind,int startIndex);\\nstatic boolean contains(byte[] array,byte valueToFind);\\nstatic int indexOf(double[] array,double valueToFind);\\nstatic int indexOf(double[] array,double valueToFind,double tolerance);\\nstatic int indexOf(double[] array,double valueToFind,int startIndex);\\nstatic int indexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nstatic int lastIndexOf(double[] array,double valueToFind);\\nstatic int lastIndexOf(double[] array,double valueToFind,double tolerance);\\nstatic int lastIndexOf(double[] array,double valueToFind,int startIndex);\\nstatic int lastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nstatic boolean contains(double[] array,double valueToFind);\\nstatic boolean contains(double[] array,double valueToFind,double tolerance);\\nstatic int indexOf(float[] array,float valueToFind);\\nstatic int indexOf(float[] array,float valueToFind,int startIndex);\\nstatic int lastIndexOf(float[] array,float valueToFind);\\nstatic int lastIndexOf(float[] array,float valueToFind,int startIndex);\\nstatic boolean contains(float[] array,float valueToFind);\\nstatic int indexOf(boolean[] array,boolean valueToFind);\\nstatic int indexOf(boolean[] array,boolean valueToFind,int startIndex);\\nstatic int lastIndexOf(boolean[] array,boolean valueToFind);\\nstatic int lastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\nstatic boolean contains(boolean[] array,boolean valueToFind);\\nstatic char[] toPrimitive(Character[] array);\\nstatic char[] toPrimitive(Character[] array,char valueForNull);\\nstatic Character[] toObject(char[] array);\\nstatic long[] toPrimitive(Long[] array);\\nstatic long[] toPrimitive(Long[] array,long valueForNull);\\nstatic Long[] toObject(long[] array);\\nstatic int[] toPrimitive(Integer[] array);\\nstatic int[] toPrimitive(Integer[] array,int valueForNull);\\nstatic Integer[] toObject(int[] array);\\nstatic short[] toPrimitive(Short[] array);\\nstatic short[] toPrimitive(Short[] array,short valueForNull);\\nstatic Short[] toObject(short[] array);\\nstatic byte[] toPrimitive(Byte[] array);\\nstatic byte[] toPrimitive(Byte[] array,byte valueForNull);\\nstatic Byte[] toObject(byte[] array);\\nstatic double[] toPrimitive(Double[] array);\\nstatic double[] toPrimitive(Double[] array,double valueForNull);\\nstatic Double[] toObject(double[] array);\\nstatic float[] toPrimitive(Float[] array);\\nstatic float[] toPrimitive(Float[] array,float valueForNull);\\nstatic Float[] toObject(float[] array);\\nstatic boolean[] toPrimitive(Boolean[] array);\\nstatic boolean[] toPrimitive(Boolean[] array,boolean valueForNull);\\nstatic Boolean[] toObject(boolean[] array);\\nstatic boolean isEmpty(Object[] array);\\nstatic boolean isEmpty(long[] array);\\nstatic boolean isEmpty(int[] array);\\nstatic boolean isEmpty(short[] array);\\nstatic boolean isEmpty(char[] array);\\nstatic boolean isEmpty(byte[] array);\\nstatic boolean isEmpty(double[] array);\\nstatic boolean isEmpty(float[] array);\\nstatic boolean isEmpty(boolean[] array);\\nstatic boolean isNotEmpty(Object[] array);\\nstatic boolean isNotEmpty(long[] array);\\nstatic boolean isNotEmpty(int[] array);\\nstatic boolean isNotEmpty(short[] array);\\nstatic boolean isNotEmpty(char[] array);\\nstatic boolean isNotEmpty(byte[] array);\\nstatic boolean isNotEmpty(double[] array);\\nstatic boolean isNotEmpty(float[] array);\\nstatic boolean isNotEmpty(boolean[] array);\\nstatic Object[] addAll(Object[] array1,Object[] array2);\\nstatic boolean[] addAll(boolean[] array1,boolean[] array2);\\nstatic char[] addAll(char[] array1,char[] array2);\\nstatic byte[] addAll(byte[] array1,byte[] array2);\\nstatic short[] addAll(short[] array1,short[] array2);\\nstatic int[] addAll(int[] array1,int[] array2);\\nstatic long[] addAll(long[] array1,long[] array2);\\nstatic float[] addAll(float[] array1,float[] array2);\\nstatic double[] addAll(double[] array1,double[] array2);\\nstatic String[] addAll(String[] array1,String[] array2);\\nstatic T[] add(T[] array,T element);\\nstatic boolean[] add(boolean[] array,boolean element);\\nstatic byte[] add(byte[] array,byte element);\\nstatic char[] add(char[] array,char element);\\nstatic double[] add(double[] array,double element);\\nstatic float[] add(float[] array,float element);\\nstatic int[] add(int[] array,int element);\\nstatic long[] add(long[] array,long element);\\nstatic short[] add(short[] array,short element);\\nstatic Object[] add(Object[] array,int index,Object element);\\nstatic boolean[] add(boolean[] array,int index,boolean element);\\nstatic char[] add(char[] array,int index,char element);\\nstatic byte[] add(byte[] array,int index,byte element);\\nstatic short[] add(short[] array,int index,short element);\\nstatic int[] add(int[] array,int index,int element);\\nstatic long[] add(long[] array,int index,long element);\\nstatic float[] add(float[] array,int index,float element);\\nstatic double[] add(double[] array,int index,double element);\\nstatic Object[] remove(Object[] array,int index);\\nstatic Object[] removeElement(Object[] array,Object element);\\nstatic boolean[] remove(boolean[] array,int index);\\nstatic boolean[] removeElement(boolean[] array,boolean element);\\nstatic byte[] remove(byte[] array,int index);\\nstatic byte[] removeElement(byte[] array,byte element);\\nstatic char[] remove(char[] array,int index);\\nstatic char[] removeElement(char[] array,char element);\\nstatic double[] remove(double[] array,int index);\\nstatic double[] removeElement(double[] array,double element);\\nstatic float[] remove(float[] array,int index);\\nstatic float[] removeElement(float[] array,float element);\\nstatic int[] remove(int[] array,int index);\\nstatic int[] removeElement(int[] array,int element);\\nstatic long[] remove(long[] array,int index);\\nstatic long[] removeElement(long[] array,long element);\\nstatic short[] remove(short[] array,int index);\\nstatic short[] removeElement(short[] array,short element);\\nstatic Object[] clearNull(Object[] arr);\\n }\\npublic interface ClassUtils {static String getShortClassName(Object object,String valueIfNull);\\nstatic String getShortClassName(Class cls);\\nstatic String getShortClassName(String className);\\nstatic String getPackageName(Object object,String valueIfNull);\\nstatic String getPackageName(Class cls);\\nstatic String getPackageName(String className);\\nstatic List> getAllSuperclasses(Class cls);\\nstatic List> getAllInterfaces(Class cls);\\nstatic List> convertClassNamesToClasses(List classNames);\\nstatic List convertClassesToClassNames(List classes);\\nstatic boolean isAssignable(Class[] classArray,Class[] toClassArray);\\nstatic boolean isAssignable(Class[] classArray,Class[] toClassArray,boolean autoboxing);\\nstatic boolean isAssignable(Class cls,Class toClass);\\nstatic boolean isAssignable(Class cls,Class toClass,boolean autoboxing);\\nstatic Class primitiveToWrapper(Class cls);\\nstatic Class[] primitivesToWrappers(Class[] classes);\\nstatic Class wrapperToPrimitive(Class cls);\\nstatic Class[] wrappersToPrimitives(Class[] classes);\\nstatic boolean isInnerClass(Class cls);\\nstatic Class getClass(ClassLoader classLoader,String className,boolean initialize);\\nstatic Class getClass(ClassLoader classLoader,String className);\\nstatic Class getClass(String className);\\nstatic Class getClass(String className,boolean initialize);\\nstatic Method getPublicMethod(Class cls,String methodName,Class parameterTypes);\\nstatic Class[] toClass(Object[] array);\\nstatic String getShortCanonicalName(Object object,String valueIfNull);\\nstatic String getShortCanonicalName(Class cls);\\nstatic String getShortCanonicalName(String canonicalName);\\nstatic String getPackageCanonicalName(Object object,String valueIfNull);\\nstatic String getPackageCanonicalName(Class cls);\\nstatic String getPackageCanonicalName(String canonicalName);\\nstatic ClassLoader getClassLoader(ClassLoader classLoader);\\nstatic boolean isLangClass(Class target);\\nstatic String getDescName(Class type);\\nstatic String getDescNameWithOutModifiers(Method method);\\nstatic String getDescName(Method method);\\nstatic Class getSuperClassGenricType(Class clazz,int index);\\nstatic T newInstance(Class clazz);\\n }\\n\" }", "class_name": "ReflectionToStringBuilder", "code": "public String toString(){\n if (this.getObject() == null) {\n return this.getStyle().getNullText();\n }\n Class clazz=this.getObject().getClass();\n this.appendFieldsIn(clazz);\n while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) {\n clazz=clazz.getSuperclass();\n this.appendFieldsIn(clazz);\n }\n return super.toString();\n}\n", "docstring": "/** \n *

Gets the String built by this builder.

\n * @return the built string\n */\n", "end_lineno": "684", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.builder;\nimport net.hasor.utils.ArrayUtils;\nimport net.hasor.utils.ClassUtils;\n\nimport java.lang.reflect.AccessibleObject;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\n\n/**\n *

\n * Assists in implementing {@link Object#toString()} methods using reflection.\n *

\n *\n *

\n * This class uses reflection to determine the fields to append. Because these fields are usually private, the class\n * uses {@link java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[], boolean)} to\n * change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are\n * set up correctly.\n *

\n *\n *

\n * A typical invocation for this method would look like:\n *

\n *\n *
\n * public String toString() {\n *   return ReflectionToStringBuilder.toString(this);\n * }
\n *\n *\n *\n *

\n * You can also use the builder to debug 3rd party objects:\n *

\n *\n *
\n * System.out.println(\"An object: \" + ReflectionToStringBuilder.toString(anObject));
\n *\n *\n *\n *

\n * A subclass can control field output by overriding the methods:\n *

    \n *
  • {@link #accept(java.lang.reflect.Field)}
  • \n *
  • {@link #getValue(java.lang.reflect.Field)}
  • \n *
\n *

\n *

\n * For example, this method does not include the password field in the returned\n * String:\n *

\n *\n *
\n * public String toString() {\n *     return (new ReflectionToStringBuilder(this) {\n *         protected boolean accept(Field f) {\n *             return super.accept(f) && !f.getName().equals(\"password\");\n *         }\n *     }).toString();\n * }
\n *\n *\n *\n *

\n * The exact format of the toString is determined by the {@link ToStringStyle} passed into the\n * constructor.\n *

\n *\n * @author Apache Software Foundation\n * @author Gary Gregory\n * @author Pete Gieser\n * @since 2.0\n * @version $Id: ReflectionToStringBuilder.java 905636 2010-02-02 14:03:32Z niallp $\n */\npublic class ReflectionToStringBuilder extends ToStringBuilder {\n /**\n *

\n * Builds a toString value using the default ToStringStyle through reflection.\n *

\n *\n *

\n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

\n *\n *

\n * Transient members will be not be included, as they are likely derived. Static fields will not be included.\n * Superclass fields will be appended.\n *

\n *\n * @param object\n * the Object to be output\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object is null\n */\n public static String toString(Object object) {\n return toString(object, null, false, false, null);\n }\n\n /**\n *

\n * Builds a toString value through reflection.\n *

\n *\n *

\n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

\n *\n *

\n * Transient members will be not be included, as they are likely derived. Static fields will not be included.\n * Superclass fields will be appended.\n *

\n *\n *

\n * If the style is null, the default ToStringStyle is used.\n *

\n *\n * @param object\n * the Object to be output\n * @param style\n * the style of the toString to create, may be null\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object or ToStringStyle is null\n */\n public static String toString(Object object, ToStringStyle style) {\n return toString(object, style, false, false, null);\n }\n\n /**\n *

\n * Builds a toString value through reflection.\n *

\n *\n *

\n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

\n *\n *

\n * If the outputTransients is true, transient members will be output, otherwise they\n * are ignored, as they are likely derived fields, and not part of the value of the Object.\n *

\n *\n *

\n * Static fields will not be included. Superclass fields will be appended.\n *

\n *\n *

\n * If the style is null, the default ToStringStyle is used.\n *

\n *\n * @param object\n * the Object to be output\n * @param style\n * the style of the toString to create, may be null\n * @param outputTransients\n * whether to include transient fields\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object is null\n */\n public static String toString(Object object, ToStringStyle style, boolean outputTransients) {\n return toString(object, style, outputTransients, false, null);\n }\n\n /**\n *

\n * Builds a toString value through reflection.\n *

\n *\n *

\n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

\n *\n *

\n * If the outputTransients is true, transient fields will be output, otherwise they\n * are ignored, as they are likely derived fields, and not part of the value of the Object.\n *

\n *\n *

\n * If the outputStatics is true, static fields will be output, otherwise they are\n * ignored.\n *

\n *\n *

\n * Static fields will not be included. Superclass fields will be appended.\n *

\n *\n *

\n * If the style is null, the default ToStringStyle is used.\n *

\n *\n * @param object\n * the Object to be output\n * @param style\n * the style of the toString to create, may be null\n * @param outputTransients\n * whether to include transient fields\n * @param outputStatics\n * whether to include transient fields\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object is null\n * @since 2.1\n */\n public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics) {\n return toString(object, style, outputTransients, outputStatics, null);\n }\n\n /**\n *

\n * Builds a toString value through reflection.\n *

\n *\n *

\n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

\n *\n *

\n * If the outputTransients is true, transient fields will be output, otherwise they\n * are ignored, as they are likely derived fields, and not part of the value of the Object.\n *

\n *\n *

\n * If the outputStatics is true, static fields will be output, otherwise they are\n * ignored.\n *

\n *\n *

\n * Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as\n * java.lang.Object.\n *

\n *\n *

\n * If the style is null, the default ToStringStyle is used.\n *

\n *\n * @param object\n * the Object to be output\n * @param style\n * the style of the toString to create, may be null\n * @param outputTransients\n * whether to include transient fields\n * @param outputStatics\n * whether to include static fields\n * @param reflectUpToClass\n * the superclass to reflect up to (inclusive), may be null\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object is null\n * @since 2.1\n */\n public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics, Class reflectUpToClass) {\n return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics).toString();\n }\n\n /**\n * Builds a String for a toString method excluding the given field name.\n *\n * @param object\n * The object to \"toString\".\n * @param excludeFieldName\n * The field name to exclude\n * @return The toString value.\n */\n public static String toStringExclude(Object object, final String excludeFieldName) {\n return toStringExclude(object, new String[] { excludeFieldName });\n }\n\n /**\n * Builds a String for a toString method excluding the given field names.\n *\n * @param object\n * The object to \"toString\".\n * @param excludeFieldNames\n * The field names to exclude. Null excludes nothing.\n * @return The toString value.\n */\n public static String toStringExclude(Object object, Collection /*String*/ excludeFieldNames) {\n return toStringExclude(object, toNoNullStringArray(excludeFieldNames));\n }\n\n /**\n * Converts the given Collection into an array of Strings. The returned array does not contain null\n * entries. Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} if an array element \n * is null.\n *\n * @param collection\n * The collection to convert\n * @return A new array of Strings.\n */\n static String[] toNoNullStringArray(Collection collection) {\n if (collection == null) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return toNoNullStringArray(collection.toArray());\n }\n\n /**\n * Returns a new array of Strings without null elements. Internal method used to normalize exclude lists\n * (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException}\n * if an array element is null.\n *\n * @param array\n * The array to check\n * @return The given array or a new array without null.\n */\n static String[] toNoNullStringArray(Object[] array) {\n ArrayList list = new ArrayList(array.length);\n for (int i = 0; i < array.length; i++) {\n Object e = array[i];\n if (e != null) {\n list.add(e.toString());\n }\n }\n return (String[]) list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);\n }\n\n /**\n * Builds a String for a toString method excluding the given field names.\n *\n * @param object\n * The object to \"toString\".\n * @param excludeFieldNames\n * The field names to exclude\n * @return The toString value.\n */\n public static String toStringExclude(Object object, String[] excludeFieldNames) {\n return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString();\n }\n\n /**\n * Whether or not to append static fields.\n */\n private boolean appendStatics = false;\n /**\n * Whether or not to append transient fields.\n */\n private boolean appendTransients = false;\n /**\n * Which field names to exclude from output. Intended for fields like \"password\".\n */\n private String[] excludeFieldNames;\n /**\n * The last super class to stop appending fields for.\n */\n private Class upToClass = null;\n\n /**\n *

\n * Constructor.\n *

\n *\n *

\n * This constructor outputs using the default style set with setDefaultStyle.\n *

\n *\n * @param object\n * the Object to build a toString for, must not be null\n * @throws IllegalArgumentException\n * if the Object passed in is null\n */\n public ReflectionToStringBuilder(Object object) {\n super(object);\n }\n\n /**\n *

\n * Constructor.\n *

\n *\n *

\n * If the style is null, the default style is used.\n *

\n *\n * @param object\n * the Object to build a toString for, must not be null\n * @param style\n * the style of the toString to create, may be null\n * @throws IllegalArgumentException\n * if the Object passed in is null\n */\n public ReflectionToStringBuilder(Object object, ToStringStyle style) {\n super(object, style);\n }\n\n /**\n *

\n * Constructor.\n *

\n *\n *

\n * If the style is null, the default style is used.\n *

\n *\n *

\n * If the buffer is null, a new one is created.\n *

\n *\n * @param object\n * the Object to build a toString for\n * @param style\n * the style of the toString to create, may be null\n * @param buffer\n * the StringBuffer to populate, may be null\n * @throws IllegalArgumentException\n * if the Object passed in is null\n */\n public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) {\n super(object, style, buffer);\n }\n\n /**\n * Constructor.\n *\n * @param object\n * the Object to build a toString for\n * @param style\n * the style of the toString to create, may be null\n * @param buffer\n * the StringBuffer to populate, may be null\n * @param reflectUpToClass\n * the superclass to reflect up to (inclusive), may be null\n * @param outputTransients\n * whether to include transient fields\n * @param outputStatics\n * whether to include static fields\n * @since 2.1\n */\n public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer, Class reflectUpToClass, boolean outputTransients, boolean outputStatics) {\n super(object, style, buffer);\n this.setUpToClass(reflectUpToClass);\n this.setAppendTransients(outputTransients);\n this.setAppendStatics(outputStatics);\n }\n\n /**\n * Returns whether or not to append the given Field.\n *
    \n *
  • Transient fields are appended only if {@link #isAppendTransients()} returns true.\n *
  • Static fields are appended only if {@link #isAppendStatics()} returns true.\n *
  • Inner class fields are not appened.
  • \n *
\n *\n * @param field The Field to test.\n * @return Whether or not to append the given Field.\n */\n protected boolean accept(Field field) {\n if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {\n // Reject field from inner class.\n return false;\n }\n if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) {\n // Reject transient fields.\n return false;\n }\n if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) {\n // Reject static fields.\n return false;\n }\n if (this.getExcludeFieldNames() != null && Arrays.binarySearch(this.getExcludeFieldNames(), field.getName()) >= 0) {\n // Reject fields from the getExcludeFieldNames list.\n return false;\n }\n return true;\n }\n\n /**\n *

\n * Appends the fields and values defined by the given object of the given Class.\n *

\n *\n *

\n * If a cycle is detected as an object is "toString()'ed", such an object is rendered as if\n * Object.toString() had been called and not implemented by the object.\n *

\n *\n * @param clazz The class of object parameter\n */\n protected void appendFieldsIn(Class clazz) {\n if (clazz.isArray()) {\n this.reflectionAppendArray(this.getObject());\n return;\n }\n Field[] fields = clazz.getDeclaredFields();\n AccessibleObject.setAccessible(fields, true);\n for (int i = 0; i < fields.length; i++) {\n Field field = fields[i];\n String fieldName = field.getName();\n if (this.accept(field)) {\n try {\n // Warning: Field.get(Object) creates wrappers objects\n // for primitive types.\n Object fieldValue = this.getValue(field);\n this.append(fieldName, fieldValue);\n } catch (IllegalAccessException ex) {\n //this can't happen. Would get a Security exception\n // instead\n //throw a runtime exception in case the impossible\n // happens.\n throw new InternalError(\"Unexpected IllegalAccessException: \" + ex.getMessage());\n }\n }\n }\n }\n\n /**\n * @return Returns the excludeFieldNames.\n */\n public String[] getExcludeFieldNames() {\n return this.excludeFieldNames;\n }\n\n /**\n *

\n * Gets the last super class to stop appending fields for.\n *

\n *\n * @return The last super class to stop appending fields for.\n */\n public Class getUpToClass() {\n return this.upToClass;\n }\n\n /**\n *

\n * Calls java.lang.reflect.Field.get(Object).\n *

\n *\n * @param field The Field to query.\n * @return The Object from the given Field.\n *\n * @throws IllegalArgumentException see {@link java.lang.reflect.Field#get(Object)}\n * @throws IllegalAccessException see {@link java.lang.reflect.Field#get(Object)}\n * @see java.lang.reflect.Field#get(Object)\n */\n protected Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException {\n return field.get(this.getObject());\n }\n\n /**\n *

\n * Gets whether or not to append static fields.\n *

\n *\n * @return Whether or not to append static fields.\n * @since 2.1\n */\n public boolean isAppendStatics() {\n return this.appendStatics;\n }\n\n /**\n *

\n * Gets whether or not to append transient fields.\n *

\n *\n * @return Whether or not to append transient fields.\n */\n public boolean isAppendTransients() {\n return this.appendTransients;\n }\n\n /**\n *

\n * Append to the toString an Object array.\n *

\n *\n * @param array\n * the array to add to the toString\n * @return this\n */\n public ToStringBuilder reflectionAppendArray(Object array) {\n this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array);\n return this;\n }\n\n /**\n *

\n * Sets whether or not to append static fields.\n *

\n *\n * @param appendStatics\n * Whether or not to append static fields.\n * @since 2.1\n */\n public void setAppendStatics(boolean appendStatics) {\n this.appendStatics = appendStatics;\n }\n\n /**\n *

\n * Sets whether or not to append transient fields.\n *

\n *\n * @param appendTransients Whether or not to append transient fields.\n */\n public void setAppendTransients(boolean appendTransients) {\n this.appendTransients = appendTransients;\n }\n\n /**\n * Sets the field names to exclude.\n *\n * @param excludeFieldNamesParam\n * The excludeFieldNames to excluding from toString or null.\n * @return this\n */\n public ReflectionToStringBuilder setExcludeFieldNames(String[] excludeFieldNamesParam) {\n if (excludeFieldNamesParam == null) {\n this.excludeFieldNames = null;\n } else {\n this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam);\n Arrays.sort(this.excludeFieldNames);\n }\n return this;\n }\n\n /**\n *

\n * Sets the last super class to stop appending fields for.\n *

\n *\n * @param clazz\n * The last super class to stop appending fields for.\n */\n public void setUpToClass(Class clazz) {\n if (clazz != null) {\n Object object = getObject();\n if (object != null && clazz.isInstance(object) == false) {\n throw new IllegalArgumentException(\"Specified class is not a superclass of the object\");\n }\n }\n this.upToClass = clazz;\n }\n\n /**\n *

\n * Gets the String built by this builder.\n *

\n *\n * @return the built string\n */\n public String toString() {\n if (this.getObject() == null) {\n return this.getStyle().getNullText();\n }\n Class clazz = this.getObject().getClass();\n this.appendFieldsIn(clazz);\n while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) {\n clazz = clazz.getSuperclass();\n this.appendFieldsIn(clazz);\n }\n return super.toString();\n }\n}\n", "file_name": "ReflectionToStringBuilder.java", "human_label": "Return the string built by this string builder.", "level": "project_runnable", "lineno": "666", "name": "toString", "oracle_context": "{ \"apis\" : \"[getObject, getNullText, getStyle, getClass, appendFieldsIn, getSuperclass, getUpToClass]\", \"classes\" : \"[Class]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils.builder", "project": "hasor-master" }, { "_id": "636767781a6d9265ec01823d", "all_context": "{ \"class_level\" : \"import java.io.File;\\nimport java.io.Writer;\\nimport java.io.FileWriter;\\nimport java.io.BufferedWriter;\\nimport org.apache.log4j.spi.LoggingEvent;\\nimport org.apache.log4j.helpers.OptionConverter;\\nimport org.apache.log4j.spi.ErrorHandler;\\nString PATH_OPTION;\\nString path;\\nString PREFIX_OPTION;\\nString prefix;\\nString SUFFIX_OPTION;\\nString suffix;\\nFile dir;\\nTempFileAppender();\\ngetOptionStrings();\\nsetOption(String key,String value);\\ncheckEntryConditions();\\nsubAppend(LoggingEvent event);\\nrequiresLayout();\\nclose();\\nappend(LoggingEvent event);\\n\", \"repo_level\" : \"public interface LoggingEvent {public LocationInfo getLocationInformation();\\npublic Level getLevel();\\npublic String getLoggerName();\\npublic Category getLogger();\\npublic Object getMessage();\\npublic String getNDC();\\npublic Object getMDC(String key);\\npublic void getMDCCopy();\\npublic String getRenderedMessage();\\nstatic long getStartTime();\\npublic String getThreadName();\\npublic ThrowableInformation getThrowableInformation();\\npublic String[] getThrowableStrRep();\\nfinal void setProperty(String propName,String propValue);\\nfinal String getProperty(String key);\\nfinal boolean locationInformationExists();\\nfinal long getTimeStamp();\\npublic Set getPropertyKeySet();\\npublic Map getProperties();\\npublic String getFQNOfLoggerClass();\\npublic Object removeProperty(String propName);\\n }\\npublic interface OptionConverter {static String[] concatanateArrays(String[] l,String[] r);\\nstatic String convertSpecialChars(String s);\\nstatic String getSystemProperty(String key,String def);\\nstatic Object instantiateByKey(Properties props,String key,Class superClass,Object defaultValue);\\nstatic boolean toBoolean(String value,boolean dEfault);\\nstatic int toInt(String value,int dEfault);\\nstatic Level toLevel(String value,Level defaultValue);\\nstatic long toFileSize(String value,long dEfault);\\nstatic String findAndSubst(String key,Properties props);\\nstatic Object instantiateByClassName(String className,Class superClass,Object defaultValue);\\nstatic String substVars(String val,Properties props);\\npublic void selectAndConfigure(InputStream inputStream,String clazz,LoggerRepository hierarchy);\\npublic void selectAndConfigure(URL url,String clazz,LoggerRepository hierarchy);\\n }\\npublic interface ErrorHandler { void setLogger(Logger logger);\\n void error(String message,Exception e,int errorCode);\\n void error(String message);\\n void error(String message,Exception e,int errorCode,LoggingEvent event);\\n void setAppender(Appender appender);\\n void setBackupAppender(Appender appender);\\n }\\n\" }", "class_name": "TempFileAppender", "code": "protected void subAppend(LoggingEvent event){\n try {\n File tmp=File.createTempFile(prefix,suffix,dir);\n Writer out=new BufferedWriter(new FileWriter(tmp));\n out.write(event.message);\n out.close();\n }\n catch ( Exception e) {\n errorHandler.error(\"Error during creation of temporary File!\",e,1);\n }\n}\n", "docstring": "/** \n * This method does actual writing\n */\n", "end_lineno": "175", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n package org.apache.log4j;\n \nimport java.io.File;\nimport java.io.Writer;\nimport java.io.FileWriter;\nimport java.io.BufferedWriter;\nimport org.apache.log4j.spi.LoggingEvent;\nimport org.apache.log4j.helpers.OptionConverter;\nimport org.apache.log4j.spi.ErrorHandler;\n\n/**\n TempFileAppender creates new unique file for each logging statement.\n \n @author Leos Literak\n @author Ceki Gülcü\n \n*/\npublic class TempFileAppender extends AppenderSkeleton {\n \n /**\n A string constant used in naming the option for setting the\n directory where the log files will be created. Current value \n of this string constant is Path. java.io.tmpdir directory\n will be used, if ommited.\n */\n static final public String PATH_OPTION = \"Path\";\n \n /**\n The default path is actual directory.\n */\n protected String path = null;\n \n /**\n A string constant used in naming the option for setting the\n prefix of the log files. It has to have at least 3 characters!\n Current value of this string constant is Prefix.\n */\n static final public String PREFIX_OPTION = \"Prefix\";\n \n /**\n The default path is actual directory.\n */\n protected String prefix = \"l4j_\";\n \n /**\n A string constant used in naming the option for setting the\n suffix of the log files. Current value of this string constant \n is Suffix.\n */\n static final public String SUFFIX_OPTION = \"Suffix\";\n \n /**\n The default path is actual directory.\n */\n protected String suffix = \".tmp\";\n \n /**\n Default dir\n */\n \n protected File dir = null;\n\n\n\n\n /**\n The default constructor simply calls its parent's constructor. \n */\n public TempFileAppender() {\n super();\n }\n \n /**\n Retuns the option names for this component\n */\n public String[] getOptionStrings() {\n return OptionConverter.concatanateArrays(super.getOptionStrings(),\n new String[] {PATH_OPTION,PREFIX_OPTION,SUFFIX_OPTION});\n } \n\n /**\n Set TempFileAppender specific options.\n \n The recognized options are Path, Prefix and Suffix,\n i.e. the values of the string constants {@link #PATH_OPTION}, \n {@link #PREFIX_OPTION} and respectively {@link #SUFFIX_OPTION}. \n The options of the super class {@link AppenderSkeleton} are also \n recognized.\n */\n \n public void setOption(String key, String value) {\n super.setOption(key, value);\n if(key.equalsIgnoreCase(PATH_OPTION)) {\n\t path = value;\n\t if(path==null) {\n errorHandler.error(\"Path cannot be empty!\",null,0);\n\t }\n\n\t dir = new File(path);\n\t if(!(dir.exists() && dir.isDirectory() && dir.canWrite())) {\n errorHandler.error(\"Cannot write to directory \" + path + \"!\",null,0);\n\t }\n }\n else if(key.equalsIgnoreCase(PREFIX_OPTION)) {\n if(value!=null && value.length()>=3) {\n\t prefix = value;\n\t } else {\n errorHandler.error(\"Prefix cannot be shorter than 3 characters!\",\n\t null,0);\n\t }\n }\n else if(key.equalsIgnoreCase(SUFFIX_OPTION)) {\n if(value!=null && value.length()>=1) {\n\t suffix = value;\n\t } else {\n errorHandler.error(\"Suffix cannot be empty!\",null,0);\n\t }\n }\n }\n\n /**\n This method is called by {@link AppenderSkeleton#doAppend}\n method.\n \n

Whenever this method is called, new unique file is created\n with specified prefix and suffix. The file is closed afterwards.\n \n

The format of the output will depend on this appender's\n layout.\n \n */ \n public void append(LoggingEvent event) { \n if(!checkEntryConditions()) {\n return;\n }\n subAppend(event);\n }\n \n /**\n This method determines if there is a sense in attempting to append.\n */\n protected boolean checkEntryConditions() {\n return true;\n } \n\n /**\n This method does actual writing\n */\n protected void subAppend(LoggingEvent event) {\n try {\n File tmp = File.createTempFile(prefix,suffix,dir);\n\t Writer out = new BufferedWriter(new FileWriter(tmp));\n\t out.write(event.message);\n\t out.close();\n /* this Appender is not supposed to be used for logging of Exceptions */\n } catch (Exception e) {\n errorHandler.error(\"Error during creation of temporary File!\",e,1);\n }\n }\n \n public boolean requiresLayout() {\n return false;\n }\n \n public void close() {\n /* nothing to do */\n }\n} \n/*\n * @author $Author$\n * @version $Revision$\n * @since $Date$\n *\n * $Log$\n * Revision 1.1.2.1 2005/05/27 03:27:54 mwomack\n * Fix for #35032. Added license header to .java files that did not already have a license.\n *\n * Revision 1.1 2001/04/20 17:38:31 ceki\n *\n * Added LeosLiterak's TempFileAppender.java\n *\n*/\n", "file_name": "TempFileAppender.java", "human_label": "Write the message in the event into a temp file.", "level": "project_runnable", "lineno": "162", "name": "subAppend", "oracle_context": "{ \"apis\" : \"[createTempFile, write, close, error]\", \"classes\" : \"[File, Writer]\", \"vars\" : \"[message, prefix, suffix, dir]\" }", "package": "org.apache.log4j", "project": "logging-log4j1-main" }, { "_id": "636766ef1a6d9265ec01761a", "all_context": "{ \"class_level\" : \"ClassWriter classWriter;\\nClassReader sourceClassReader;\\nint majorVersion;\\nString className;\\nint entryCount;\\nEntry[] entries;\\nint constantPoolCount;\\nByteVector constantPool;\\nint bootstrapMethodCount;\\nByteVector bootstrapMethods;\\nint typeCount;\\nEntry[] typeTable;\\nint hashCode;\\nEntry next;\\nSymbolTable(ClassWriter classWriter);\\nSymbolTable(ClassWriter classWriter,ClassReader classReader);\\ngetSource();\\ngetMajorVersion();\\ngetClassName();\\nsetMajorVersionAndClassName(int majorVersion,String className);\\ngetConstantPoolCount();\\ngetConstantPoolLength();\\nputConstantPool(ByteVector output);\\ncomputeBootstrapMethodsSize();\\nputBootstrapMethods(ByteVector output);\\nget(int hashCode);\\nput(Entry entry);\\nadd(Entry entry);\\naddConstant(Object value);\\naddConstantClass(String value);\\naddConstantFieldref(String owner,String name,String descriptor);\\naddConstantMethodref(String owner,String name,String descriptor,boolean isInterface);\\naddConstantMemberReference(int tag,String owner,String name,String descriptor);\\naddConstantMemberReference(int index,int tag,String owner,String name,String descriptor);\\naddConstantString(String value);\\naddConstantInteger(int value);\\naddConstantFloat(float value);\\naddConstantIntegerOrFloat(int tag,int value);\\naddConstantIntegerOrFloat(int index,int tag,int value);\\naddConstantLong(long value);\\naddConstantDouble(double value);\\naddConstantLongOrDouble(int tag,long value);\\naddConstantLongOrDouble(int index,int tag,long value);\\naddConstantNameAndType(String name,String descriptor);\\naddConstantNameAndType(int index,String name,String descriptor);\\naddConstantUtf8(String value);\\naddConstantUtf8(int index,String value);\\naddConstantMethodHandle(int referenceKind,String owner,String name,String descriptor,boolean isInterface);\\naddConstantMethodHandle(int index,int referenceKind,String owner,String name,String descriptor);\\naddConstantMethodType(String methodDescriptor);\\naddConstantDynamic(String name,String descriptor,Handle bootstrapMethodHandle,Object bootstrapMethodArguments);\\naddConstantInvokeDynamic(String name,String descriptor,Handle bootstrapMethodHandle,Object bootstrapMethodArguments);\\naddConstantDynamicOrInvokeDynamicReference(int tag,String name,String descriptor,int bootstrapMethodIndex);\\naddConstantDynamicOrInvokeDynamicReference(int tag,int index,String name,String descriptor,int bootstrapMethodIndex);\\naddConstantModule(String moduleName);\\naddConstantPackage(String packageName);\\naddConstantUtf8Reference(int tag,String value);\\naddConstantUtf8Reference(int index,int tag,String value);\\naddBootstrapMethod(Handle bootstrapMethodHandle,Object bootstrapMethodArguments);\\naddBootstrapMethod(int offset,int length,int hashCode);\\ngetType(int typeIndex);\\naddType(String value);\\naddUninitializedType(String value,int bytecodeOffset);\\naddMergedType(int typeTableIndex1,int typeTableIndex2);\\naddTypeInternal(Entry entry);\\nhash(int tag,int value);\\nhash(int tag,long value);\\nhash(int tag,String value);\\nhash(int tag,String value1,int value2);\\nhash(int tag,String value1,String value2);\\nhash(int tag,String value1,String value2,int value3);\\nhash(int tag,String value1,String value2,String value3);\\nhash(int tag,String value1,String value2,String value3,int value4);\\nEntry(int index,int tag,String owner,String name,String value,long data,int hashCode);\\nEntry(int index,int tag,String value,int hashCode);\\nEntry(int index,int tag,String value,long data,int hashCode);\\nEntry(int index,int tag,String name,String value,int hashCode);\\nEntry(int index,int tag,long data,int hashCode);\\ncopyBootstrapMethods(ClassReader classReader,char[] charBuffer);\\n\", \"repo_level\" : \"\" }", "class_name": "SymbolTable", "code": "int addType(final String value){\n int hashCode=hash(Symbol.TYPE_TAG,value);\n Entry entry=get(hashCode);\n while (entry != null) {\n if (entry.tag == Symbol.TYPE_TAG && entry.hashCode == hashCode && entry.value.equals(value)) {\n return entry.index;\n }\n entry=entry.next;\n }\n return addTypeInternal(new Entry(typeCount,Symbol.TYPE_TAG,value,hashCode));\n}\n", "docstring": "/** \n * Adds a type in the type table of this symbol table. Does nothing if the type table already contains a similar type.\n * @param value an internal class name.\n * @return the index of a new or already existing type Symbol with the given value.\n */\n", "end_lineno": "1019", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage net.hasor.utils.asm;\n/**\n * The constant pool entries, the BootstrapMethods attribute entries and the (ASM specific) type\n * table entries of a class.\n *\n * @see JVMS 4.4\n * @see JVMS 4.7.23\n * @author Eric Bruneton\n */\nfinal class SymbolTable {\n /**\n * The ClassWriter to which this SymbolTable belongs. This is only used to get access to {@link\n * ClassWriter#getCommonSuperClass} and to serialize custom attributes with {@link\n * Attribute#write}.\n */\n final ClassWriter classWriter;\n /**\n * The ClassReader from which this SymbolTable was constructed, or {@literal null} if it was\n * constructed from scratch.\n */\n private final ClassReader sourceClassReader;\n /** The major version number of the class to which this symbol table belongs. */\n private int majorVersion;\n /** The internal name of the class to which this symbol table belongs. */\n private String className;\n /**\n * The total number of {@link Entry} instances in {@link #entries}. This includes entries that are\n * accessible (recursively) via {@link Entry#next}.\n */\n private int entryCount;\n /**\n * A hash set of all the entries in this SymbolTable (this includes the constant pool entries, the\n * bootstrap method entries and the type table entries). Each {@link Entry} instance is stored at\n * the array index given by its hash code modulo the array size. If several entries must be stored\n * at the same array index, they are linked together via their {@link Entry#next} field. The\n * factory methods of this class make sure that this table does not contain duplicated entries.\n */\n private Entry[] entries;\n /**\n * The number of constant pool items in {@link #constantPool}, plus 1. The first constant pool\n * item has index 1, and long and double items count for two items.\n */\n private int constantPoolCount;\n /**\n * The content of the ClassFile's constant_pool JVMS structure corresponding to this SymbolTable.\n * The ClassFile's constant_pool_count field is not included.\n */\n private ByteVector constantPool;\n /**\n * The number of bootstrap methods in {@link #bootstrapMethods}. Corresponds to the\n * BootstrapMethods_attribute's num_bootstrap_methods field value.\n */\n private int bootstrapMethodCount;\n /**\n * The content of the BootstrapMethods attribute 'bootstrap_methods' array corresponding to this\n * SymbolTable. Note that the first 6 bytes of the BootstrapMethods_attribute, and its\n * num_bootstrap_methods field, are not included.\n */\n private ByteVector bootstrapMethods;\n /**\n * The actual number of elements in {@link #typeTable}. These elements are stored from index 0 to\n * typeCount (excluded). The other array entries are empty.\n */\n private int typeCount;\n /**\n * An ASM specific type table used to temporarily store internal names that will not necessarily\n * be stored in the constant pool. This type table is used by the control flow and data flow\n * analysis algorithm used to compute stack map frames from scratch. This array stores {@link\n * Symbol#TYPE_TAG} and {@link Symbol#UNINITIALIZED_TYPE_TAG}) Symbol. The type symbol at index\n * {@code i} has its {@link Symbol#index} equal to {@code i} (and vice versa).\n */\n private Entry[] typeTable;\n\n /**\n * Constructs a new, empty SymbolTable for the given ClassWriter.\n *\n * @param classWriter a ClassWriter.\n */\n SymbolTable(final ClassWriter classWriter) {\n this.classWriter = classWriter;\n this.sourceClassReader = null;\n this.entries = new Entry[256];\n this.constantPoolCount = 1;\n this.constantPool = new ByteVector();\n }\n\n /**\n * Constructs a new SymbolTable for the given ClassWriter, initialized with the constant pool and\n * bootstrap methods of the given ClassReader.\n *\n * @param classWriter a ClassWriter.\n * @param classReader the ClassReader whose constant pool and bootstrap methods must be copied to\n * initialize the SymbolTable.\n */\n SymbolTable(final ClassWriter classWriter, final ClassReader classReader) {\n this.classWriter = classWriter;\n this.sourceClassReader = classReader;\n // Copy the constant pool binary content.\n byte[] inputBytes = classReader.classFileBuffer;\n int constantPoolOffset = classReader.getItem(1) - 1;\n int constantPoolLength = classReader.header - constantPoolOffset;\n constantPoolCount = classReader.getItemCount();\n constantPool = new ByteVector(constantPoolLength);\n constantPool.putByteArray(inputBytes, constantPoolOffset, constantPoolLength);\n // Add the constant pool items in the symbol table entries. Reserve enough space in 'entries' to\n // avoid too many hash set collisions (entries is not dynamically resized by the addConstant*\n // method calls below), and to account for bootstrap method entries.\n entries = new Entry[constantPoolCount * 2];\n char[] charBuffer = new char[classReader.getMaxStringLength()];\n boolean hasBootstrapMethods = false;\n int itemIndex = 1;\n while (itemIndex < constantPoolCount) {\n int itemOffset = classReader.getItem(itemIndex);\n int itemTag = inputBytes[itemOffset - 1];\n int nameAndTypeItemOffset;\n switch (itemTag) {\n case Symbol.CONSTANT_FIELDREF_TAG:\n case Symbol.CONSTANT_METHODREF_TAG:\n case Symbol.CONSTANT_INTERFACE_METHODREF_TAG:\n nameAndTypeItemOffset = classReader.getItem(classReader.readUnsignedShort(itemOffset + 2));\n addConstantMemberReference(itemIndex, itemTag, classReader.readClass(itemOffset, charBuffer), classReader.readUTF8(nameAndTypeItemOffset, charBuffer), classReader.readUTF8(nameAndTypeItemOffset + 2, charBuffer));\n break;\n case Symbol.CONSTANT_INTEGER_TAG:\n case Symbol.CONSTANT_FLOAT_TAG:\n addConstantIntegerOrFloat(itemIndex, itemTag, classReader.readInt(itemOffset));\n break;\n case Symbol.CONSTANT_NAME_AND_TYPE_TAG:\n addConstantNameAndType(itemIndex, classReader.readUTF8(itemOffset, charBuffer), classReader.readUTF8(itemOffset + 2, charBuffer));\n break;\n case Symbol.CONSTANT_LONG_TAG:\n case Symbol.CONSTANT_DOUBLE_TAG:\n addConstantLongOrDouble(itemIndex, itemTag, classReader.readLong(itemOffset));\n break;\n case Symbol.CONSTANT_UTF8_TAG:\n addConstantUtf8(itemIndex, classReader.readUtf(itemIndex, charBuffer));\n break;\n case Symbol.CONSTANT_METHOD_HANDLE_TAG:\n int memberRefItemOffset = classReader.getItem(classReader.readUnsignedShort(itemOffset + 1));\n nameAndTypeItemOffset = classReader.getItem(classReader.readUnsignedShort(memberRefItemOffset + 2));\n addConstantMethodHandle(itemIndex, classReader.readByte(itemOffset), classReader.readClass(memberRefItemOffset, charBuffer), classReader.readUTF8(nameAndTypeItemOffset, charBuffer), classReader.readUTF8(nameAndTypeItemOffset + 2, charBuffer));\n break;\n case Symbol.CONSTANT_DYNAMIC_TAG:\n case Symbol.CONSTANT_INVOKE_DYNAMIC_TAG:\n hasBootstrapMethods = true;\n nameAndTypeItemOffset = classReader.getItem(classReader.readUnsignedShort(itemOffset + 2));\n addConstantDynamicOrInvokeDynamicReference(itemTag, itemIndex, classReader.readUTF8(nameAndTypeItemOffset, charBuffer), classReader.readUTF8(nameAndTypeItemOffset + 2, charBuffer), classReader.readUnsignedShort(itemOffset));\n break;\n case Symbol.CONSTANT_STRING_TAG:\n case Symbol.CONSTANT_CLASS_TAG:\n case Symbol.CONSTANT_METHOD_TYPE_TAG:\n case Symbol.CONSTANT_MODULE_TAG:\n case Symbol.CONSTANT_PACKAGE_TAG:\n addConstantUtf8Reference(itemIndex, itemTag, classReader.readUTF8(itemOffset, charBuffer));\n break;\n default:\n throw new IllegalArgumentException();\n }\n itemIndex += (itemTag == Symbol.CONSTANT_LONG_TAG || itemTag == Symbol.CONSTANT_DOUBLE_TAG) ? 2 : 1;\n }\n // Copy the BootstrapMethods, if any.\n if (hasBootstrapMethods) {\n copyBootstrapMethods(classReader, charBuffer);\n }\n }\n\n /**\n * Read the BootstrapMethods 'bootstrap_methods' array binary content and add them as entries of\n * the SymbolTable.\n *\n * @param classReader the ClassReader whose bootstrap methods must be copied to initialize the\n * SymbolTable.\n * @param charBuffer a buffer used to read strings in the constant pool.\n */\n private void copyBootstrapMethods(final ClassReader classReader, final char[] charBuffer) {\n // Find attributOffset of the 'bootstrap_methods' array.\n byte[] inputBytes = classReader.classFileBuffer;\n int currentAttributeOffset = classReader.getFirstAttributeOffset();\n for (int i = classReader.readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) {\n String attributeName = classReader.readUTF8(currentAttributeOffset, charBuffer);\n if (Constants.BOOTSTRAP_METHODS.equals(attributeName)) {\n bootstrapMethodCount = classReader.readUnsignedShort(currentAttributeOffset + 6);\n break;\n }\n currentAttributeOffset += 6 + classReader.readInt(currentAttributeOffset + 2);\n }\n if (bootstrapMethodCount > 0) {\n // Compute the offset and the length of the BootstrapMethods 'bootstrap_methods' array.\n int bootstrapMethodsOffset = currentAttributeOffset + 8;\n int bootstrapMethodsLength = classReader.readInt(currentAttributeOffset + 2) - 2;\n bootstrapMethods = new ByteVector(bootstrapMethodsLength);\n bootstrapMethods.putByteArray(inputBytes, bootstrapMethodsOffset, bootstrapMethodsLength);\n // Add each bootstrap method in the symbol table entries.\n int currentOffset = bootstrapMethodsOffset;\n for (int i = 0; i < bootstrapMethodCount; i++) {\n int offset = currentOffset - bootstrapMethodsOffset;\n int bootstrapMethodRef = classReader.readUnsignedShort(currentOffset);\n currentOffset += 2;\n int numBootstrapArguments = classReader.readUnsignedShort(currentOffset);\n currentOffset += 2;\n int hashCode = classReader.readConst(bootstrapMethodRef, charBuffer).hashCode();\n while (numBootstrapArguments-- > 0) {\n int bootstrapArgument = classReader.readUnsignedShort(currentOffset);\n currentOffset += 2;\n hashCode ^= classReader.readConst(bootstrapArgument, charBuffer).hashCode();\n }\n add(new Entry(i, Symbol.BOOTSTRAP_METHOD_TAG, offset, hashCode & 0x7FFFFFFF));\n }\n }\n }\n\n /**\n * Returns the ClassReader from which this SymbolTable was constructed.\n *\n * @return the ClassReader from which this SymbolTable was constructed, or {@literal null} if it\n * was constructed from scratch.\n */\n ClassReader getSource() {\n return sourceClassReader;\n }\n\n /**\n * Returns the major version of the class to which this symbol table belongs.\n *\n * @return the major version of the class to which this symbol table belongs.\n */\n int getMajorVersion() {\n return majorVersion;\n }\n\n /**\n * Returns the internal name of the class to which this symbol table belongs.\n *\n * @return the internal name of the class to which this symbol table belongs.\n */\n String getClassName() {\n return className;\n }\n\n /**\n * Sets the major version and the name of the class to which this symbol table belongs. Also adds\n * the class name to the constant pool.\n *\n * @param majorVersion a major ClassFile version number.\n * @param className an internal class name.\n * @return the constant pool index of a new or already existing Symbol with the given class name.\n */\n int setMajorVersionAndClassName(final int majorVersion, final String className) {\n this.majorVersion = majorVersion;\n this.className = className;\n return addConstantClass(className).index;\n }\n\n /**\n * Returns the number of items in this symbol table's constant_pool array (plus 1).\n *\n * @return the number of items in this symbol table's constant_pool array (plus 1).\n */\n int getConstantPoolCount() {\n return constantPoolCount;\n }\n\n /**\n * Returns the length in bytes of this symbol table's constant_pool array.\n *\n * @return the length in bytes of this symbol table's constant_pool array.\n */\n int getConstantPoolLength() {\n return constantPool.length;\n }\n\n /**\n * Puts this symbol table's constant_pool array in the given ByteVector, preceded by the\n * constant_pool_count value.\n *\n * @param output where the JVMS ClassFile's constant_pool array must be put.\n */\n void putConstantPool(final ByteVector output) {\n output.putShort(constantPoolCount).putByteArray(constantPool.data, 0, constantPool.length);\n }\n\n /**\n * Returns the size in bytes of this symbol table's BootstrapMethods attribute. Also adds the\n * attribute name in the constant pool.\n *\n * @return the size in bytes of this symbol table's BootstrapMethods attribute.\n */\n int computeBootstrapMethodsSize() {\n if (bootstrapMethods != null) {\n addConstantUtf8(Constants.BOOTSTRAP_METHODS);\n return 8 + bootstrapMethods.length;\n } else {\n return 0;\n }\n }\n\n /**\n * Puts this symbol table's BootstrapMethods attribute in the given ByteVector. This includes the\n * 6 attribute header bytes and the num_bootstrap_methods value.\n *\n * @param output where the JVMS BootstrapMethods attribute must be put.\n */\n void putBootstrapMethods(final ByteVector output) {\n if (bootstrapMethods != null) {\n output.putShort(addConstantUtf8(Constants.BOOTSTRAP_METHODS)).putInt(bootstrapMethods.length + 2).putShort(bootstrapMethodCount).putByteArray(bootstrapMethods.data, 0, bootstrapMethods.length);\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Generic symbol table entries management.\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the list of entries which can potentially have the given hash code.\n *\n * @param hashCode a {@link Entry#hashCode} value.\n * @return the list of entries which can potentially have the given hash code. The list is stored\n * via the {@link Entry#next} field.\n */\n private Entry get(final int hashCode) {\n return entries[hashCode % entries.length];\n }\n\n /**\n * Puts the given entry in the {@link #entries} hash set. This method does not check\n * whether {@link #entries} already contains a similar entry or not. {@link #entries} is resized\n * if necessary to avoid hash collisions (multiple entries needing to be stored at the same {@link\n * #entries} array index) as much as possible, with reasonable memory usage.\n *\n * @param entry an Entry (which must not already be contained in {@link #entries}).\n * @return the given entry\n */\n private Entry put(final Entry entry) {\n if (entryCount > (entries.length * 3) / 4) {\n int currentCapacity = entries.length;\n int newCapacity = currentCapacity * 2 + 1;\n Entry[] newEntries = new Entry[newCapacity];\n for (int i = currentCapacity - 1; i >= 0; --i) {\n Entry currentEntry = entries[i];\n while (currentEntry != null) {\n int newCurrentEntryIndex = currentEntry.hashCode % newCapacity;\n Entry nextEntry = currentEntry.next;\n currentEntry.next = newEntries[newCurrentEntryIndex];\n newEntries[newCurrentEntryIndex] = currentEntry;\n currentEntry = nextEntry;\n }\n }\n entries = newEntries;\n }\n entryCount++;\n int index = entry.hashCode % entries.length;\n entry.next = entries[index];\n return entries[index] = entry;\n }\n\n /**\n * Adds the given entry in the {@link #entries} hash set. This method does not check\n * whether {@link #entries} already contains a similar entry or not, and does not resize\n * {@link #entries} if necessary.\n *\n * @param entry an Entry (which must not already be contained in {@link #entries}).\n */\n private void add(final Entry entry) {\n entryCount++;\n int index = entry.hashCode % entries.length;\n entry.next = entries[index];\n entries[index] = entry;\n }\n // -----------------------------------------------------------------------------------------------\n // Constant pool entries management.\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Adds a number or string constant to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value the value of the constant to be added to the constant pool. This parameter must be\n * an {@link Integer}, {@link Byte}, {@link Character}, {@link Short}, {@link Boolean}, {@link\n * Float}, {@link Long}, {@link Double}, {@link String}, {@link Type} or {@link Handle}.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstant(final Object value) {\n if (value instanceof Integer) {\n return addConstantInteger(((Integer) value).intValue());\n } else if (value instanceof Byte) {\n return addConstantInteger(((Byte) value).intValue());\n } else if (value instanceof Character) {\n return addConstantInteger(((Character) value).charValue());\n } else if (value instanceof Short) {\n return addConstantInteger(((Short) value).intValue());\n } else if (value instanceof Boolean) {\n return addConstantInteger(((Boolean) value).booleanValue() ? 1 : 0);\n } else if (value instanceof Float) {\n return addConstantFloat(((Float) value).floatValue());\n } else if (value instanceof Long) {\n return addConstantLong(((Long) value).longValue());\n } else if (value instanceof Double) {\n return addConstantDouble(((Double) value).doubleValue());\n } else if (value instanceof String) {\n return addConstantString((String) value);\n } else if (value instanceof Type) {\n Type type = (Type) value;\n int typeSort = type.getSort();\n if (typeSort == Type.OBJECT) {\n return addConstantClass(type.getInternalName());\n } else if (typeSort == Type.METHOD) {\n return addConstantMethodType(type.getDescriptor());\n } else { // type is a primitive or array type.\n return addConstantClass(type.getDescriptor());\n }\n } else if (value instanceof Handle) {\n Handle handle = (Handle) value;\n return addConstantMethodHandle(handle.getTag(), handle.getOwner(), handle.getName(), handle.getDesc(), handle.isInterface());\n } else if (value instanceof ConstantDynamic) {\n ConstantDynamic constantDynamic = (ConstantDynamic) value;\n return addConstantDynamic(constantDynamic.getName(), constantDynamic.getDescriptor(), constantDynamic.getBootstrapMethod(), constantDynamic.getBootstrapMethodArgumentsUnsafe());\n } else {\n throw new IllegalArgumentException(\"value \" + value);\n }\n }\n\n /**\n * Adds a CONSTANT_Class_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value the internal name of a class.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantClass(final String value) {\n return addConstantUtf8Reference(Symbol.CONSTANT_CLASS_TAG, value);\n }\n\n /**\n * Adds a CONSTANT_Fieldref_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param owner the internal name of a class.\n * @param name a field name.\n * @param descriptor a field descriptor.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantFieldref(final String owner, final String name, final String descriptor) {\n return addConstantMemberReference(Symbol.CONSTANT_FIELDREF_TAG, owner, name, descriptor);\n }\n\n /**\n * Adds a CONSTANT_Methodref_info or CONSTANT_InterfaceMethodref_info to the constant pool of this\n * symbol table. Does nothing if the constant pool already contains a similar item.\n *\n * @param owner the internal name of a class.\n * @param name a method name.\n * @param descriptor a method descriptor.\n * @param isInterface whether owner is an interface or not.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantMethodref(final String owner, final String name, final String descriptor, final boolean isInterface) {\n int tag = isInterface ? Symbol.CONSTANT_INTERFACE_METHODREF_TAG : Symbol.CONSTANT_METHODREF_TAG;\n return addConstantMemberReference(tag, owner, name, descriptor);\n }\n\n /**\n * Adds a CONSTANT_Fieldref_info, CONSTANT_Methodref_info or CONSTANT_InterfaceMethodref_info to\n * the constant pool of this symbol table. Does nothing if the constant pool already contains a\n * similar item.\n *\n * @param tag one of {@link Symbol#CONSTANT_FIELDREF_TAG}, {@link Symbol#CONSTANT_METHODREF_TAG}\n * or {@link Symbol#CONSTANT_INTERFACE_METHODREF_TAG}.\n * @param owner the internal name of a class.\n * @param name a field or method name.\n * @param descriptor a field or method descriptor.\n * @return a new or already existing Symbol with the given value.\n */\n private Entry addConstantMemberReference(final int tag, final String owner, final String name, final String descriptor) {\n int hashCode = hash(tag, owner, name, descriptor);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.owner.equals(owner) && entry.name.equals(name) && entry.value.equals(descriptor)) {\n return entry;\n }\n entry = entry.next;\n }\n constantPool.put122(tag, addConstantClass(owner).index, addConstantNameAndType(name, descriptor));\n return put(new Entry(constantPoolCount++, tag, owner, name, descriptor, 0, hashCode));\n }\n\n /**\n * Adds a new CONSTANT_Fieldref_info, CONSTANT_Methodref_info or CONSTANT_InterfaceMethodref_info\n * to the constant pool of this symbol table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param tag one of {@link Symbol#CONSTANT_FIELDREF_TAG}, {@link Symbol#CONSTANT_METHODREF_TAG}\n * or {@link Symbol#CONSTANT_INTERFACE_METHODREF_TAG}.\n * @param owner the internal name of a class.\n * @param name a field or method name.\n * @param descriptor a field or method descriptor.\n */\n private void addConstantMemberReference(final int index, final int tag, final String owner, final String name, final String descriptor) {\n add(new Entry(index, tag, owner, name, descriptor, 0, hash(tag, owner, name, descriptor)));\n }\n\n /**\n * Adds a CONSTANT_String_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value a string.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantString(final String value) {\n return addConstantUtf8Reference(Symbol.CONSTANT_STRING_TAG, value);\n }\n\n /**\n * Adds a CONSTANT_Integer_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value an int.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantInteger(final int value) {\n return addConstantIntegerOrFloat(Symbol.CONSTANT_INTEGER_TAG, value);\n }\n\n /**\n * Adds a CONSTANT_Float_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value a float.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantFloat(final float value) {\n return addConstantIntegerOrFloat(Symbol.CONSTANT_FLOAT_TAG, Float.floatToRawIntBits(value));\n }\n\n /**\n * Adds a CONSTANT_Integer_info or CONSTANT_Float_info to the constant pool of this symbol table.\n * Does nothing if the constant pool already contains a similar item.\n *\n * @param tag one of {@link Symbol#CONSTANT_INTEGER_TAG} or {@link Symbol#CONSTANT_FLOAT_TAG}.\n * @param value an int or float.\n * @return a constant pool constant with the given tag and primitive values.\n */\n private Symbol addConstantIntegerOrFloat(final int tag, final int value) {\n int hashCode = hash(tag, value);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.data == value) {\n return entry;\n }\n entry = entry.next;\n }\n constantPool.putByte(tag).putInt(value);\n return put(new Entry(constantPoolCount++, tag, value, hashCode));\n }\n\n /**\n * Adds a new CONSTANT_Integer_info or CONSTANT_Float_info to the constant pool of this symbol\n * table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param tag one of {@link Symbol#CONSTANT_INTEGER_TAG} or {@link Symbol#CONSTANT_FLOAT_TAG}.\n * @param value an int or float.\n */\n private void addConstantIntegerOrFloat(final int index, final int tag, final int value) {\n add(new Entry(index, tag, value, hash(tag, value)));\n }\n\n /**\n * Adds a CONSTANT_Long_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value a long.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantLong(final long value) {\n return addConstantLongOrDouble(Symbol.CONSTANT_LONG_TAG, value);\n }\n\n /**\n * Adds a CONSTANT_Double_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value a double.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantDouble(final double value) {\n return addConstantLongOrDouble(Symbol.CONSTANT_DOUBLE_TAG, Double.doubleToRawLongBits(value));\n }\n\n /**\n * Adds a CONSTANT_Long_info or CONSTANT_Double_info to the constant pool of this symbol table.\n * Does nothing if the constant pool already contains a similar item.\n *\n * @param tag one of {@link Symbol#CONSTANT_LONG_TAG} or {@link Symbol#CONSTANT_DOUBLE_TAG}.\n * @param value a long or double.\n * @return a constant pool constant with the given tag and primitive values.\n */\n private Symbol addConstantLongOrDouble(final int tag, final long value) {\n int hashCode = hash(tag, value);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.data == value) {\n return entry;\n }\n entry = entry.next;\n }\n int index = constantPoolCount;\n constantPool.putByte(tag).putLong(value);\n constantPoolCount += 2;\n return put(new Entry(index, tag, value, hashCode));\n }\n\n /**\n * Adds a new CONSTANT_Long_info or CONSTANT_Double_info to the constant pool of this symbol\n * table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param tag one of {@link Symbol#CONSTANT_LONG_TAG} or {@link Symbol#CONSTANT_DOUBLE_TAG}.\n * @param value a long or double.\n */\n private void addConstantLongOrDouble(final int index, final int tag, final long value) {\n add(new Entry(index, tag, value, hash(tag, value)));\n }\n\n /**\n * Adds a CONSTANT_NameAndType_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param name a field or method name.\n * @param descriptor a field or method descriptor.\n * @return a new or already existing Symbol with the given value.\n */\n int addConstantNameAndType(final String name, final String descriptor) {\n final int tag = Symbol.CONSTANT_NAME_AND_TYPE_TAG;\n int hashCode = hash(tag, name, descriptor);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.name.equals(name) && entry.value.equals(descriptor)) {\n return entry.index;\n }\n entry = entry.next;\n }\n constantPool.put122(tag, addConstantUtf8(name), addConstantUtf8(descriptor));\n return put(new Entry(constantPoolCount++, tag, name, descriptor, hashCode)).index;\n }\n\n /**\n * Adds a new CONSTANT_NameAndType_info to the constant pool of this symbol table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param name a field or method name.\n * @param descriptor a field or method descriptor.\n */\n private void addConstantNameAndType(final int index, final String name, final String descriptor) {\n final int tag = Symbol.CONSTANT_NAME_AND_TYPE_TAG;\n add(new Entry(index, tag, name, descriptor, hash(tag, name, descriptor)));\n }\n\n /**\n * Adds a CONSTANT_Utf8_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value a string.\n * @return a new or already existing Symbol with the given value.\n */\n int addConstantUtf8(final String value) {\n int hashCode = hash(Symbol.CONSTANT_UTF8_TAG, value);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == Symbol.CONSTANT_UTF8_TAG && entry.hashCode == hashCode && entry.value.equals(value)) {\n return entry.index;\n }\n entry = entry.next;\n }\n constantPool.putByte(Symbol.CONSTANT_UTF8_TAG).putUTF8(value);\n return put(new Entry(constantPoolCount++, Symbol.CONSTANT_UTF8_TAG, value, hashCode)).index;\n }\n\n /**\n * Adds a new CONSTANT_String_info to the constant pool of this symbol table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param value a string.\n */\n private void addConstantUtf8(final int index, final String value) {\n add(new Entry(index, Symbol.CONSTANT_UTF8_TAG, value, hash(Symbol.CONSTANT_UTF8_TAG, value)));\n }\n\n /**\n * Adds a CONSTANT_MethodHandle_info to the constant pool of this symbol table. Does nothing if\n * the constant pool already contains a similar item.\n *\n * @param referenceKind one of {@link Opcodes#H_GETFIELD}, {@link Opcodes#H_GETSTATIC}, {@link\n * Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL}, {@link\n * Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, {@link\n * Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}.\n * @param owner the internal name of a class of interface.\n * @param name a field or method name.\n * @param descriptor a field or method descriptor.\n * @param isInterface whether owner is an interface or not.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantMethodHandle(final int referenceKind, final String owner, final String name, final String descriptor, final boolean isInterface) {\n final int tag = Symbol.CONSTANT_METHOD_HANDLE_TAG;\n // Note that we don't need to include isInterface in the hash computation, because it is\n // redundant with owner (we can't have the same owner with different isInterface values).\n int hashCode = hash(tag, owner, name, descriptor, referenceKind);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.data == referenceKind && entry.owner.equals(owner) && entry.name.equals(name) && entry.value.equals(descriptor)) {\n return entry;\n }\n entry = entry.next;\n }\n if (referenceKind <= Opcodes.H_PUTSTATIC) {\n constantPool.put112(tag, referenceKind, addConstantFieldref(owner, name, descriptor).index);\n } else {\n constantPool.put112(tag, referenceKind, addConstantMethodref(owner, name, descriptor, isInterface).index);\n }\n return put(new Entry(constantPoolCount++, tag, owner, name, descriptor, referenceKind, hashCode));\n }\n\n /**\n * Adds a new CONSTANT_MethodHandle_info to the constant pool of this symbol table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param referenceKind one of {@link Opcodes#H_GETFIELD}, {@link Opcodes#H_GETSTATIC}, {@link\n * Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL}, {@link\n * Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, {@link\n * Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}.\n * @param owner the internal name of a class of interface.\n * @param name a field or method name.\n * @param descriptor a field or method descriptor.\n */\n private void addConstantMethodHandle(final int index, final int referenceKind, final String owner, final String name, final String descriptor) {\n final int tag = Symbol.CONSTANT_METHOD_HANDLE_TAG;\n int hashCode = hash(tag, owner, name, descriptor, referenceKind);\n add(new Entry(index, tag, owner, name, descriptor, referenceKind, hashCode));\n }\n\n /**\n * Adds a CONSTANT_MethodType_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param methodDescriptor a method descriptor.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantMethodType(final String methodDescriptor) {\n return addConstantUtf8Reference(Symbol.CONSTANT_METHOD_TYPE_TAG, methodDescriptor);\n }\n\n /**\n * Adds a CONSTANT_Dynamic_info to the constant pool of this symbol table. Also adds the related\n * bootstrap method to the BootstrapMethods of this symbol table. Does nothing if the constant\n * pool already contains a similar item.\n *\n * @param name a method name.\n * @param descriptor a field descriptor.\n * @param bootstrapMethodHandle a bootstrap method handle.\n * @param bootstrapMethodArguments the bootstrap method arguments.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantDynamic(final String name, final String descriptor, final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) {\n Symbol bootstrapMethod = addBootstrapMethod(bootstrapMethodHandle, bootstrapMethodArguments);\n return addConstantDynamicOrInvokeDynamicReference(Symbol.CONSTANT_DYNAMIC_TAG, name, descriptor, bootstrapMethod.index);\n }\n\n /**\n * Adds a CONSTANT_InvokeDynamic_info to the constant pool of this symbol table. Also adds the\n * related bootstrap method to the BootstrapMethods of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param name a method name.\n * @param descriptor a method descriptor.\n * @param bootstrapMethodHandle a bootstrap method handle.\n * @param bootstrapMethodArguments the bootstrap method arguments.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantInvokeDynamic(final String name, final String descriptor, final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) {\n Symbol bootstrapMethod = addBootstrapMethod(bootstrapMethodHandle, bootstrapMethodArguments);\n return addConstantDynamicOrInvokeDynamicReference(Symbol.CONSTANT_INVOKE_DYNAMIC_TAG, name, descriptor, bootstrapMethod.index);\n }\n\n /**\n * Adds a CONSTANT_Dynamic or a CONSTANT_InvokeDynamic_info to the constant pool of this symbol\n * table. Does nothing if the constant pool already contains a similar item.\n *\n * @param tag one of {@link Symbol#CONSTANT_DYNAMIC_TAG} or {@link\n * Symbol#CONSTANT_INVOKE_DYNAMIC_TAG}.\n * @param name a method name.\n * @param descriptor a field descriptor for CONSTANT_DYNAMIC_TAG) or a method descriptor for\n * CONSTANT_INVOKE_DYNAMIC_TAG.\n * @param bootstrapMethodIndex the index of a bootstrap method in the BootstrapMethods attribute.\n * @return a new or already existing Symbol with the given value.\n */\n private Symbol addConstantDynamicOrInvokeDynamicReference(final int tag, final String name, final String descriptor, final int bootstrapMethodIndex) {\n int hashCode = hash(tag, name, descriptor, bootstrapMethodIndex);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.data == bootstrapMethodIndex && entry.name.equals(name) && entry.value.equals(descriptor)) {\n return entry;\n }\n entry = entry.next;\n }\n constantPool.put122(tag, bootstrapMethodIndex, addConstantNameAndType(name, descriptor));\n return put(new Entry(constantPoolCount++, tag, null, name, descriptor, bootstrapMethodIndex, hashCode));\n }\n\n /**\n * Adds a new CONSTANT_Dynamic_info or CONSTANT_InvokeDynamic_info to the constant pool of this\n * symbol table.\n *\n * @param tag one of {@link Symbol#CONSTANT_DYNAMIC_TAG} or {@link\n * Symbol#CONSTANT_INVOKE_DYNAMIC_TAG}.\n * @param index the constant pool index of the new Symbol.\n * @param name a method name.\n * @param descriptor a field descriptor for CONSTANT_DYNAMIC_TAG or a method descriptor for\n * CONSTANT_INVOKE_DYNAMIC_TAG.\n * @param bootstrapMethodIndex the index of a bootstrap method in the BootstrapMethods attribute.\n */\n private void addConstantDynamicOrInvokeDynamicReference(final int tag, final int index, final String name, final String descriptor, final int bootstrapMethodIndex) {\n int hashCode = hash(tag, name, descriptor, bootstrapMethodIndex);\n add(new Entry(index, tag, null, name, descriptor, bootstrapMethodIndex, hashCode));\n }\n\n /**\n * Adds a CONSTANT_Module_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param moduleName a fully qualified name (using dots) of a module.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantModule(final String moduleName) {\n return addConstantUtf8Reference(Symbol.CONSTANT_MODULE_TAG, moduleName);\n }\n\n /**\n * Adds a CONSTANT_Package_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param packageName the internal name of a package.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantPackage(final String packageName) {\n return addConstantUtf8Reference(Symbol.CONSTANT_PACKAGE_TAG, packageName);\n }\n\n /**\n * Adds a CONSTANT_Class_info, CONSTANT_String_info, CONSTANT_MethodType_info,\n * CONSTANT_Module_info or CONSTANT_Package_info to the constant pool of this symbol table. Does\n * nothing if the constant pool already contains a similar item.\n *\n * @param tag one of {@link Symbol#CONSTANT_CLASS_TAG}, {@link Symbol#CONSTANT_STRING_TAG}, {@link\n * Symbol#CONSTANT_METHOD_TYPE_TAG}, {@link Symbol#CONSTANT_MODULE_TAG} or {@link\n * Symbol#CONSTANT_PACKAGE_TAG}.\n * @param value an internal class name, an arbitrary string, a method descriptor, a module or a\n * package name, depending on tag.\n * @return a new or already existing Symbol with the given value.\n */\n private Symbol addConstantUtf8Reference(final int tag, final String value) {\n int hashCode = hash(tag, value);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.value.equals(value)) {\n return entry;\n }\n entry = entry.next;\n }\n constantPool.put12(tag, addConstantUtf8(value));\n return put(new Entry(constantPoolCount++, tag, value, hashCode));\n }\n\n /**\n * Adds a new CONSTANT_Class_info, CONSTANT_String_info, CONSTANT_MethodType_info,\n * CONSTANT_Module_info or CONSTANT_Package_info to the constant pool of this symbol table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param tag one of {@link Symbol#CONSTANT_CLASS_TAG}, {@link Symbol#CONSTANT_STRING_TAG}, {@link\n * Symbol#CONSTANT_METHOD_TYPE_TAG}, {@link Symbol#CONSTANT_MODULE_TAG} or {@link\n * Symbol#CONSTANT_PACKAGE_TAG}.\n * @param value an internal class name, an arbitrary string, a method descriptor, a module or a\n * package name, depending on tag.\n */\n private void addConstantUtf8Reference(final int index, final int tag, final String value) {\n add(new Entry(index, tag, value, hash(tag, value)));\n }\n // -----------------------------------------------------------------------------------------------\n // Bootstrap method entries management.\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Adds a bootstrap method to the BootstrapMethods attribute of this symbol table. Does nothing if\n * the BootstrapMethods already contains a similar bootstrap method.\n *\n * @param bootstrapMethodHandle a bootstrap method handle.\n * @param bootstrapMethodArguments the bootstrap method arguments.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addBootstrapMethod(final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) {\n ByteVector bootstrapMethodsAttribute = bootstrapMethods;\n if (bootstrapMethodsAttribute == null) {\n bootstrapMethodsAttribute = bootstrapMethods = new ByteVector();\n }\n // The bootstrap method arguments can be Constant_Dynamic values, which reference other\n // bootstrap methods. We must therefore add the bootstrap method arguments to the constant pool\n // and BootstrapMethods attribute first, so that the BootstrapMethods attribute is not modified\n // while adding the given bootstrap method to it, in the rest of this method.\n for (Object bootstrapMethodArgument : bootstrapMethodArguments) {\n addConstant(bootstrapMethodArgument);\n }\n // Write the bootstrap method in the BootstrapMethods table. This is necessary to be able to\n // compare it with existing ones, and will be reverted below if there is already a similar\n // bootstrap method.\n int bootstrapMethodOffset = bootstrapMethodsAttribute.length;\n bootstrapMethodsAttribute.putShort(addConstantMethodHandle(bootstrapMethodHandle.getTag(), bootstrapMethodHandle.getOwner(), bootstrapMethodHandle.getName(), bootstrapMethodHandle.getDesc(), bootstrapMethodHandle.isInterface()).index);\n int numBootstrapArguments = bootstrapMethodArguments.length;\n bootstrapMethodsAttribute.putShort(numBootstrapArguments);\n for (Object bootstrapMethodArgument : bootstrapMethodArguments) {\n bootstrapMethodsAttribute.putShort(addConstant(bootstrapMethodArgument).index);\n }\n // Compute the length and the hash code of the bootstrap method.\n int bootstrapMethodlength = bootstrapMethodsAttribute.length - bootstrapMethodOffset;\n int hashCode = bootstrapMethodHandle.hashCode();\n for (Object bootstrapMethodArgument : bootstrapMethodArguments) {\n hashCode ^= bootstrapMethodArgument.hashCode();\n }\n hashCode &= 0x7FFFFFFF;\n // Add the bootstrap method to the symbol table or revert the above changes.\n return addBootstrapMethod(bootstrapMethodOffset, bootstrapMethodlength, hashCode);\n }\n\n /**\n * Adds a bootstrap method to the BootstrapMethods attribute of this symbol table. Does nothing if\n * the BootstrapMethods already contains a similar bootstrap method (more precisely, reverts the\n * content of {@link #bootstrapMethods} to remove the last, duplicate bootstrap method).\n *\n * @param offset the offset of the last bootstrap method in {@link #bootstrapMethods}, in bytes.\n * @param length the length of this bootstrap method in {@link #bootstrapMethods}, in bytes.\n * @param hashCode the hash code of this bootstrap method.\n * @return a new or already existing Symbol with the given value.\n */\n private Symbol addBootstrapMethod(final int offset, final int length, final int hashCode) {\n final byte[] bootstrapMethodsData = bootstrapMethods.data;\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == Symbol.BOOTSTRAP_METHOD_TAG && entry.hashCode == hashCode) {\n int otherOffset = (int) entry.data;\n boolean isSameBootstrapMethod = true;\n for (int i = 0; i < length; ++i) {\n if (bootstrapMethodsData[offset + i] != bootstrapMethodsData[otherOffset + i]) {\n isSameBootstrapMethod = false;\n break;\n }\n }\n if (isSameBootstrapMethod) {\n bootstrapMethods.length = offset; // Revert to old position.\n return entry;\n }\n }\n entry = entry.next;\n }\n return put(new Entry(bootstrapMethodCount++, Symbol.BOOTSTRAP_METHOD_TAG, offset, hashCode));\n }\n // -----------------------------------------------------------------------------------------------\n // Type table entries management.\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the type table element whose index is given.\n *\n * @param typeIndex a type table index.\n * @return the type table element whose index is given.\n */\n Symbol getType(final int typeIndex) {\n return typeTable[typeIndex];\n }\n\n /**\n * Adds a type in the type table of this symbol table. Does nothing if the type table already\n * contains a similar type.\n *\n * @param value an internal class name.\n * @return the index of a new or already existing type Symbol with the given value.\n */\n int addType(final String value) {\n int hashCode = hash(Symbol.TYPE_TAG, value);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == Symbol.TYPE_TAG && entry.hashCode == hashCode && entry.value.equals(value)) {\n return entry.index;\n }\n entry = entry.next;\n }\n return addTypeInternal(new Entry(typeCount, Symbol.TYPE_TAG, value, hashCode));\n }\n\n /**\n * Adds an {@link Frame#ITEM_UNINITIALIZED} type in the type table of this symbol table. Does\n * nothing if the type table already contains a similar type.\n *\n * @param value an internal class name.\n * @param bytecodeOffset the bytecode offset of the NEW instruction that created this {@link\n * Frame#ITEM_UNINITIALIZED} type value.\n * @return the index of a new or already existing type Symbol with the given value.\n */\n int addUninitializedType(final String value, final int bytecodeOffset) {\n int hashCode = hash(Symbol.UNINITIALIZED_TYPE_TAG, value, bytecodeOffset);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == Symbol.UNINITIALIZED_TYPE_TAG && entry.hashCode == hashCode && entry.data == bytecodeOffset && entry.value.equals(value)) {\n return entry.index;\n }\n entry = entry.next;\n }\n return addTypeInternal(new Entry(typeCount, Symbol.UNINITIALIZED_TYPE_TAG, value, bytecodeOffset, hashCode));\n }\n\n /**\n * Adds a merged type in the type table of this symbol table. Does nothing if the type table\n * already contains a similar type.\n *\n * @param typeTableIndex1 a {@link Symbol#TYPE_TAG} type, specified by its index in the type\n * table.\n * @param typeTableIndex2 another {@link Symbol#TYPE_TAG} type, specified by its index in the type\n * table.\n * @return the index of a new or already existing {@link Symbol#TYPE_TAG} type Symbol,\n * corresponding to the common super class of the given types.\n */\n int addMergedType(final int typeTableIndex1, final int typeTableIndex2) {\n long data = typeTableIndex1 < typeTableIndex2 ? typeTableIndex1 | (((long) typeTableIndex2) << 32) : typeTableIndex2 | (((long) typeTableIndex1) << 32);\n int hashCode = hash(Symbol.MERGED_TYPE_TAG, typeTableIndex1 + typeTableIndex2);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == Symbol.MERGED_TYPE_TAG && entry.hashCode == hashCode && entry.data == data) {\n return entry.info;\n }\n entry = entry.next;\n }\n String type1 = typeTable[typeTableIndex1].value;\n String type2 = typeTable[typeTableIndex2].value;\n int commonSuperTypeIndex = addType(classWriter.getCommonSuperClass(type1, type2));\n put(new Entry(typeCount, Symbol.MERGED_TYPE_TAG, data, hashCode)).info = commonSuperTypeIndex;\n return commonSuperTypeIndex;\n }\n\n /**\n * Adds the given type Symbol to {@link #typeTable}.\n *\n * @param entry a {@link Symbol#TYPE_TAG} or {@link Symbol#UNINITIALIZED_TYPE_TAG} type symbol.\n * The index of this Symbol must be equal to the current value of {@link #typeCount}.\n * @return the index in {@link #typeTable} where the given type was added, which is also equal to\n * entry's index by hypothesis.\n */\n private int addTypeInternal(final Entry entry) {\n if (typeTable == null) {\n typeTable = new Entry[16];\n }\n if (typeCount == typeTable.length) {\n Entry[] newTypeTable = new Entry[2 * typeTable.length];\n System.arraycopy(typeTable, 0, newTypeTable, 0, typeTable.length);\n typeTable = newTypeTable;\n }\n typeTable[typeCount++] = entry;\n return put(entry).index;\n }\n // -----------------------------------------------------------------------------------------------\n // Static helper methods to compute hash codes.\n // -----------------------------------------------------------------------------------------------\n\n private static int hash(final int tag, final int value) {\n return 0x7FFFFFFF & (tag + value);\n }\n\n private static int hash(final int tag, final long value) {\n return 0x7FFFFFFF & (tag + (int) value + (int) (value >>> 32));\n }\n\n private static int hash(final int tag, final String value) {\n return 0x7FFFFFFF & (tag + value.hashCode());\n }\n\n private static int hash(final int tag, final String value1, final int value2) {\n return 0x7FFFFFFF & (tag + value1.hashCode() + value2);\n }\n\n private static int hash(final int tag, final String value1, final String value2) {\n return 0x7FFFFFFF & (tag + value1.hashCode() * value2.hashCode());\n }\n\n private static int hash(final int tag, final String value1, final String value2, final int value3) {\n return 0x7FFFFFFF & (tag + value1.hashCode() * value2.hashCode() * (value3 + 1));\n }\n\n private static int hash(final int tag, final String value1, final String value2, final String value3) {\n return 0x7FFFFFFF & (tag + value1.hashCode() * value2.hashCode() * value3.hashCode());\n }\n\n private static int hash(final int tag, final String value1, final String value2, final String value3, final int value4) {\n return 0x7FFFFFFF & (tag + value1.hashCode() * value2.hashCode() * value3.hashCode() * value4);\n }\n\n /**\n * An entry of a SymbolTable. This concrete and private subclass of {@link Symbol} adds two fields\n * which are only used inside SymbolTable, to implement hash sets of symbols (in order to avoid\n * duplicate symbols). See {@link #entries}.\n *\n * @author Eric Bruneton\n */\n private static class Entry extends Symbol {\n /** The hash code of this entry. */\n final int hashCode;\n /**\n * Another entry (and so on recursively) having the same hash code (modulo the size of {@link\n * #entries}) as this one.\n */\n Entry next;\n\n Entry(final int index, final int tag, final String owner, final String name, final String value, final long data, final int hashCode) {\n super(index, tag, owner, name, value, data);\n this.hashCode = hashCode;\n }\n\n Entry(final int index, final int tag, final String value, final int hashCode) {\n super(index, tag, /* owner = */ null, /* name = */ null, value, /* data = */ 0);\n this.hashCode = hashCode;\n }\n\n Entry(final int index, final int tag, final String value, final long data, final int hashCode) {\n super(index, tag, /* owner = */ null, /* name = */ null, value, data);\n this.hashCode = hashCode;\n }\n\n Entry(final int index, final int tag, final String name, final String value, final int hashCode) {\n super(index, tag, /* owner = */ null, name, value, /* data = */ 0);\n this.hashCode = hashCode;\n }\n\n Entry(final int index, final int tag, final long data, final int hashCode) {\n super(index, tag, /* owner = */ null, /* name = */ null, /* value = */ null, data);\n this.hashCode = hashCode;\n }\n }\n}\n", "file_name": "SymbolTable.java", "human_label": "Add a new type entry of the given value into the type table of this symbol table. Does nothing if the type table already contains a similar type. Return the index of the type entry in the symbol table.", "level": "project_runnable", "lineno": "1002", "name": "addType", "oracle_context": "{ \"apis\" : \"[hash, get, equals, addTypeInternal, Entry]\", \"classes\" : \"[Entry, Symbol]\", \"vars\" : \"[TYPE_TAG, tag, index, next, typeCount]\" }", "package": "net.hasor.utils.asm", "project": "hasor-master" }, { "_id": "636766821a6d9265ec0174b6", "all_context": "{ \"class_level\" : \"import java.lang.ref.Reference;\\nimport java.lang.ref.WeakReference;\\nimport java.lang.reflect.Array;\\nimport java.lang.reflect.GenericArrayType;\\nimport java.lang.reflect.ParameterizedType;\\nimport java.lang.reflect.Type;\\nimport java.lang.reflect.TypeVariable;\\nimport java.util.Collections;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.WeakHashMap;\\nMap,Reference,Type>>> typeVariableCache;\\nboolean cacheEnabled;\\nTypeResolver();\\nUnknown();\\ndisableCache();\\nresolveArgument(Class initialType,Class targetType);\\nresolveArgument(Type genericType,Class targetType);\\nresolveArguments(Class initialType,Class targetType);\\nresolveArguments(Type genericType,Class targetType);\\nresolveGenericType(Type initialType,Class targetType);\\nresolveClass(Type genericType,Class targetType);\\ngetTypeVariableMap(Class targetType);\\nbuildTypeVariableMap(Type[] types,Map map);\\nbuildTypeVariableMap(ParameterizedType type,Map typeVariableMap);\\nresolveBound(TypeVariable typeVariable);\\nenableCache();\\n\", \"repo_level\" : \"\" }", "class_name": "TypeResolver", "code": "public static Class[] resolveArguments(Type genericType,Class targetType){\n Class[] result=null;\n if (genericType instanceof ParameterizedType) {\n ParameterizedType paramType=(ParameterizedType)genericType;\n Type[] arguments=paramType.getActualTypeArguments();\n result=new Class[arguments.length];\n for (int i=0; i < arguments.length; i++) result[i]=resolveClass(arguments[i],targetType);\n }\n else if (genericType instanceof TypeVariable) {\n result=new Class[1];\n result[0]=resolveClass(genericType,targetType);\n }\n return result;\n}\n", "docstring": "/** \n * Resolves the arguments for the {@code genericType} using the type variable information for the{@code targetType}. Returns {@code null} if {@code genericType} is not parameterized or ifarguments cannot be resolved.\n */\n", "end_lineno": "158", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n/**\n * Copyright 2002-2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This class is from https://github.com/jhalterman/typetools\n */\npackage org.atmosphere.config.managed;\n\nimport java.lang.ref.Reference;\nimport java.lang.ref.WeakReference;\nimport java.lang.reflect.Array;\nimport java.lang.reflect.GenericArrayType;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.lang.reflect.TypeVariable;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.WeakHashMap;\n\n/**\n * Enhanced type resolution utilities. Based on org.springframework.core.GenericTypeResolver.\n *\n * @author Jonathan Halterman\n */\npublic final class TypeResolver {\n private TypeResolver() {\n }\n\n /** An unknown type. */\n public static final class Unknown {\n private Unknown() {\n }\n }\n\n /** Cache of type variable/argument pairs */\n private static final Map, Reference, Type>>> typeVariableCache = Collections.synchronizedMap(new WeakHashMap<>());\n private static boolean cacheEnabled = true;\n\n /**\n * Enables the internal caching of TypeVariables.\n */\n public static void enableCache() {\n cacheEnabled = true;\n }\n\n /**\n * Disables the internal caching of TypeVariables.\n */\n public static void disableCache() {\n typeVariableCache.clear();\n cacheEnabled = false;\n }\n\n /**\n * Returns the raw class representing the type argument for the {@code targetType} resolved\n * upwards from the {@code initialType}. If no arguments can be resolved then\n * {@code Unknown.class} is returned.\n *\n * @param initialType to resolve upwards from\n * @param targetType to resolve arguments for\n * @return type argument for {@code initialType} else {@code null} if no type arguments are\n * declared\n * @throws IllegalArgumentException if more or less than one type argument is resolved for the\n * give types\n */\n public static Class resolveArgument(Class initialType, Class targetType) {\n return resolveArgument(resolveGenericType(initialType, targetType), initialType);\n }\n\n /**\n * Resolves the type argument for the {@code genericType} using type variable information from the\n * {@code sourceType}. If {@code genericType} is an instance of class, then {@code genericType} is\n * returned. If no arguments can be resolved then {@code Unknown.class} is returned.\n *\n * @param genericType to resolve upwards from\n * @param targetType to resolve arguments for\n * @return type argument for {@code initialType} else {@code null} if no type arguments are\n * declared\n * @throws IllegalArgumentException if more or less than one type argument is resolved for the\n * give types\n */\n public static Class resolveArgument(Type genericType, Class targetType) {\n Class[] arguments = resolveArguments(genericType, targetType);\n if (arguments == null)\n return Unknown.class;\n\n if (arguments.length != 1)\n throw new IllegalArgumentException(\"Expected 1 type argument on generic type \"\n + targetType.getName() + \" but found \" + arguments.length);\n\n return arguments[0];\n }\n\n /**\n * Returns an array of raw classes representing type arguments for the {@code targetType} resolved\n * upwards from the {@code initialType}. Arguments for {@code targetType} that cannot be resolved\n * to a Class are returned as {@code Unknown.class}. If no arguments can be resolved then\n * {@code null} is returned.\n *\n * @param initialType to resolve upwards from\n * @param targetType to resolve arguments for\n * @return array of raw classes representing type arguments for {@code initialType} else\n * {@code null} if no type arguments are declared\n */\n public static Class[] resolveArguments(Class initialType,\n Class targetType) {\n return resolveArguments(resolveGenericType(initialType, targetType), initialType);\n }\n\n /**\n * Resolves the arguments for the {@code genericType} using the type variable information for the\n * {@code targetType}. Returns {@code null} if {@code genericType} is not parameterized or if\n * arguments cannot be resolved.\n */\n public static Class[] resolveArguments(Type genericType, Class targetType) {\n Class[] result = null;\n\n if (genericType instanceof ParameterizedType) {\n ParameterizedType paramType = (ParameterizedType) genericType;\n Type[] arguments = paramType.getActualTypeArguments();\n result = new Class[arguments.length];\n for (int i = 0; i < arguments.length; i++)\n result[i] = resolveClass(arguments[i], targetType);\n } else if (genericType instanceof TypeVariable) {\n result = new Class[1];\n result[0] = resolveClass(genericType, targetType);\n }\n\n return result;\n }\n\n /**\n * Resolves the generic Type for the {@code targetType} by walking the type hierarchy upwards from\n * the {@code initialType}.\n */\n public static Type resolveGenericType(Type initialType, Class targetType) {\n Class rawType;\n if (initialType instanceof ParameterizedType)\n rawType = (Class) ((ParameterizedType) initialType).getRawType();\n else\n rawType = (Class) initialType;\n\n if (targetType.equals(rawType))\n return initialType;\n\n Type result;\n if (targetType.isInterface()) {\n for (Type superInterface : rawType.getGenericInterfaces())\n if (superInterface != null && !superInterface.equals(Object.class))\n if ((result = resolveGenericType(superInterface, targetType)) != null)\n return result;\n }\n\n Type superType = rawType.getGenericSuperclass();\n if (superType != null && !superType.equals(Object.class))\n if ((result = resolveGenericType(superType, targetType)) != null)\n return result;\n\n return null;\n }\n\n /**\n * Resolves the raw class for the given {@code genericType}, using the type variable information\n * from the {@code targetType}.\n */\n public static Class resolveClass(Type genericType, Class targetType) {\n if (genericType instanceof Class) {\n return (Class) genericType;\n } else if (genericType instanceof ParameterizedType) {\n return resolveClass(((ParameterizedType) genericType).getRawType(), targetType);\n } else if (genericType instanceof GenericArrayType) {\n GenericArrayType arrayType = (GenericArrayType) genericType;\n Class compoment = resolveClass(arrayType.getGenericComponentType(), targetType);\n return Array.newInstance(compoment, 0).getClass();\n } else if (genericType instanceof TypeVariable) {\n TypeVariable variable = (TypeVariable) genericType;\n genericType = getTypeVariableMap(targetType).get(variable);\n genericType = genericType == null ? resolveBound(variable) : resolveClass(genericType,\n targetType);\n }\n\n return genericType instanceof Class ? (Class) genericType : Unknown.class;\n }\n\n private static Map, Type> getTypeVariableMap(final Class targetType) {\n Reference, Type>> ref = typeVariableCache.get(targetType);\n Map, Type> map = ref != null ? ref.get() : null;\n\n if (map == null) {\n map = new HashMap<>();\n\n // Populate interfaces\n buildTypeVariableMap(targetType.getGenericInterfaces(), map);\n\n // Populate super classes and interfaces\n Type genericType = targetType.getGenericSuperclass();\n Class type = targetType.getSuperclass();\n while (type != null && !Object.class.equals(type)) {\n if (genericType instanceof ParameterizedType)\n buildTypeVariableMap((ParameterizedType) genericType, map);\n buildTypeVariableMap(type.getGenericInterfaces(), map);\n\n genericType = type.getGenericSuperclass();\n type = type.getSuperclass();\n }\n\n // Populate enclosing classes\n type = targetType;\n while (type.isMemberClass()) {\n genericType = type.getGenericSuperclass();\n if (genericType instanceof ParameterizedType)\n buildTypeVariableMap((ParameterizedType) genericType, map);\n\n type = type.getEnclosingClass();\n }\n\n if (cacheEnabled)\n typeVariableCache.put(targetType, new WeakReference<>(map));\n }\n\n return map;\n }\n\n /**\n * Populates the {@code map} with with variable/argument pairs for the given {@code types}.\n */\n static void buildTypeVariableMap(final Type[] types, final Map, Type> map) {\n for (Type type : types) {\n if (type instanceof ParameterizedType) {\n ParameterizedType parameterizedType = (ParameterizedType) type;\n buildTypeVariableMap(parameterizedType, map);\n Type rawType = parameterizedType.getRawType();\n if (rawType instanceof Class)\n buildTypeVariableMap(((Class) rawType).getGenericInterfaces(), map);\n } else if (type instanceof Class) {\n buildTypeVariableMap(((Class) type).getGenericInterfaces(), map);\n }\n }\n }\n\n /**\n * Populates the {@code typeVariableMap} with type arguments and parameters for the given\n * {@code type}.\n */\n private static void buildTypeVariableMap(ParameterizedType type,\n Map, Type> typeVariableMap) {\n if (type.getRawType() instanceof Class) {\n TypeVariable[] typeVariables = ((Class) type.getRawType()).getTypeParameters();\n Type[] typeArguments = type.getActualTypeArguments();\n\n for (int i = 0; i < typeArguments.length; i++) {\n TypeVariable variable = typeVariables[i];\n Type typeArgument = typeArguments[i];\n\n if (typeArgument instanceof Class) {\n typeVariableMap.put(variable, typeArgument);\n } else if (typeArgument instanceof GenericArrayType) {\n typeVariableMap.put(variable, typeArgument);\n } else if (typeArgument instanceof ParameterizedType) {\n typeVariableMap.put(variable, typeArgument);\n } else if (typeArgument instanceof TypeVariable) {\n TypeVariable typeVariableArgument = (TypeVariable) typeArgument;\n Type resolvedType = typeVariableMap.get(typeVariableArgument);\n if (resolvedType == null)\n resolvedType = resolveBound(typeVariableArgument);\n typeVariableMap.put(variable, resolvedType);\n }\n }\n }\n }\n\n /**\n * Resolves the first bound for the {@code typeVariable}, returning {@code Unknown.class} if none\n * can be resolved.\n */\n public static Type resolveBound(TypeVariable typeVariable) {\n Type[] bounds = typeVariable.getBounds();\n if (bounds.length == 0)\n return Unknown.class;\n\n Type bound = bounds[0];\n if (bound instanceof TypeVariable)\n bound = resolveBound((TypeVariable) bound);\n\n return bound == Object.class ? Unknown.class : bound;\n }\n}\n", "file_name": "TypeResolver.java", "human_label": "Resolve and return the arguments for the genericType using the type variable information for the targetType. Returns null if genericType is not parameterized or if arguments cannot be resolved.", "level": "class_runnable", "lineno": "138", "name": "resolveArguments", "oracle_context": "{ \"apis\" : \"[getActualTypeArguments, resolveClass]\", \"classes\" : \"[Class[], ParameterizedType, Type[]]\", \"vars\" : \"[length]\" }", "package": "org.atmosphere.config.managed", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767e11a6d9265ec018781", "all_context": "{ \"class_level\" : \"import java.util.HashMap;\\nimport java.util.List;\\nimport java.util.Map;\\nimport java.util.stream.Collectors;\\nimport org.apache.skywalking.oap.server.core.analysis.metrics.Metrics;\\nMap buffer;\\nMergableBufferedData();\\nread();\\n\", \"repo_level\" : \"public interface Metrics {abstract boolean combine(Metrics metrics);\\nabstract void calculate();\\nabstract Metrics toHour();\\nabstract Metrics toDay();\\npublic void setLastUpdateTimestamp(long timestamp);\\npublic boolean isExpired(long timestamp,long expiredThreshold);\\npublic long toTimeBucketInHour();\\npublic long toTimeBucketInDay();\\nprotected long getDurationInMinute();\\npublic String id();\\nabstract String id0();\\n }\\n\" }", "class_name": "MergableBufferedData", "code": "@Override public void accept(final METRICS data){\n final String id=data.id();\n final METRICS existed=buffer.get(id);\n if (existed == null) {\n buffer.put(id,data);\n }\n else {\n final boolean isAbandoned=!existed.combine(data);\n if (isAbandoned) {\n buffer.remove(id);\n }\n }\n}\n", "docstring": "/** \n * Accept the data into the cache and merge with the existing value. This method is not thread safe, should avoid concurrency calling.\n * @param data to be added potentially.\n */\n", "end_lineno": "59", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.core.analysis.data;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\nimport org.apache.skywalking.oap.server.core.analysis.metrics.Metrics;\n\n/**\n * MergableBufferedData is a thread no safe implementation of {@link BufferedData}. {@link Metrics} in this cache would\n * be {@link Metrics#combine(Metrics)} if their {@link Metrics#id()}s are same.\n *\n * Concurrency {@link #accept(Metrics)}s and {@link #read()} while {@link #accept(Metrics)} are both not recommended.\n */\npublic class MergableBufferedData implements BufferedData {\n private Map buffer;\n\n public MergableBufferedData() {\n buffer = new HashMap<>();\n }\n\n /**\n * Accept the data into the cache and merge with the existing value.\n *\n * This method is not thread safe, should avoid concurrency calling.\n *\n * @param data to be added potentially.\n */\n @Override\n public void accept(final METRICS data) {\n final String id = data.id();\n final METRICS existed = buffer.get(id);\n if (existed == null) {\n buffer.put(id, data);\n } else {\n final boolean isAbandoned = !existed.combine(data);\n if (isAbandoned) {\n buffer.remove(id);\n }\n }\n }\n\n @Override\n public List read() {\n try {\n return buffer.values().stream().collect(Collectors.toList());\n } finally {\n buffer.clear();\n }\n }\n}\n", "file_name": "MergableBufferedData.java", "human_label": "Accept the data into the buffer if its id does not exist in the buffer. Otherwise try to combine it with the existing value, and remove it if the combined is abandoned.", "level": "self_contained", "lineno": "40", "name": "accept", "oracle_context": "{ \"apis\" : \"[get, put, combine, remove]\", \"classes\" : \"[String, METRICS]\", \"vars\" : \"[buffer]\" }", "package": "org.apache.skywalking.oap.server.core.analysis.data", "project": "skywalking-master" }, { "_id": "636767531a6d9265ec017efb", "all_context": "{ \"class_level\" : \"import java.util.Collection;\\nimport java.util.HashSet;\\nimport java.util.LinkedHashSet;\\nimport java.util.Map;\\nimport java.util.NoSuchElementException;\\nimport java.util.Set;\\nimport org.jgrapht.Graph;\\nimport org.jgrapht.GraphTests;\\nimport org.jgrapht.Graphs;\\nimport org.jgrapht.util.CollectionUtil;\\nBucketList bucketList;\\nV current;\\nBucket head;\\nMap bucketMap;\\nBucket next;\\nBucket prev;\\nSet vertices;\\nLexBreadthFirstIterator(Graph graph);\\nnext();\\nisCrossComponentTraversal();\\nsetCrossComponentTraversal(boolean crossComponentTraversal);\\nadvance();\\ngetUnvisitedNeighbours(V vertex);\\nBucketList(Collection vertices);\\ncontainsBucketWith(V vertex);\\npoll();\\nupdateBuckets(Set vertices);\\nBucket(Collection vertices);\\nBucket(V vertex);\\nremoveVertex(V vertex);\\nremoveSelf();\\ninsertBefore(Bucket bucket);\\naddVertex(V vertex);\\nisEmpty();\\nhasNext();\\n\", \"repo_level\" : \"public interface Graph { Set getAllEdges(V sourceVertex,V targetVertex);\\n E getEdge(V sourceVertex,V targetVertex);\\n Supplier getVertexSupplier();\\n Supplier getEdgeSupplier();\\n E addEdge(V sourceVertex,V targetVertex);\\n boolean addEdge(V sourceVertex,V targetVertex,E e);\\n V addVertex();\\n boolean addVertex(V v);\\n boolean containsEdge(V sourceVertex,V targetVertex);\\n boolean containsEdge(E e);\\n boolean containsVertex(V v);\\n Set edgeSet();\\n int degreeOf(V vertex);\\n Set edgesOf(V vertex);\\n int inDegreeOf(V vertex);\\n Set incomingEdgesOf(V vertex);\\n int outDegreeOf(V vertex);\\n Set outgoingEdgesOf(V vertex);\\n boolean removeAllEdges(Collection edges);\\n Set removeAllEdges(V sourceVertex,V targetVertex);\\n boolean removeAllVertices(Collection vertices);\\n E removeEdge(V sourceVertex,V targetVertex);\\n boolean removeEdge(E e);\\n boolean removeVertex(V v);\\n Set vertexSet();\\n V getEdgeSource(E e);\\n V getEdgeTarget(E e);\\n GraphType getType();\\n double getEdgeWeight(E e);\\n void setEdgeWeight(E e,double weight);\\ndefault void setEdgeWeight(V sourceVertex,V targetVertex,double weight);\\ndefault GraphIterables iterables();\\n }\\npublic interface Graphs {static E addEdge(Graph g,V sourceVertex,V targetVertex,double weight);\\nstatic E addEdgeWithVertices(Graph g,V sourceVertex,V targetVertex);\\nstatic boolean addEdgeWithVertices(Graph targetGraph,Graph sourceGraph,E edge);\\nstatic E addEdgeWithVertices(Graph g,V sourceVertex,V targetVertex,double weight);\\nstatic boolean addGraph(Graph destination,Graph source);\\nstatic void addGraphReversed(Graph destination,Graph source);\\nstatic boolean addAllEdges(Graph destination,Graph source,Collection edges);\\nstatic boolean addAllVertices(Graph destination,Collection vertices);\\nstatic List neighborListOf(Graph g,V vertex);\\nstatic Set neighborSetOf(Graph g,V vertex);\\nstatic List predecessorListOf(Graph g,V vertex);\\nstatic List successorListOf(Graph g,V vertex);\\nstatic Graph undirectedGraph(Graph g);\\nstatic boolean testIncidence(Graph g,E e,V v);\\nstatic V getOppositeVertex(Graph g,E e,V v);\\nstatic boolean removeVertexAndPreserveConnectivity(Graph graph,V vertex);\\nstatic boolean removeVerticesAndPreserveConnectivity(Graph graph,Predicate predicate);\\nstatic boolean removeVertexAndPreserveConnectivity(Graph graph,Iterable vertices);\\nstatic void addOutgoingEdges(Graph graph,V source,Iterable targets);\\nstatic void addIncomingEdges(Graph graph,V target,Iterable sources);\\nstatic boolean vertexHasSuccessors(Graph graph,V vertex);\\nstatic boolean vertexHasPredecessors(Graph graph,V vertex);\\nstatic VertexToIntegerMapping getVertexToIntegerMapping(Graph graph);\\n }\\npublic interface CollectionUtil {static HashMap newHashMapWithExpectedSize(int expectedSize);\\nstatic LinkedHashMap newLinkedHashMapWithExpectedSize(int expectedSize);\\nstatic HashSet newHashSetWithExpectedSize(int expectedSize);\\nstatic LinkedHashSet newLinkedHashSetWithExpectedSize(int expectedSize);\\nstatic E getElement(Iterable iterable,int index);\\n }\\n\" }", "class_name": "LexBreadthFirstIterator$BucketList", "code": "void insertBefore(Bucket bucket){\n this.next=bucket;\n if (bucket != null) {\n this.prev=bucket.prev;\n if (bucket.prev != null) {\n bucket.prev.next=this;\n }\n bucket.prev=this;\n }\n else {\n this.prev=null;\n }\n}\n", "docstring": "/** \n * Inserts this bucket in the data structure before the {@code bucket}.\n * @param bucket the bucket, that will be the next to this bucket.\n */\n", "end_lineno": "375", "file_content": "/*\n * (C) Copyright 2018-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.traverse;\n\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.LinkedHashSet;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.jgrapht.Graph;\nimport org.jgrapht.GraphTests;\nimport org.jgrapht.Graphs;\nimport org.jgrapht.util.CollectionUtil;\n\n/**\n * A lexicographical breadth-first iterator for an undirected graph.\n *

\n * Every vertex has an implicit label (they aren't used explicitly in order to reduce time and\n * memory complexity). When some vertex is returned by this iterator, its index is the number of\n * vertices in this graph minus number of already returned vertices. For a given vertex v its label\n * is a concatenation of indices of already returned vertices, that were also its neighbours, with\n * some separator between them. For example, 7#4#3 is a valid vertex label.\n *

\n * Iterator chooses vertex with lexicographically largest label and returns it. It breaks ties\n * arbitrarily. For more information on lexicographical BFS see the following article: Corneil D.G.\n * (2004) \n * Lexicographic Breadth First Search – A Survey. In: Hromkovič J., Nagl M., Westfechtel\n * B. (eds) Graph-Theoretic Concepts in Computer Science. WG 2004. Lecture Notes in Computer\n * Science, vol 3353. Springer, Berlin, Heidelberg; and the following\n * paper:CS 762:\n * Graph-theoretic algorithms. Lecture notes of a graduate course. University of Waterloo.\n *

\n * For this iterator to work correctly the graph must not be modified during iteration. Currently\n * there are no means to ensure that, nor to fail-fast. The results of such modifications are\n * undefined.\n *

\n * Note: only vertex events are fired by this iterator.\n *\n * @param the graph vertex type.\n * @param the graph edge type.\n * @author Timofey Chudakov\n */\npublic class LexBreadthFirstIterator\n extends\n AbstractGraphIterator\n{\n\n /**\n * Reference to the {@code BucketList} that contains unvisited vertices.\n */\n private BucketList bucketList;\n\n /**\n * Contains current vertex of the {@code graph}.\n */\n private V current;\n\n /**\n * Creates new lexicographical breadth-first iterator for {@code graph}.\n *\n * @param graph the graph to be iterated.\n */\n public LexBreadthFirstIterator(Graph graph)\n {\n super(graph);\n GraphTests.requireUndirected(graph);\n bucketList = new BucketList(graph.vertexSet());\n }\n\n /**\n * Checks whether there exist unvisited vertices.\n *\n * @return true if there exist unvisited vertices.\n */\n @Override\n public boolean hasNext()\n {\n if (current != null) {\n return true;\n }\n current = advance();\n if (current != null && nListeners != 0) {\n fireVertexTraversed(createVertexTraversalEvent(current));\n }\n return current != null;\n }\n\n /**\n * Returns the next vertex in the ordering.\n *\n * @return the next vertex in the ordering.\n */\n @Override\n public V next()\n {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n V result = current;\n current = null;\n if (nListeners != 0) {\n fireVertexFinished(createVertexTraversalEvent(result));\n }\n return result;\n }\n\n /**\n * {@inheritDoc}\n *

\n * Always returns true since this iterator doesn't care about connected components.\n */\n @Override\n public boolean isCrossComponentTraversal()\n {\n return true;\n }\n\n /**\n * {@inheritDoc}\n *

\n * Trying to disable the cross components nature of this iterator will result into throwing a\n * {@link IllegalArgumentException}.\n */\n @Override\n public void setCrossComponentTraversal(boolean crossComponentTraversal)\n {\n if (!crossComponentTraversal) {\n throw new IllegalArgumentException(\"Iterator is always cross-component\");\n }\n }\n\n /**\n * Retrieves vertex from the {@code bucketList} and returns it.\n *\n * @return the vertex retrieved from the {@code bucketList}.\n */\n private V advance()\n {\n V vertex = bucketList.poll();\n if (vertex != null) {\n bucketList.updateBuckets(getUnvisitedNeighbours(vertex));\n }\n return vertex;\n }\n\n /**\n * Computes and returns neighbours of {@code vertex} which haven't been visited by this\n * iterator.\n *\n * @param vertex the vertex, whose neighbours are being explored.\n * @return neighbours of {@code vertex} which have yet to be visited by this iterator.\n */\n private Set getUnvisitedNeighbours(V vertex)\n {\n Set unmapped = new LinkedHashSet<>();\n Set edges = graph.edgesOf(vertex);\n for (E edge : edges) {\n V oppositeVertex = Graphs.getOppositeVertex(graph, edge, vertex);\n if (bucketList.containsBucketWith(oppositeVertex)) {\n unmapped.add(oppositeVertex);\n }\n }\n return unmapped;\n }\n\n /**\n * Data structure for performing lexicographical breadth-first search. Allows to add and\n * retrieve vertices from buckets, update their buckets after a new vertex has been added to the\n * LexBFS order. Labels aren't used explicitly, which results in time and space optimization.\n *\n * @author Timofey Chudakov\n */\n class BucketList\n {\n /**\n * Bucket with the vertices that have lexicographically largest label.\n */\n private Bucket head;\n /**\n * Map for mapping vertices to buckets they are currently in. Is used for finding the bucket\n * of the vertex in constant time.\n */\n private Map bucketMap;\n\n /**\n * Creates a {@code BucketList} with a single bucket and all specified {@code vertices} in\n * it.\n *\n * @param vertices the vertices of the graph, that should be stored in the {@code head}\n * bucket.\n */\n BucketList(Collection vertices)\n {\n head = new Bucket(vertices);\n bucketMap = CollectionUtil.newHashMapWithExpectedSize(vertices.size());\n for (V vertex : vertices) {\n bucketMap.put(vertex, head);\n }\n }\n\n /**\n * Checks whether there exists a bucket with the specified {@code vertex}.\n *\n * @param vertex the vertex whose presence in some {@code Bucket} in this {@code BucketList}\n * is checked.\n * @return true if there exists a bucket with {@code vertex} in it, otherwise\n * false.\n */\n boolean containsBucketWith(V vertex)\n {\n return bucketMap.containsKey(vertex);\n }\n\n /**\n * Retrieves element from the head bucket by invoking {@link Bucket#poll()} or null if this\n * {@code BucketList} is empty.\n *

\n * Removes the head bucket if it becomes empty after the operation.\n *\n * @return vertex returned by {@link Bucket#poll()} invoked on head bucket or null if this\n * {@code BucketList} is empty.\n */\n V poll()\n {\n if (bucketMap.size() > 0) {\n V res = head.poll();\n bucketMap.remove(res);\n if (head.isEmpty()) {\n head = head.next;\n if (head != null) {\n head.prev = null;\n }\n }\n return res;\n } else {\n return null;\n }\n }\n\n /**\n * For every bucket B in this {@code BucketList}, which contains vertices from the set\n * {@code\n * vertices}, creates a new {@code Bucket} B' and moves vertices from B to B' according to\n * the following rule: $B' = B\\cap vertices$ and $B = B\\backslash B'$. For every such\n * {@code Bucket} B only one {@code Bucket} B' is created. If some bucket B becomes empty\n * after this operation, it is removed from the data structure.\n *\n * @param vertices the vertices, that should be moved to new buckets.\n */\n void updateBuckets(Set vertices)\n {\n Set visitedBuckets = new HashSet<>();\n for (V vertex : vertices) {\n Bucket bucket = bucketMap.get(vertex);\n if (visitedBuckets.contains(bucket)) {\n bucket.prev.addVertex(vertex);\n bucketMap.put(vertex, bucket.prev);\n } else {\n visitedBuckets.add(bucket);\n Bucket newBucket = new Bucket(vertex);\n newBucket.insertBefore(bucket);\n bucketMap.put(vertex, newBucket);\n if (head == bucket) {\n head = newBucket;\n }\n }\n bucket.removeVertex(vertex);\n if (bucket.isEmpty()) {\n visitedBuckets.remove(bucket);\n bucket.removeSelf();\n }\n }\n }\n\n /**\n * Plays the role of the container of vertices. All vertices stored in a bucket have\n * identical label. Labels aren't used explicitly.\n *

\n * Encapsulates operations of addition and removal of vertices from the bucket and removal\n * of a bucket from the data structure.\n */\n private class Bucket\n {\n /**\n * Reference of the bucket with lexicographically smaller label.\n */\n private Bucket next;\n /**\n * Reference of the bucket with lexicographically larger label.\n */\n private Bucket prev;\n /**\n * Set of vertices currently stored in this bucket.\n */\n private Set vertices;\n\n /**\n * Creates a new bucket with all {@code vertices} stored in it.\n *\n * @param vertices vertices to store in this bucket.\n */\n Bucket(Collection vertices)\n {\n this.vertices = new LinkedHashSet<>(vertices);\n }\n\n /**\n * Creates a new Bucket with a single {@code vertex} in it.\n *\n * @param vertex the vertex to store in this bucket.\n */\n Bucket(V vertex)\n {\n this.vertices = new LinkedHashSet<>();\n vertices.add(vertex);\n }\n\n /**\n * Removes the {@code vertex} from this bucket.\n *\n * @param vertex the vertex to remove.\n */\n void removeVertex(V vertex)\n {\n vertices.remove(vertex);\n }\n\n /**\n * Removes this bucket from the data structure.\n */\n void removeSelf()\n {\n if (next != null) {\n next.prev = prev;\n }\n if (prev != null) {\n prev.next = next;\n }\n }\n\n /**\n * Inserts this bucket in the data structure before the {@code bucket}.\n *\n * @param bucket the bucket, that will be the next to this bucket.\n */\n void insertBefore(Bucket bucket)\n {\n this.next = bucket;\n if (bucket != null) {\n this.prev = bucket.prev;\n if (bucket.prev != null) {\n bucket.prev.next = this;\n }\n bucket.prev = this;\n } else {\n this.prev = null;\n }\n }\n\n /**\n * Adds the {@code vertex} to this bucket.\n *\n * @param vertex the vertex to add.\n */\n void addVertex(V vertex)\n {\n vertices.add(vertex);\n }\n\n /**\n * Retrieves one vertex from this bucket.\n *\n * @return vertex, that was removed from this bucket, null if the bucket was empty.\n */\n V poll()\n {\n if (vertices.isEmpty()) {\n return null;\n } else {\n V vertex = vertices.iterator().next();\n vertices.remove(vertex);\n return vertex;\n }\n }\n\n /**\n * Checks whether this bucket is empty.\n *\n * @return true if this bucket doesn't contain any elements, otherwise false.\n */\n boolean isEmpty()\n {\n return vertices.size() == 0;\n }\n }\n }\n}\n", "file_name": "LexBreadthFirstIterator.java", "human_label": "Insert this bucket in the data structure before the given bucket.", "level": "class_runnable", "lineno": "358", "name": "insertBefore", "oracle_context": "{ \"apis\" : \"[Bucket, next]\", \"classes\" : \"[bucket.prev]\", \"vars\" : \"[prev, next]\" }", "package": "org.jgrapht.traverse", "project": "jgrapht-master" }, { "_id": "636766f11a6d9265ec017641", "all_context": "{ \"class_level\" : \"import java.io.*;\\nReader reader;\\nByteArrayOutputStream byteArrayOut;\\nWriter writer;\\nchar[] chars;\\nbyte[] buffer;\\nint index;\\nint length;\\nReaderInputStream(String readerString);\\nReaderInputStream(Reader reader);\\nReaderInputStream(Reader reader,String encoding);\\nfillBuffer();\\nread(byte[] data,int off,int len);\\navailable();\\nclose();\\nread();\\n\", \"repo_level\" : \"\" }", "class_name": "ReaderInputStream", "code": "@Override public int available() throws IOException {\n return this.index < this.length ? this.length - this.index : this.length >= 0 && this.reader.ready() ? 1 : 0;\n}\n", "docstring": "/** \n * @see InputStream#available() \n */\n", "end_lineno": "117", "file_content": "/*\n * Copyright 2008-2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.io.input;\nimport java.io.*;\n\n/**\n * 使用InputStream读取Reader的工具类\n * @version 2009-5-13\n * @author 网络收集\n */\npublic class ReaderInputStream extends InputStream {\n private Reader reader = null;\n private ByteArrayOutputStream byteArrayOut = null;\n private Writer writer = null;\n private char[] chars = null;\n private byte[] buffer = null;\n private int index, length = 0;\n //========================================================================================\n\n /**\n * 带Reader参数构造函数\n * @param readerString - 要阅读的字符串。\n */\n public ReaderInputStream(final String readerString) {\n this.reader = new StringReader(readerString);\n this.byteArrayOut = new ByteArrayOutputStream();\n this.writer = new OutputStreamWriter(this.byteArrayOut);\n this.chars = new char[1024];\n }\n\n /**\n * 带Reader参数构造函数\n * @param reader - InputStream使用的Reader\n */\n public ReaderInputStream(final Reader reader) {\n this.reader = reader;\n this.byteArrayOut = new ByteArrayOutputStream();\n this.writer = new OutputStreamWriter(this.byteArrayOut);\n this.chars = new char[1024];\n }\n\n /**\n * 带Reader和字符编码格式参数的构造函数\n * @param reader - InputStream使用的Reader\n * @param encoding - InputStream使用的字符编码格式.\n * @throws UnsupportedEncodingException 如果字符编码格式不支持,则抛 UnsupportedEncodingException 异常\n */\n public ReaderInputStream(final Reader reader, final String encoding) throws UnsupportedEncodingException {\n this.reader = reader;\n this.byteArrayOut = new ByteArrayOutputStream();\n this.writer = new OutputStreamWriter(this.byteArrayOut, encoding);\n this.chars = new char[1024];\n }\n //========================================================================================\n\n /** @see InputStream#read() */\n @Override\n public int read() throws IOException {\n if (this.index >= this.length) {\n this.fillBuffer();\n }\n if (this.index >= this.length) {\n return -1;\n }\n return 0xff & this.buffer[this.index++];\n }\n\n private void fillBuffer() throws IOException {\n if (this.length < 0) {\n return;\n }\n int numChars = this.reader.read(this.chars);\n if (numChars < 0) {\n this.length = -1;\n } else {\n this.byteArrayOut.reset();\n this.writer.write(this.chars, 0, numChars);\n this.writer.flush();\n this.buffer = this.byteArrayOut.toByteArray();\n this.length = this.buffer.length;\n this.index = 0;\n }\n }\n\n /** @see InputStream#read(byte[], int, int) */\n @Override\n public int read(final byte[] data, final int off, final int len) throws IOException {\n if (this.index >= this.length) {\n this.fillBuffer();\n }\n if (this.index >= this.length) {\n return -1;\n }\n int amount = Math.min(len, this.length - this.index);\n System.arraycopy(this.buffer, this.index, data, off, amount);\n this.index += amount;\n return amount;\n }\n\n /** @see InputStream#available() */\n @Override\n public int available() throws IOException {\n return this.index < this.length ? this.length - this.index : this.length >= 0 && this.reader.ready() ? 1 : 0;\n }\n\n /** @see InputStream#close() */\n @Override\n public void close() throws IOException {\n this.reader.close();\n }\n}\n", "file_name": "ReaderInputStream.java", "human_label": "Check the available space of this InputStream according to the index.", "level": "class_runnable", "lineno": "113", "name": "available", "oracle_context": "{ \"apis\" : \"[ready]\", \"classes\" : \"[]\", \"vars\" : \"[index, length, reader]\" }", "package": "net.hasor.utils.io.input", "project": "hasor-master" }, { "_id": "636767de1a6d9265ec018706", "all_context": "{ \"class_level\" : \"import java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Objects;\\nimport java.util.stream.Collectors;\\nimport org.apache.skywalking.library.elasticsearch.response.Mappings;\\nimport org.apache.skywalking.oap.server.library.client.elasticsearch.ElasticSearchClient;\\nMap structures;\\nMap properties;\\nMappings.Source source;\\nIndexStructures();\\ngetMapping(String tableName);\\ndiffStructure(String tableName,Mappings mappings);\\ncontainsStructure(String tableName,Mappings mappings);\\nFields(Mappings mapping);\\ncontainsAllFields(Fields fields);\\nappendNewFields(Fields fields);\\ndiffFields(Fields fields);\\nputStructure(String tableName,Mappings mapping);\\n\", \"repo_level\" : \"public interface Mappings { }\\npublic interface ElasticSearchClient {public void connect();\\npublic void shutdown();\\npublic void registerChecker(HealthChecker healthChecker);\\npublic boolean createIndex(String indexName);\\npublic boolean createIndex(String indexName,Mappings mappings,Map settings);\\npublic boolean updateIndexMapping(String indexName,Mappings mapping);\\npublic Optional getIndex(String indexName);\\npublic Collection retrievalIndexByAliases(String alias);\\npublic boolean deleteByIndexName(String indexName);\\npublic boolean isExistsIndex(String indexName);\\npublic Optional getTemplate(String name);\\npublic boolean isExistsTemplate(String indexName);\\npublic boolean createOrUpdateTemplate(String indexName,Map settings,Mappings mapping,int order);\\npublic boolean deleteTemplate(String indexName);\\npublic SearchResponse search(Supplier indices,Search search);\\npublic SearchResponse search(String indexName,Search search);\\npublic SearchResponse search(String indexName,Search search,SearchParams params);\\npublic SearchResponse scroll(Duration contextRetention,String scrollId);\\npublic boolean deleteScrollContextQuietly(String scrollId);\\npublic Optional get(String indexName,String id);\\npublic boolean existDoc(String indexName,String id);\\npublic Optional ids(Map indexIds);\\npublic SearchResponse searchIDs(String indexName,Iterable ids);\\npublic void forceInsert(String indexName,String id,Map source);\\npublic void forceUpdate(String indexName,String id,Map source);\\npublic IndexRequestWrapper prepareInsert(String indexName,String id,Map source);\\npublic UpdateRequestWrapper prepareUpdate(String indexName,String id,Map source);\\npublic BulkProcessor createBulkProcessor(int bulkActions,int flushInterval,int concurrentRequests);\\npublic String formatIndexName(String indexName);\\n }\\n\" }", "class_name": "IndexStructures", "code": "public Mappings diffStructure(String tableName,Mappings mappings){\n if (!structures.containsKey(tableName)) {\n return new Mappings();\n }\n Map properties=mappings.getProperties();\n Map diffProperties=structures.get(tableName).diffFields(new Fields(mappings));\n return Mappings.builder().type(ElasticSearchClient.TYPE).properties(diffProperties).build();\n}\n", "docstring": "/** \n * Returns mappings with fields that not exist in the input mappings. The input mappings should be history mapping from current index. Do not return _source config to avoid current index update conflict.\n */\n", "end_lineno": "83", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.stream.Collectors;\nimport org.apache.skywalking.library.elasticsearch.response.Mappings;\nimport org.apache.skywalking.oap.server.library.client.elasticsearch.ElasticSearchClient;\n\npublic class IndexStructures {\n private final Map structures;\n\n public IndexStructures() {\n this.structures = new HashMap<>();\n }\n\n public Mappings getMapping(String tableName) {\n Map properties =\n structures.containsKey(tableName) ?\n structures.get(tableName).properties : new HashMap<>();\n Mappings.Source source =\n structures.containsKey(tableName) ?\n structures.get(tableName).source : new Mappings.Source();\n return Mappings.builder()\n .type(ElasticSearchClient.TYPE)\n .properties(properties)\n .source(source)\n .build();\n }\n\n /**\n * Add or append field when the current structures don't contain the input structure or having\n * new fields in it.\n */\n public void putStructure(String tableName, Mappings mapping) {\n if (Objects.isNull(mapping)\n || Objects.isNull(mapping.getProperties())\n || mapping.getProperties().isEmpty()) {\n return;\n }\n Fields fields = new Fields(mapping);\n if (structures.containsKey(tableName)) {\n structures.get(tableName).appendNewFields(fields);\n } else {\n structures.put(tableName, fields);\n }\n }\n\n /**\n * Returns mappings with fields that not exist in the input mappings.\n * The input mappings should be history mapping from current index.\n * Do not return _source config to avoid current index update conflict.\n */\n public Mappings diffStructure(String tableName, Mappings mappings) {\n if (!structures.containsKey(tableName)) {\n return new Mappings();\n }\n Map properties = mappings.getProperties();\n Map diffProperties =\n structures.get(tableName).diffFields(new Fields(mappings));\n return Mappings.builder()\n .type(ElasticSearchClient.TYPE)\n .properties(diffProperties)\n .build();\n }\n\n /**\n * Returns true when the current structures already contains the properties of the input\n * mappings.\n */\n public boolean containsStructure(String tableName, Mappings mappings) {\n if (Objects.isNull(mappings) ||\n Objects.isNull(mappings.getProperties()) ||\n mappings.getProperties().isEmpty()) {\n return true;\n }\n return structures.containsKey(tableName)\n && structures.get(tableName)\n .containsAllFields(new Fields(mappings));\n }\n\n /**\n * The properties of the template or index.\n */\n public static class Fields {\n private final Map properties;\n private Mappings.Source source;\n\n private Fields(Mappings mapping) {\n this.properties = mapping.getProperties();\n this.source = mapping.getSource();\n }\n\n /**\n * Returns ture when the input fields have already been stored in the properties.\n */\n private boolean containsAllFields(Fields fields) {\n if (this.properties.size() < fields.properties.size()) {\n return false;\n }\n boolean isContains = fields.properties.entrySet().stream()\n .allMatch(item -> Objects.equals(properties.get(item.getKey()), item.getValue()));\n if (!isContains) {\n return false;\n }\n return fields.source.getExcludes().containsAll(this.source.getExcludes());\n }\n\n /**\n * Append new fields and update.\n * Properties combine input and exist, update property's attribute, won't remove old one.\n * Source will be updated to the input.\n */\n private void appendNewFields(Fields fields) {\n properties.putAll(fields.properties);\n source = fields.source;\n }\n\n /**\n * Returns the properties that not exist in the input fields.\n */\n private Map diffFields(Fields fields) {\n return this.properties.entrySet().stream()\n .filter(e -> !fields.properties.containsKey(e.getKey()))\n .collect(Collectors.toMap(\n Map.Entry::getKey,\n Map.Entry::getValue\n ));\n }\n }\n}\n", "file_name": "IndexStructures.java", "human_label": "Return mappings with fields that do not exist in the input mappings. The input mappings should be history mapping from the current index.", "level": "plib_runnable", "lineno": "67", "name": "diffStructure", "oracle_context": "{ \"apis\" : \"[containsKey, getProperties, diffFields, get, build, type, builder, Fields]\", \"classes\" : \"[Map, ElasticSearchClient]\", \"vars\" : \"[TYPE, structures]\" }", "package": "org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base", "project": "skywalking-master" }, { "_id": "636767dd1a6d9265ec0186e5", "all_context": "{ \"class_level\" : \"import java.util.ArrayList;\\nimport java.util.List;\\nimport org.apache.skywalking.oap.server.library.datacarrier.buffer.Channels;\\nimport org.apache.skywalking.oap.server.library.datacarrier.buffer.QueueBuffer;\\nboolean running;\\nArrayList consumeTargets;\\nlong size;\\nlong consumeCycle;\\nChannels channels;\\nIConsumer consumer;\\nMultipleChannelsConsumer(String threadName,long consumeCycle);\\nrun();\\nconsume(Group target,List consumeList);\\nsize();\\nshutdown();\\nGroup(Channels channels,IConsumer consumer);\\n\", \"repo_level\" : \"public interface Channels {public boolean save(T data);\\npublic void setPartitioner(IDataPartitioner dataPartitioner);\\npublic void setStrategy(BufferStrategy strategy);\\npublic int getChannelSize();\\npublic long size();\\npublic QueueBuffer getBuffer(int index);\\n }\\npublic interface QueueBuffer { boolean save(T data);\\n void setStrategy(BufferStrategy strategy);\\n void obtain(List consumeList);\\n int getBufferSize();\\n }\\n\" }", "class_name": "MultipleChannelsConsumer", "code": "public void addNewTarget(Channels channels,IConsumer consumer){\n Group group=new Group(channels,consumer);\n ArrayList newList=new ArrayList();\n for ( Group target : consumeTargets) {\n newList.add(target);\n }\n newList.add(group);\n consumeTargets=newList;\n size+=channels.size();\n}\n", "docstring": "/** \n * Add a new target channels.\n */\n", "end_lineno": "105", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.library.datacarrier.consumer;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.apache.skywalking.oap.server.library.datacarrier.buffer.Channels;\nimport org.apache.skywalking.oap.server.library.datacarrier.buffer.QueueBuffer;\n\n/**\n * MultipleChannelsConsumer represent a single consumer thread, but support multiple channels with their {@link\n * IConsumer}s\n */\npublic class MultipleChannelsConsumer extends Thread {\n private volatile boolean running;\n private volatile ArrayList consumeTargets;\n @SuppressWarnings(\"NonAtomicVolatileUpdate\")\n private volatile long size;\n private final long consumeCycle;\n\n public MultipleChannelsConsumer(String threadName, long consumeCycle) {\n super(threadName);\n this.consumeTargets = new ArrayList<>();\n this.consumeCycle = consumeCycle;\n }\n\n @Override\n public void run() {\n running = true;\n\n final List consumeList = new ArrayList(2000);\n while (running) {\n boolean hasData = false;\n for (Group target : consumeTargets) {\n boolean consumed = consume(target, consumeList);\n hasData = hasData || consumed;\n }\n\n if (!hasData) {\n try {\n Thread.sleep(consumeCycle);\n } catch (InterruptedException e) {\n }\n }\n }\n\n // consumer thread is going to stop\n // consume the last time\n for (Group target : consumeTargets) {\n consume(target, consumeList);\n\n target.consumer.onExit();\n }\n }\n\n private boolean consume(Group target, List consumeList) {\n for (int i = 0; i < target.channels.getChannelSize(); i++) {\n QueueBuffer buffer = target.channels.getBuffer(i);\n buffer.obtain(consumeList);\n }\n\n if (!consumeList.isEmpty()) {\n try {\n target.consumer.consume(consumeList);\n } catch (Throwable t) {\n target.consumer.onError(consumeList, t);\n } finally {\n consumeList.clear();\n }\n return true;\n }\n target.consumer.nothingToConsume();\n return false;\n }\n\n /**\n * Add a new target channels.\n */\n public void addNewTarget(Channels channels, IConsumer consumer) {\n Group group = new Group(channels, consumer);\n // Recreate the new list to avoid change list while the list is used in consuming.\n ArrayList newList = new ArrayList();\n for (Group target : consumeTargets) {\n newList.add(target);\n }\n newList.add(group);\n consumeTargets = newList;\n size += channels.size();\n }\n\n public long size() {\n return size;\n }\n\n void shutdown() {\n running = false;\n }\n\n private static class Group {\n private Channels channels;\n private IConsumer consumer;\n\n public Group(Channels channels, IConsumer consumer) {\n this.channels = channels;\n this.consumer = consumer;\n }\n }\n}\n", "file_name": "MultipleChannelsConsumer.java", "human_label": "Add the given target channels to the consumeTargets.", "level": "plib_runnable", "lineno": "92", "name": "addNewTarget", "oracle_context": "{ \"apis\" : \"[add, size, Group]\", \"classes\" : \"[Group, ArrayList]\", \"vars\" : \"[consumeTargets, size]\" }", "package": "org.apache.skywalking.oap.server.library.datacarrier.consumer", "project": "skywalking-master" }, { "_id": "636767871a6d9265ec01846d", "all_context": "{ \"class_level\" : \"import java.io.BufferedInputStream;\\nimport java.io.File;\\nimport java.io.FileInputStream;\\nimport java.io.FileNotFoundException;\\nimport java.io.FileOutputStream;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport java.io.ObjectInputStream;\\nimport java.io.ObjectOutputStream;\\nimport java.net.URL;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nString CONFIG_FILE_NAME;\\nint DEFAULT_MAX_SIZE;\\nint _maxSize;\\nLinkedList _mruFileList;\\nMRUFileManager();\\nMRUFileManager(int maxSize);\\nsize();\\ngetFile(int index);\\ngetInputStream(int index);\\nset(File file);\\nset(URL url);\\ngetMRUFileList();\\nmoveToTop(int index);\\ncreateConfigurationDirectory();\\ngetInputStream(File file);\\ngetInputStream(URL url);\\nsetMRU(Object o);\\nload();\\ngetFilename();\\nsetMaxSize(int maxSize);\\nsave();\\n\", \"repo_level\" : \"\" }", "class_name": "MRUFileManager", "code": "public static void createConfigurationDirectory(){\n String home=System.getProperty(\"user.home\");\n String sep=System.getProperty(\"file.separator\");\n File f=new File(home + sep + \"lf5\");\n if (!f.exists()) {\n try {\n f.mkdir();\n }\n catch ( SecurityException e) {\n e.printStackTrace();\n }\n }\n}\n", "docstring": "/** \n * Creates the directory where the MRU file list will be written. The \"lf5\" directory is created in the Documents and Settings directory on Windows 2000 machines and where ever the user.home variable points on all other platforms.\n */\n", "end_lineno": "194", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.log4j.lf5.viewer.configure;\n\nimport java.io.BufferedInputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.net.URL;\nimport java.util.Iterator;\nimport java.util.LinkedList;\n\n\n/**\n *

MRUFileManager handles the storage and retrival the most\n * recently opened log files.\n *\n * @author Brad Marlborough\n * @author Richard Hurst\n */\n\n// Contributed by ThoughtWorks Inc.\n\npublic class MRUFileManager {\n //--------------------------------------------------------------------------\n // Constants:\n //--------------------------------------------------------------------------\n private static final String CONFIG_FILE_NAME = \"mru_file_manager\";\n private static final int DEFAULT_MAX_SIZE = 3;\n\n //--------------------------------------------------------------------------\n // Protected Variables:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Private Variables:\n //--------------------------------------------------------------------------\n private int _maxSize = 0;\n private LinkedList _mruFileList;\n\n //--------------------------------------------------------------------------\n // Constructors:\n //--------------------------------------------------------------------------\n public MRUFileManager() {\n load();\n setMaxSize(DEFAULT_MAX_SIZE);\n }\n\n public MRUFileManager(int maxSize) {\n load();\n setMaxSize(maxSize);\n }\n //--------------------------------------------------------------------------\n // Public Methods:\n //--------------------------------------------------------------------------\n\n /**\n * Saves a list of MRU files out to a file.\n */\n public void save() {\n File file = new File(getFilename());\n\n try {\n ObjectOutputStream oos = new ObjectOutputStream(new\n FileOutputStream(file));\n oos.writeObject(_mruFileList);\n oos.flush();\n oos.close();\n } catch (Exception e) {\n // do nothing\n e.printStackTrace();\n }\n }\n\n /**\n * Gets the size of the MRU file list.\n */\n public int size() {\n return _mruFileList.size();\n }\n\n /**\n * Returns a particular file name stored in a MRU file\n * list based on an index value.\n */\n public Object getFile(int index) {\n if (index < size()) {\n return _mruFileList.get(index);\n }\n\n return null;\n }\n\n /**\n * Returns a input stream to the resource at the specified index\n */\n public InputStream getInputStream(int index) throws IOException,\n FileNotFoundException {\n if (index < size()) {\n Object o = getFile(index);\n if (o instanceof File) {\n return getInputStream((File) o);\n } else {\n return getInputStream((URL) o);\n }\n }\n return null;\n }\n\n /**\n * Adds a file name to the MRU file list.\n */\n public void set(File file) {\n setMRU(file);\n }\n\n /**\n * Adds a url to the MRU file list.\n */\n public void set(URL url) {\n setMRU(url);\n }\n\n /**\n * Gets the list of files stored in the MRU file list.\n */\n public String[] getMRUFileList() {\n if (size() == 0) {\n return null;\n }\n\n String[] ss = new String[size()];\n\n for (int i = 0; i < size(); i++) {\n Object o = getFile(i);\n if (o instanceof File) {\n ss[i] = ((File) o).getAbsolutePath();\n } else // must be a url\n {\n ss[i] = o.toString();\n }\n\n }\n\n return ss;\n }\n\n /**\n * Moves the the index to the top of the MRU List\n *\n * @param index The index to be first in the mru list\n */\n public void moveToTop(int index) {\n _mruFileList.add(0, _mruFileList.remove(index));\n }\n\n /**\n * Creates the directory where the MRU file list will be written.\n * The \"lf5\" directory is created in the Documents and Settings\n * directory on Windows 2000 machines and where ever the user.home\n * variable points on all other platforms.\n */\n public static void createConfigurationDirectory() {\n String home = System.getProperty(\"user.home\");\n String sep = System.getProperty(\"file.separator\");\n File f = new File(home + sep + \"lf5\");\n if (!f.exists()) {\n try {\n f.mkdir();\n } catch (SecurityException e) {\n e.printStackTrace();\n }\n }\n\n }\n //--------------------------------------------------------------------------\n // Protected Methods:\n //--------------------------------------------------------------------------\n /**\n * Gets an input stream for the corresponding file.\n *\n * @param file The file to create the input stream from.\n * @return InputStream\n */\n protected InputStream getInputStream(File file) throws IOException,\n FileNotFoundException {\n BufferedInputStream reader =\n new BufferedInputStream(new FileInputStream(file));\n\n return reader;\n }\n\n /**\n * Gets an input stream for the corresponding URL.\n *\n * @param url The url to create the input stream from.\n * @return InputStream\n */\n protected InputStream getInputStream(URL url) throws IOException {\n return url.openStream();\n }\n\n /**\n * Adds an object to the mru.\n */\n protected void setMRU(Object o) {\n int index = _mruFileList.indexOf(o);\n\n if (index == -1) {\n _mruFileList.add(0, o);\n setMaxSize(_maxSize);\n } else {\n moveToTop(index);\n }\n }\n\n /**\n * Loads the MRU file list in from a file and stores it in a LinkedList.\n * If no file exists, a new LinkedList is created.\n */\n protected void load() {\n createConfigurationDirectory();\n File file = new File(getFilename());\n if (file.exists()) {\n try {\n ObjectInputStream ois = new ObjectInputStream(\n new FileInputStream(file));\n _mruFileList = (LinkedList) ois.readObject();\n ois.close();\n\n // check that only files and url are in linked list\n Iterator it = _mruFileList.iterator();\n while (it.hasNext()) {\n Object o = it.next();\n if (!(o instanceof File) && !(o instanceof URL)) {\n it.remove();\n }\n }\n } catch (Exception e) {\n _mruFileList = new LinkedList();\n }\n } else {\n _mruFileList = new LinkedList();\n }\n\n }\n\n protected String getFilename() {\n String home = System.getProperty(\"user.home\");\n String sep = System.getProperty(\"file.separator\");\n\n return home + sep + \"lf5\" + sep + CONFIG_FILE_NAME;\n }\n\n /**\n * Ensures that the MRU list will have a MaxSize.\n */\n protected void setMaxSize(int maxSize) {\n if (maxSize < _mruFileList.size()) {\n for (int i = 0; i < _mruFileList.size() - maxSize; i++) {\n _mruFileList.removeLast();\n }\n }\n\n _maxSize = maxSize;\n }\n //--------------------------------------------------------------------------\n // Private Methods:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Nested Top-Level Classes or Interfaces\n //--------------------------------------------------------------------------\n}", "file_name": "MRUFileManager.java", "human_label": "Create the \"lf5\" directory in the Documents and Settings directory on Windows machines, or the user.home variable points on all other platforms.", "level": "slib_runnable", "lineno": "176", "name": "createConfigurationDirectory", "oracle_context": "{ \"apis\" : \"[getProperty, exists, mkdir, printStackTrace]\", \"classes\" : \"[String, File]\", \"vars\" : \"[]\" }", "package": "org.apache.log4j.lf5.viewer.configure", "project": "logging-log4j1-main" }, { "_id": "636766f81a6d9265ec01775b", "all_context": "{ \"class_level\" : \"import java.io.ByteArrayOutputStream;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nint SKIP_CODE;\\nint SKIP_DEBUG;\\nint SKIP_FRAMES;\\nint EXPAND_FRAMES;\\nint EXPAND_ASM_INSNS;\\nint INPUT_STREAM_DATA_CHUNK_SIZE;\\nbyte[] b;\\nbyte[] classFileBuffer;\\nint[] cpInfoOffsets;\\nString[] constantUtf8Values;\\nConstantDynamic[] constantDynamicValues;\\nint[] bootstrapMethodOffsets;\\nint maxStringLength;\\nint header;\\nClassReader(byte[] classFile);\\nClassReader(byte[] classFileBuffer,int classFileOffset,int classFileLength);\\nClassReader(byte[] classFileBuffer,int classFileOffset,boolean checkClassVersion);\\nClassReader(InputStream inputStream);\\nClassReader(String className);\\ngetAccess();\\ngetClassName();\\ngetSuperName();\\ngetInterfaces();\\naccept(ClassVisitor classVisitor,int parsingOptions);\\naccept(ClassVisitor classVisitor,Attribute[] attributePrototypes,int parsingOptions);\\nreadModuleAttributes(ClassVisitor classVisitor,Context context,int moduleOffset,int modulePackagesOffset,String moduleMainClass);\\nreadRecordComponent(ClassVisitor classVisitor,Context context,int recordComponentOffset);\\nreadField(ClassVisitor classVisitor,Context context,int fieldInfoOffset);\\nreadMethod(ClassVisitor classVisitor,Context context,int methodInfoOffset);\\nreadCode(MethodVisitor methodVisitor,Context context,int codeOffset);\\nreadLabel(int bytecodeOffset,Label[] labels);\\ncreateLabel(int bytecodeOffset,Label[] labels);\\ncreateDebugLabel(int bytecodeOffset,Label[] labels);\\nreadTypeAnnotations(MethodVisitor methodVisitor,Context context,int runtimeTypeAnnotationsOffset,boolean visible);\\ngetTypeAnnotationBytecodeOffset(int[] typeAnnotationOffsets,int typeAnnotationIndex);\\nreadTypeAnnotationTarget(Context context,int typeAnnotationOffset);\\nreadParameterAnnotations(MethodVisitor methodVisitor,Context context,int runtimeParameterAnnotationsOffset,boolean visible);\\nreadElementValues(AnnotationVisitor annotationVisitor,int annotationOffset,boolean named,char[] charBuffer);\\nreadElementValue(AnnotationVisitor annotationVisitor,int elementValueOffset,String elementName,char[] charBuffer);\\ncomputeImplicitFrame(Context context);\\nreadStackMapFrame(int stackMapFrameOffset,boolean compressed,boolean expand,Context context);\\nreadVerificationTypeInfo(int verificationTypeInfoOffset,Object[] frame,int index,char[] charBuffer,Label[] labels);\\ngetFirstAttributeOffset();\\nreadBootstrapMethodsAttribute(int maxStringLength);\\nreadAttribute(Attribute[] attributePrototypes,String type,int offset,int length,char[] charBuffer,int codeAttributeOffset,Label[] labels);\\ngetItemCount();\\ngetItem(int constantPoolEntryIndex);\\ngetMaxStringLength();\\nreadByte(int offset);\\nreadUnsignedShort(int offset);\\nreadShort(int offset);\\nreadInt(int offset);\\nreadLong(int offset);\\nreadUTF8(int offset,char[] charBuffer);\\nreadUtf(int constantPoolEntryIndex,char[] charBuffer);\\nreadUtf(int utfOffset,int utfLength,char[] charBuffer);\\nreadStringish(int offset,char[] charBuffer);\\nreadClass(int offset,char[] charBuffer);\\nreadModule(int offset,char[] charBuffer);\\nreadPackage(int offset,char[] charBuffer);\\nreadConstantDynamic(int constantPoolEntryIndex,char[] charBuffer);\\nreadConst(int constantPoolEntryIndex,char[] charBuffer);\\nreadStream(InputStream inputStream,boolean close);\\n\", \"repo_level\" : \"\" }", "class_name": "ClassReader", "code": "public long readLong(final int offset){\n long l1=readInt(offset);\n long l0=readInt(offset + 4) & 0xFFFFFFFFL;\n return (l1 << 32) | l0;\n}\n", "docstring": "/** \n * Reads a signed long value in this {@link ClassReader}. This method is intended for {@link Attribute} sub classes, and is normally not needed by class generators or adapters.\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n", "end_lineno": "3134", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage net.hasor.utils.asm;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/**\n * A parser to make a {@link ClassVisitor} visit a ClassFile structure, as defined in the Java\n * Virtual Machine Specification (JVMS). This class parses the ClassFile content and calls the\n * appropriate visit methods of a given {@link ClassVisitor} for each field, method and bytecode\n * instruction encountered.\n *\n * @see JVMS 4\n * @author Eric Bruneton\n * @author Eugene Kuleshov\n */\npublic class ClassReader {\n /**\n * A flag to skip the Code attributes. If this flag is set the Code attributes are neither parsed\n * nor visited.\n */\n public static final int SKIP_CODE = 1;\n /**\n * A flag to skip the SourceFile, SourceDebugExtension, LocalVariableTable,\n * LocalVariableTypeTable, LineNumberTable and MethodParameters attributes. If this flag is set\n * these attributes are neither parsed nor visited (i.e. {@link ClassVisitor#visitSource}, {@link\n * MethodVisitor#visitLocalVariable}, {@link MethodVisitor#visitLineNumber} and {@link\n * MethodVisitor#visitParameter} are not called).\n */\n public static final int SKIP_DEBUG = 2;\n /**\n * A flag to skip the StackMap and StackMapTable attributes. If this flag is set these attributes\n * are neither parsed nor visited (i.e. {@link MethodVisitor#visitFrame} is not called). This flag\n * is useful when the {@link ClassWriter#COMPUTE_FRAMES} option is used: it avoids visiting frames\n * that will be ignored and recomputed from scratch.\n */\n public static final int SKIP_FRAMES = 4;\n /**\n * A flag to expand the stack map frames. By default stack map frames are visited in their\n * original format (i.e. \"expanded\" for classes whose version is less than V1_6, and \"compressed\"\n * for the other classes). If this flag is set, stack map frames are always visited in expanded\n * format (this option adds a decompression/compression step in ClassReader and ClassWriter which\n * degrades performance quite a lot).\n */\n public static final int EXPAND_FRAMES = 8;\n /**\n * A flag to expand the ASM specific instructions into an equivalent sequence of standard bytecode\n * instructions. When resolving a forward jump it may happen that the signed 2 bytes offset\n * reserved for it is not sufficient to store the bytecode offset. In this case the jump\n * instruction is replaced with a temporary ASM specific instruction using an unsigned 2 bytes\n * offset (see {@link Label#resolve}). This internal flag is used to re-read classes containing\n * such instructions, in order to replace them with standard instructions. In addition, when this\n * flag is used, goto_w and jsr_w are not converted into goto and jsr, to make sure that\n * infinite loops where a goto_w is replaced with a goto in ClassReader and converted back to a\n * goto_w in ClassWriter cannot occur.\n */\n static final int EXPAND_ASM_INSNS = 256;\n /** The size of the temporary byte array used to read class input streams chunk by chunk. */\n private static final int INPUT_STREAM_DATA_CHUNK_SIZE = 4096;\n /**\n * A byte array containing the JVMS ClassFile structure to be parsed.\n *\n * @deprecated Use {@link #readByte(int)} and the other read methods instead. This field will\n * eventually be deleted.\n */\n @Deprecated\n // DontCheck(MemberName): can't be renamed (for backward binary compatibility).\n public final byte[] b;\n /**\n * A byte array containing the JVMS ClassFile structure to be parsed. The content of this array\n * must not be modified. This field is intended for {@link Attribute} sub classes, and is normally\n * not needed by class visitors.\n *\n *

NOTE: the ClassFile structure can start at any offset within this array, i.e. it does not\n * necessarily start at offset 0. Use {@link #getItem} and {@link #header} to get correct\n * ClassFile element offsets within this byte array.\n */\n final byte[] classFileBuffer;\n /**\n * The offset in bytes, in {@link #classFileBuffer}, of each cp_info entry of the ClassFile's\n * constant_pool array, plus one. In other words, the offset of constant pool entry i is\n * given by cpInfoOffsets[i] - 1, i.e. its cp_info's tag field is given by b[cpInfoOffsets[i] -\n * 1].\n */\n private final int[] cpInfoOffsets;\n /**\n * The String objects corresponding to the CONSTANT_Utf8 constant pool items. This cache avoids\n * multiple parsing of a given CONSTANT_Utf8 constant pool item.\n */\n private final String[] constantUtf8Values;\n /**\n * The ConstantDynamic objects corresponding to the CONSTANT_Dynamic constant pool items. This\n * cache avoids multiple parsing of a given CONSTANT_Dynamic constant pool item.\n */\n private final ConstantDynamic[] constantDynamicValues;\n /**\n * The start offsets in {@link #classFileBuffer} of each element of the bootstrap_methods array\n * (in the BootstrapMethods attribute).\n *\n * @see JVMS\n * 4.7.23\n */\n private final int[] bootstrapMethodOffsets;\n /**\n * A conservative estimate of the maximum length of the strings contained in the constant pool of\n * the class.\n */\n private final int maxStringLength;\n /** The offset in bytes of the ClassFile's access_flags field. */\n public final int header;\n // -----------------------------------------------------------------------------------------------\n // Constructors\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param classFile the JVMS ClassFile structure to be read.\n */\n public ClassReader(final byte[] classFile) {\n this(classFile, 0, classFile.length);\n }\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read.\n * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read.\n * @param classFileLength the length in bytes of the ClassFile to be read.\n */\n public ClassReader(final byte[] classFileBuffer, final int classFileOffset, final int classFileLength) { // NOPMD(UnusedFormalParameter) used for backward compatibility.\n this(classFileBuffer, classFileOffset, /* checkClassVersion = */ true);\n }\n\n /**\n * Constructs a new {@link ClassReader} object. This internal constructor must not be exposed\n * as a public API.\n *\n * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read.\n * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read.\n * @param checkClassVersion whether to check the class version or not.\n */\n ClassReader(final byte[] classFileBuffer, final int classFileOffset, final boolean checkClassVersion) {\n this.classFileBuffer = classFileBuffer;\n this.b = classFileBuffer;\n // Check the class' major_version. This field is after the magic and minor_version fields, which\n // use 4 and 2 bytes respectively.\n if (checkClassVersion && readShort(classFileOffset + 6) > Opcodes.V15) {\n throw new IllegalArgumentException(\"Unsupported class file major version \" + readShort(classFileOffset + 6));\n }\n // Create the constant pool arrays. The constant_pool_count field is after the magic,\n // minor_version and major_version fields, which use 4, 2 and 2 bytes respectively.\n int constantPoolCount = readUnsignedShort(classFileOffset + 8);\n cpInfoOffsets = new int[constantPoolCount];\n constantUtf8Values = new String[constantPoolCount];\n // Compute the offset of each constant pool entry, as well as a conservative estimate of the\n // maximum length of the constant pool strings. The first constant pool entry is after the\n // magic, minor_version, major_version and constant_pool_count fields, which use 4, 2, 2 and 2\n // bytes respectively.\n int currentCpInfoIndex = 1;\n int currentCpInfoOffset = classFileOffset + 10;\n int currentMaxStringLength = 0;\n boolean hasBootstrapMethods = false;\n boolean hasConstantDynamic = false;\n // The offset of the other entries depend on the total size of all the previous entries.\n while (currentCpInfoIndex < constantPoolCount) {\n cpInfoOffsets[currentCpInfoIndex++] = currentCpInfoOffset + 1;\n int cpInfoSize;\n switch (classFileBuffer[currentCpInfoOffset]) {\n case Symbol.CONSTANT_FIELDREF_TAG:\n case Symbol.CONSTANT_METHODREF_TAG:\n case Symbol.CONSTANT_INTERFACE_METHODREF_TAG:\n case Symbol.CONSTANT_INTEGER_TAG:\n case Symbol.CONSTANT_FLOAT_TAG:\n case Symbol.CONSTANT_NAME_AND_TYPE_TAG:\n cpInfoSize = 5;\n break;\n case Symbol.CONSTANT_DYNAMIC_TAG:\n cpInfoSize = 5;\n hasBootstrapMethods = true;\n hasConstantDynamic = true;\n break;\n case Symbol.CONSTANT_INVOKE_DYNAMIC_TAG:\n cpInfoSize = 5;\n hasBootstrapMethods = true;\n break;\n case Symbol.CONSTANT_LONG_TAG:\n case Symbol.CONSTANT_DOUBLE_TAG:\n cpInfoSize = 9;\n currentCpInfoIndex++;\n break;\n case Symbol.CONSTANT_UTF8_TAG:\n cpInfoSize = 3 + readUnsignedShort(currentCpInfoOffset + 1);\n if (cpInfoSize > currentMaxStringLength) {\n // The size in bytes of this CONSTANT_Utf8 structure provides a conservative estimate\n // of the length in characters of the corresponding string, and is much cheaper to\n // compute than this exact length.\n currentMaxStringLength = cpInfoSize;\n }\n break;\n case Symbol.CONSTANT_METHOD_HANDLE_TAG:\n cpInfoSize = 4;\n break;\n case Symbol.CONSTANT_CLASS_TAG:\n case Symbol.CONSTANT_STRING_TAG:\n case Symbol.CONSTANT_METHOD_TYPE_TAG:\n case Symbol.CONSTANT_PACKAGE_TAG:\n case Symbol.CONSTANT_MODULE_TAG:\n cpInfoSize = 3;\n break;\n default:\n throw new IllegalArgumentException();\n }\n currentCpInfoOffset += cpInfoSize;\n }\n maxStringLength = currentMaxStringLength;\n // The Classfile's access_flags field is just after the last constant pool entry.\n header = currentCpInfoOffset;\n // Allocate the cache of ConstantDynamic values, if there is at least one.\n constantDynamicValues = hasConstantDynamic ? new ConstantDynamic[constantPoolCount] : null;\n // Read the BootstrapMethods attribute, if any (only get the offset of each method).\n bootstrapMethodOffsets = hasBootstrapMethods ? readBootstrapMethodsAttribute(currentMaxStringLength) : null;\n }\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param inputStream an input stream of the JVMS ClassFile structure to be read. This input\n * stream must contain nothing more than the ClassFile structure itself. It is read from its\n * current position to its end.\n * @throws IOException if a problem occurs during reading.\n */\n public ClassReader(final InputStream inputStream) throws IOException {\n this(readStream(inputStream, false));\n }\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param className the fully qualified name of the class to be read. The ClassFile structure is\n * retrieved with the current class loader's {@link ClassLoader#getSystemResourceAsStream}.\n * @throws IOException if an exception occurs during reading.\n */\n public ClassReader(final String className) throws IOException {\n this(readStream(ClassLoader.getSystemResourceAsStream(className.replace('.', '/') + \".class\"), true));\n }\n\n /**\n * Reads the given input stream and returns its content as a byte array.\n *\n * @param inputStream an input stream.\n * @param close true to close the input stream after reading.\n * @return the content of the given input stream.\n * @throws IOException if a problem occurs during reading.\n */\n private static byte[] readStream(final InputStream inputStream, final boolean close) throws IOException {\n if (inputStream == null) {\n throw new IOException(\"Class not found\");\n }\n try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {\n byte[] data = new byte[INPUT_STREAM_DATA_CHUNK_SIZE];\n int bytesRead;\n while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {\n outputStream.write(data, 0, bytesRead);\n }\n outputStream.flush();\n return outputStream.toByteArray();\n } finally {\n if (close) {\n inputStream.close();\n }\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Accessors\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the class's access flags (see {@link Opcodes}). This value may not reflect Deprecated\n * and Synthetic flags when bytecode is before 1.5 and those flags are represented by attributes.\n *\n * @return the class access flags.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public int getAccess() {\n return readUnsignedShort(header);\n }\n\n /**\n * Returns the internal name of the class (see {@link Type#getInternalName()}).\n *\n * @return the internal class name.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public String getClassName() {\n // this_class is just after the access_flags field (using 2 bytes).\n return readClass(header + 2, new char[maxStringLength]);\n }\n\n /**\n * Returns the internal of name of the super class (see {@link Type#getInternalName()}). For\n * interfaces, the super class is {@link Object}.\n *\n * @return the internal name of the super class, or {@literal null} for {@link Object} class.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public String getSuperName() {\n // super_class is after the access_flags and this_class fields (2 bytes each).\n return readClass(header + 4, new char[maxStringLength]);\n }\n\n /**\n * Returns the internal names of the implemented interfaces (see {@link Type#getInternalName()}).\n *\n * @return the internal names of the directly implemented interfaces. Inherited implemented\n * interfaces are not returned.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public String[] getInterfaces() {\n // interfaces_count is after the access_flags, this_class and super_class fields (2 bytes each).\n int currentOffset = header + 6;\n int interfacesCount = readUnsignedShort(currentOffset);\n String[] interfaces = new String[interfacesCount];\n if (interfacesCount > 0) {\n char[] charBuffer = new char[maxStringLength];\n for (int i = 0; i < interfacesCount; ++i) {\n currentOffset += 2;\n interfaces[i] = readClass(currentOffset, charBuffer);\n }\n }\n return interfaces;\n }\n // -----------------------------------------------------------------------------------------------\n // Public methods\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this\n * {@link ClassReader}.\n *\n * @param classVisitor the visitor that must visit this class.\n * @param parsingOptions the options to use to parse this class. One or more of {@link\n * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}.\n */\n public void accept(final ClassVisitor classVisitor, final int parsingOptions) {\n accept(classVisitor, new Attribute[0], parsingOptions);\n }\n\n /**\n * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this\n * {@link ClassReader}.\n *\n * @param classVisitor the visitor that must visit this class.\n * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of\n * the class. Any attribute whose type is not equal to the type of one the prototypes will not\n * be parsed: its byte array value will be passed unchanged to the ClassWriter. This may\n * corrupt it if this value contains references to the constant pool, or has syntactic or\n * semantic links with a class element that has been transformed by a class adapter between\n * the reader and the writer.\n * @param parsingOptions the options to use to parse this class. One or more of {@link\n * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}.\n */\n public void accept(final ClassVisitor classVisitor, final Attribute[] attributePrototypes, final int parsingOptions) {\n Context context = new Context();\n context.attributePrototypes = attributePrototypes;\n context.parsingOptions = parsingOptions;\n context.charBuffer = new char[maxStringLength];\n // Read the access_flags, this_class, super_class, interface_count and interfaces fields.\n char[] charBuffer = context.charBuffer;\n int currentOffset = header;\n int accessFlags = readUnsignedShort(currentOffset);\n String thisClass = readClass(currentOffset + 2, charBuffer);\n String superClass = readClass(currentOffset + 4, charBuffer);\n String[] interfaces = new String[readUnsignedShort(currentOffset + 6)];\n currentOffset += 8;\n for (int i = 0; i < interfaces.length; ++i) {\n interfaces[i] = readClass(currentOffset, charBuffer);\n currentOffset += 2;\n }\n // Read the class attributes (the variables are ordered as in Section 4.7 of the JVMS).\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The offset of the InnerClasses attribute, or 0.\n int innerClassesOffset = 0;\n // - The offset of the EnclosingMethod attribute, or 0.\n int enclosingMethodOffset = 0;\n // - The string corresponding to the Signature attribute, or null.\n String signature = null;\n // - The string corresponding to the SourceFile attribute, or null.\n String sourceFile = null;\n // - The string corresponding to the SourceDebugExtension attribute, or null.\n String sourceDebugExtension = null;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The offset of the Module attribute, or 0.\n int moduleOffset = 0;\n // - The offset of the ModulePackages attribute, or 0.\n int modulePackagesOffset = 0;\n // - The string corresponding to the ModuleMainClass attribute, or null.\n String moduleMainClass = null;\n // - The string corresponding to the NestHost attribute, or null.\n String nestHostClass = null;\n // - The offset of the NestMembers attribute, or 0.\n int nestMembersOffset = 0;\n // - The offset of the PermittedSubtypes attribute, or 0\n int permittedSubtypesOffset = 0;\n // - The offset of the Record attribute, or 0.\n int recordOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int currentAttributeOffset = getFirstAttributeOffset();\n for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentAttributeOffset, charBuffer);\n int attributeLength = readInt(currentAttributeOffset + 2);\n currentAttributeOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.SOURCE_FILE.equals(attributeName)) {\n sourceFile = readUTF8(currentAttributeOffset, charBuffer);\n } else if (Constants.INNER_CLASSES.equals(attributeName)) {\n innerClassesOffset = currentAttributeOffset;\n } else if (Constants.ENCLOSING_METHOD.equals(attributeName)) {\n enclosingMethodOffset = currentAttributeOffset;\n } else if (Constants.NEST_HOST.equals(attributeName)) {\n nestHostClass = readClass(currentAttributeOffset, charBuffer);\n } else if (Constants.NEST_MEMBERS.equals(attributeName)) {\n nestMembersOffset = currentAttributeOffset;\n } else if (Constants.PERMITTED_SUBTYPES.equals(attributeName)) {\n permittedSubtypesOffset = currentAttributeOffset;\n } else if (Constants.SIGNATURE.equals(attributeName)) {\n signature = readUTF8(currentAttributeOffset, charBuffer);\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.SYNTHETIC.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_SYNTHETIC;\n } else if (Constants.SOURCE_DEBUG_EXTENSION.equals(attributeName)) {\n sourceDebugExtension = readUtf(currentAttributeOffset, attributeLength, new char[attributeLength]);\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.RECORD.equals(attributeName)) {\n recordOffset = currentAttributeOffset;\n } else if (Constants.MODULE.equals(attributeName)) {\n moduleOffset = currentAttributeOffset;\n } else if (Constants.MODULE_MAIN_CLASS.equals(attributeName)) {\n moduleMainClass = readClass(currentAttributeOffset, charBuffer);\n } else if (Constants.MODULE_PACKAGES.equals(attributeName)) {\n modulePackagesOffset = currentAttributeOffset;\n } else if (!Constants.BOOTSTRAP_METHODS.equals(attributeName)) {\n // The BootstrapMethods attribute is read in the constructor.\n Attribute attribute = readAttribute(attributePrototypes, attributeName, currentAttributeOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentAttributeOffset += attributeLength;\n }\n // Visit the class declaration. The minor_version and major_version fields start 6 bytes before\n // the first constant pool entry, which itself starts at cpInfoOffsets[1] - 1 (by definition).\n classVisitor.visit(readInt(cpInfoOffsets[1] - 7), accessFlags, thisClass, signature, superClass, interfaces);\n // Visit the SourceFile and SourceDebugExtenstion attributes.\n if ((parsingOptions & SKIP_DEBUG) == 0 && (sourceFile != null || sourceDebugExtension != null)) {\n classVisitor.visitSource(sourceFile, sourceDebugExtension);\n }\n // Visit the Module, ModulePackages and ModuleMainClass attributes.\n if (moduleOffset != 0) {\n readModuleAttributes(classVisitor, context, moduleOffset, modulePackagesOffset, moduleMainClass);\n }\n // Visit the NestHost attribute.\n if (nestHostClass != null) {\n classVisitor.visitNestHost(nestHostClass);\n }\n // Visit the EnclosingMethod attribute.\n if (enclosingMethodOffset != 0) {\n String className = readClass(enclosingMethodOffset, charBuffer);\n int methodIndex = readUnsignedShort(enclosingMethodOffset + 2);\n String name = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex], charBuffer);\n String type = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex] + 2, charBuffer);\n classVisitor.visitOuterClass(className, name, type);\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in ClassWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n classVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the NestedMembers attribute.\n if (nestMembersOffset != 0) {\n int numberOfNestMembers = readUnsignedShort(nestMembersOffset);\n int currentNestMemberOffset = nestMembersOffset + 2;\n while (numberOfNestMembers-- > 0) {\n classVisitor.visitNestMember(readClass(currentNestMemberOffset, charBuffer));\n currentNestMemberOffset += 2;\n }\n }\n // Visit the PermittedSubtypes attribute.\n if (permittedSubtypesOffset != 0) {\n int numberOfPermittedSubtypes = readUnsignedShort(permittedSubtypesOffset);\n int currentPermittedSubtypeOffset = permittedSubtypesOffset + 2;\n while (numberOfPermittedSubtypes-- > 0) {\n classVisitor.visitPermittedSubtypeExperimental(readClass(currentPermittedSubtypeOffset, charBuffer));\n currentPermittedSubtypeOffset += 2;\n }\n }\n // Visit the InnerClasses attribute.\n if (innerClassesOffset != 0) {\n int numberOfClasses = readUnsignedShort(innerClassesOffset);\n int currentClassesOffset = innerClassesOffset + 2;\n while (numberOfClasses-- > 0) {\n classVisitor.visitInnerClass(readClass(currentClassesOffset, charBuffer), readClass(currentClassesOffset + 2, charBuffer), readUTF8(currentClassesOffset + 4, charBuffer), readUnsignedShort(currentClassesOffset + 6));\n currentClassesOffset += 8;\n }\n }\n // Visit Record components.\n if (recordOffset != 0) {\n int recordComponentsCount = readUnsignedShort(recordOffset);\n recordOffset += 2;\n while (recordComponentsCount-- > 0) {\n recordOffset = readRecordComponent(classVisitor, context, recordOffset);\n }\n }\n // Visit the fields and methods.\n int fieldsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (fieldsCount-- > 0) {\n currentOffset = readField(classVisitor, context, currentOffset);\n }\n int methodsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (methodsCount-- > 0) {\n currentOffset = readMethod(classVisitor, context, currentOffset);\n }\n // Visit the end of the class.\n classVisitor.visitEnd();\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse modules, fields and methods\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Reads the Module, ModulePackages and ModuleMainClass attributes and visit them.\n *\n * @param classVisitor the current class visitor\n * @param context information about the class being parsed.\n * @param moduleOffset the offset of the Module attribute (excluding the attribute_info's\n * attribute_name_index and attribute_length fields).\n * @param modulePackagesOffset the offset of the ModulePackages attribute (excluding the\n * attribute_info's attribute_name_index and attribute_length fields), or 0.\n * @param moduleMainClass the string corresponding to the ModuleMainClass attribute, or {@literal\n * null}.\n */\n private void readModuleAttributes(final ClassVisitor classVisitor, final Context context, final int moduleOffset, final int modulePackagesOffset, final String moduleMainClass) {\n char[] buffer = context.charBuffer;\n // Read the module_name_index, module_flags and module_version_index fields and visit them.\n int currentOffset = moduleOffset;\n String moduleName = readModule(currentOffset, buffer);\n int moduleFlags = readUnsignedShort(currentOffset + 2);\n String moduleVersion = readUTF8(currentOffset + 4, buffer);\n currentOffset += 6;\n ModuleVisitor moduleVisitor = classVisitor.visitModule(moduleName, moduleFlags, moduleVersion);\n if (moduleVisitor == null) {\n return;\n }\n // Visit the ModuleMainClass attribute.\n if (moduleMainClass != null) {\n moduleVisitor.visitMainClass(moduleMainClass);\n }\n // Visit the ModulePackages attribute.\n if (modulePackagesOffset != 0) {\n int packageCount = readUnsignedShort(modulePackagesOffset);\n int currentPackageOffset = modulePackagesOffset + 2;\n while (packageCount-- > 0) {\n moduleVisitor.visitPackage(readPackage(currentPackageOffset, buffer));\n currentPackageOffset += 2;\n }\n }\n // Read the 'requires_count' and 'requires' fields.\n int requiresCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (requiresCount-- > 0) {\n // Read the requires_index, requires_flags and requires_version fields and visit them.\n String requires = readModule(currentOffset, buffer);\n int requiresFlags = readUnsignedShort(currentOffset + 2);\n String requiresVersion = readUTF8(currentOffset + 4, buffer);\n currentOffset += 6;\n moduleVisitor.visitRequire(requires, requiresFlags, requiresVersion);\n }\n // Read the 'exports_count' and 'exports' fields.\n int exportsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (exportsCount-- > 0) {\n // Read the exports_index, exports_flags, exports_to_count and exports_to_index fields\n // and visit them.\n String exports = readPackage(currentOffset, buffer);\n int exportsFlags = readUnsignedShort(currentOffset + 2);\n int exportsToCount = readUnsignedShort(currentOffset + 4);\n currentOffset += 6;\n String[] exportsTo = null;\n if (exportsToCount != 0) {\n exportsTo = new String[exportsToCount];\n for (int i = 0; i < exportsToCount; ++i) {\n exportsTo[i] = readModule(currentOffset, buffer);\n currentOffset += 2;\n }\n }\n moduleVisitor.visitExport(exports, exportsFlags, exportsTo);\n }\n // Reads the 'opens_count' and 'opens' fields.\n int opensCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (opensCount-- > 0) {\n // Read the opens_index, opens_flags, opens_to_count and opens_to_index fields and visit them.\n String opens = readPackage(currentOffset, buffer);\n int opensFlags = readUnsignedShort(currentOffset + 2);\n int opensToCount = readUnsignedShort(currentOffset + 4);\n currentOffset += 6;\n String[] opensTo = null;\n if (opensToCount != 0) {\n opensTo = new String[opensToCount];\n for (int i = 0; i < opensToCount; ++i) {\n opensTo[i] = readModule(currentOffset, buffer);\n currentOffset += 2;\n }\n }\n moduleVisitor.visitOpen(opens, opensFlags, opensTo);\n }\n // Read the 'uses_count' and 'uses' fields.\n int usesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (usesCount-- > 0) {\n moduleVisitor.visitUse(readClass(currentOffset, buffer));\n currentOffset += 2;\n }\n // Read the 'provides_count' and 'provides' fields.\n int providesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (providesCount-- > 0) {\n // Read the provides_index, provides_with_count and provides_with_index fields and visit them.\n String provides = readClass(currentOffset, buffer);\n int providesWithCount = readUnsignedShort(currentOffset + 2);\n currentOffset += 4;\n String[] providesWith = new String[providesWithCount];\n for (int i = 0; i < providesWithCount; ++i) {\n providesWith[i] = readClass(currentOffset, buffer);\n currentOffset += 2;\n }\n moduleVisitor.visitProvide(provides, providesWith);\n }\n // Visit the end of the module attributes.\n moduleVisitor.visitEnd();\n }\n\n /**\n * Reads a record component and visit it.\n *\n * @param classVisitor the current class visitor\n * @param context information about the class being parsed.\n * @param recordComponentOffset the offset of the current record component.\n * @return the offset of the first byte following the record component.\n */\n private int readRecordComponent(final ClassVisitor classVisitor, final Context context, final int recordComponentOffset) {\n char[] charBuffer = context.charBuffer;\n int currentOffset = recordComponentOffset;\n String name = readUTF8(currentOffset, charBuffer);\n String descriptor = readUTF8(currentOffset + 2, charBuffer);\n currentOffset += 4;\n // Read the record component attributes (the variables are ordered as in Section 4.7 of the\n // JVMS).\n int accessFlags = 0;\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The string corresponding to the Signature attribute, or null.\n String signature = null;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.SIGNATURE.equals(attributeName)) {\n signature = readUTF8(currentOffset, charBuffer);\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentOffset;\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n RecordComponentVisitor recordComponentVisitor = classVisitor.visitRecordComponentExperimental(accessFlags, name, descriptor, signature);\n if (recordComponentVisitor == null) {\n return currentOffset;\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitAnnotationExperimental(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitAnnotationExperimental(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitTypeAnnotationExperimental(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitTypeAnnotationExperimental(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in FieldWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n recordComponentVisitor.visitAttributeExperimental(attributes);\n attributes = nextAttribute;\n }\n // Visit the end of the field.\n recordComponentVisitor.visitEndExperimental();\n return currentOffset;\n }\n\n /**\n * Reads a JVMS field_info structure and makes the given visitor visit it.\n *\n * @param classVisitor the visitor that must visit the field.\n * @param context information about the class being parsed.\n * @param fieldInfoOffset the start offset of the field_info structure.\n * @return the offset of the first byte following the field_info structure.\n */\n private int readField(final ClassVisitor classVisitor, final Context context, final int fieldInfoOffset) {\n char[] charBuffer = context.charBuffer;\n // Read the access_flags, name_index and descriptor_index fields.\n int currentOffset = fieldInfoOffset;\n int accessFlags = readUnsignedShort(currentOffset);\n String name = readUTF8(currentOffset + 2, charBuffer);\n String descriptor = readUTF8(currentOffset + 4, charBuffer);\n currentOffset += 6;\n // Read the field attributes (the variables are ordered as in Section 4.7 of the JVMS).\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The value corresponding to the ConstantValue attribute, or null.\n Object constantValue = null;\n // - The string corresponding to the Signature attribute, or null.\n String signature = null;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.CONSTANT_VALUE.equals(attributeName)) {\n int constantvalueIndex = readUnsignedShort(currentOffset);\n constantValue = constantvalueIndex == 0 ? null : readConst(constantvalueIndex, charBuffer);\n } else if (Constants.SIGNATURE.equals(attributeName)) {\n signature = readUTF8(currentOffset, charBuffer);\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.SYNTHETIC.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_SYNTHETIC;\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentOffset;\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n // Visit the field declaration.\n FieldVisitor fieldVisitor = classVisitor.visitField(accessFlags, name, descriptor, signature, constantValue);\n if (fieldVisitor == null) {\n return currentOffset;\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in FieldWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n fieldVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the end of the field.\n fieldVisitor.visitEnd();\n return currentOffset;\n }\n\n /**\n * Reads a JVMS method_info structure and makes the given visitor visit it.\n *\n * @param classVisitor the visitor that must visit the method.\n * @param context information about the class being parsed.\n * @param methodInfoOffset the start offset of the method_info structure.\n * @return the offset of the first byte following the method_info structure.\n */\n private int readMethod(final ClassVisitor classVisitor, final Context context, final int methodInfoOffset) {\n char[] charBuffer = context.charBuffer;\n // Read the access_flags, name_index and descriptor_index fields.\n int currentOffset = methodInfoOffset;\n context.currentMethodAccessFlags = readUnsignedShort(currentOffset);\n context.currentMethodName = readUTF8(currentOffset + 2, charBuffer);\n context.currentMethodDescriptor = readUTF8(currentOffset + 4, charBuffer);\n currentOffset += 6;\n // Read the method attributes (the variables are ordered as in Section 4.7 of the JVMS).\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The offset of the Code attribute, or 0.\n int codeOffset = 0;\n // - The offset of the Exceptions attribute, or 0.\n int exceptionsOffset = 0;\n // - The strings corresponding to the Exceptions attribute, or null.\n String[] exceptions = null;\n // - Whether the method has a Synthetic attribute.\n boolean synthetic = false;\n // - The constant pool index contained in the Signature attribute, or 0.\n int signatureIndex = 0;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleParameterAnnotations attribute, or 0.\n int runtimeVisibleParameterAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleParameterAnnotations attribute, or 0.\n int runtimeInvisibleParameterAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The offset of the AnnotationDefault attribute, or 0.\n int annotationDefaultOffset = 0;\n // - The offset of the MethodParameters attribute, or 0.\n int methodParametersOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.CODE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_CODE) == 0) {\n codeOffset = currentOffset;\n }\n } else if (Constants.EXCEPTIONS.equals(attributeName)) {\n exceptionsOffset = currentOffset;\n exceptions = new String[readUnsignedShort(exceptionsOffset)];\n int currentExceptionOffset = exceptionsOffset + 2;\n for (int i = 0; i < exceptions.length; ++i) {\n exceptions[i] = readClass(currentExceptionOffset, charBuffer);\n currentExceptionOffset += 2;\n }\n } else if (Constants.SIGNATURE.equals(attributeName)) {\n signatureIndex = readUnsignedShort(currentOffset);\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n context.currentMethodAccessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.ANNOTATION_DEFAULT.equals(attributeName)) {\n annotationDefaultOffset = currentOffset;\n } else if (Constants.SYNTHETIC.equals(attributeName)) {\n synthetic = true;\n context.currentMethodAccessFlags |= Opcodes.ACC_SYNTHETIC;\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleParameterAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleParameterAnnotationsOffset = currentOffset;\n } else if (Constants.METHOD_PARAMETERS.equals(attributeName)) {\n methodParametersOffset = currentOffset;\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n // Visit the method declaration.\n MethodVisitor methodVisitor = classVisitor.visitMethod(context.currentMethodAccessFlags, context.currentMethodName, context.currentMethodDescriptor, signatureIndex == 0 ? null : readUtf(signatureIndex, charBuffer), exceptions);\n if (methodVisitor == null) {\n return currentOffset;\n }\n // If the returned MethodVisitor is in fact a MethodWriter, it means there is no method\n // adapter between the reader and the writer. In this case, it might be possible to copy\n // the method attributes directly into the writer. If so, return early without visiting\n // the content of these attributes.\n if (methodVisitor instanceof MethodWriter) {\n MethodWriter methodWriter = (MethodWriter) methodVisitor;\n if (methodWriter.canCopyMethodAttributes(this, synthetic, (context.currentMethodAccessFlags & Opcodes.ACC_DEPRECATED) != 0, readUnsignedShort(methodInfoOffset + 4), signatureIndex, exceptionsOffset)) {\n methodWriter.setMethodAttributesSource(methodInfoOffset, currentOffset - methodInfoOffset);\n return currentOffset;\n }\n }\n // Visit the MethodParameters attribute.\n if (methodParametersOffset != 0 && (context.parsingOptions & SKIP_DEBUG) == 0) {\n int parametersCount = readByte(methodParametersOffset);\n int currentParameterOffset = methodParametersOffset + 1;\n while (parametersCount-- > 0) {\n // Read the name_index and access_flags fields and visit them.\n methodVisitor.visitParameter(readUTF8(currentParameterOffset, charBuffer), readUnsignedShort(currentParameterOffset + 2));\n currentParameterOffset += 4;\n }\n }\n // Visit the AnnotationDefault attribute.\n if (annotationDefaultOffset != 0) {\n AnnotationVisitor annotationVisitor = methodVisitor.visitAnnotationDefault();\n readElementValue(annotationVisitor, annotationDefaultOffset, null, charBuffer);\n if (annotationVisitor != null) {\n annotationVisitor.visitEnd();\n }\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleParameterAnnotations attribute.\n if (runtimeVisibleParameterAnnotationsOffset != 0) {\n readParameterAnnotations(methodVisitor, context, runtimeVisibleParameterAnnotationsOffset, /* visible = */ true);\n }\n // Visit the RuntimeInvisibleParameterAnnotations attribute.\n if (runtimeInvisibleParameterAnnotationsOffset != 0) {\n readParameterAnnotations(methodVisitor, context, runtimeInvisibleParameterAnnotationsOffset,\n /* visible = */ false);\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in MethodWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n methodVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the Code attribute.\n if (codeOffset != 0) {\n methodVisitor.visitCode();\n readCode(methodVisitor, context, codeOffset);\n }\n // Visit the end of the method.\n methodVisitor.visitEnd();\n return currentOffset;\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse a Code attribute\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Reads a JVMS 'Code' attribute and makes the given visitor visit it.\n *\n * @param methodVisitor the visitor that must visit the Code attribute.\n * @param context information about the class being parsed.\n * @param codeOffset the start offset in {@link #classFileBuffer} of the Code attribute, excluding\n * its attribute_name_index and attribute_length fields.\n */\n private void readCode(final MethodVisitor methodVisitor, final Context context, final int codeOffset) {\n int currentOffset = codeOffset;\n // Read the max_stack, max_locals and code_length fields.\n final byte[] classBuffer = classFileBuffer;\n final char[] charBuffer = context.charBuffer;\n final int maxStack = readUnsignedShort(currentOffset);\n final int maxLocals = readUnsignedShort(currentOffset + 2);\n final int codeLength = readInt(currentOffset + 4);\n currentOffset += 8;\n // Read the bytecode 'code' array to create a label for each referenced instruction.\n final int bytecodeStartOffset = currentOffset;\n final int bytecodeEndOffset = currentOffset + codeLength;\n final Label[] labels = context.currentMethodLabels = new Label[codeLength + 1];\n while (currentOffset < bytecodeEndOffset) {\n final int bytecodeOffset = currentOffset - bytecodeStartOffset;\n final int opcode = classBuffer[currentOffset] & 0xFF;\n switch (opcode) {\n case Constants.NOP:\n case Constants.ACONST_NULL:\n case Constants.ICONST_M1:\n case Constants.ICONST_0:\n case Constants.ICONST_1:\n case Constants.ICONST_2:\n case Constants.ICONST_3:\n case Constants.ICONST_4:\n case Constants.ICONST_5:\n case Constants.LCONST_0:\n case Constants.LCONST_1:\n case Constants.FCONST_0:\n case Constants.FCONST_1:\n case Constants.FCONST_2:\n case Constants.DCONST_0:\n case Constants.DCONST_1:\n case Constants.IALOAD:\n case Constants.LALOAD:\n case Constants.FALOAD:\n case Constants.DALOAD:\n case Constants.AALOAD:\n case Constants.BALOAD:\n case Constants.CALOAD:\n case Constants.SALOAD:\n case Constants.IASTORE:\n case Constants.LASTORE:\n case Constants.FASTORE:\n case Constants.DASTORE:\n case Constants.AASTORE:\n case Constants.BASTORE:\n case Constants.CASTORE:\n case Constants.SASTORE:\n case Constants.POP:\n case Constants.POP2:\n case Constants.DUP:\n case Constants.DUP_X1:\n case Constants.DUP_X2:\n case Constants.DUP2:\n case Constants.DUP2_X1:\n case Constants.DUP2_X2:\n case Constants.SWAP:\n case Constants.IADD:\n case Constants.LADD:\n case Constants.FADD:\n case Constants.DADD:\n case Constants.ISUB:\n case Constants.LSUB:\n case Constants.FSUB:\n case Constants.DSUB:\n case Constants.IMUL:\n case Constants.LMUL:\n case Constants.FMUL:\n case Constants.DMUL:\n case Constants.IDIV:\n case Constants.LDIV:\n case Constants.FDIV:\n case Constants.DDIV:\n case Constants.IREM:\n case Constants.LREM:\n case Constants.FREM:\n case Constants.DREM:\n case Constants.INEG:\n case Constants.LNEG:\n case Constants.FNEG:\n case Constants.DNEG:\n case Constants.ISHL:\n case Constants.LSHL:\n case Constants.ISHR:\n case Constants.LSHR:\n case Constants.IUSHR:\n case Constants.LUSHR:\n case Constants.IAND:\n case Constants.LAND:\n case Constants.IOR:\n case Constants.LOR:\n case Constants.IXOR:\n case Constants.LXOR:\n case Constants.I2L:\n case Constants.I2F:\n case Constants.I2D:\n case Constants.L2I:\n case Constants.L2F:\n case Constants.L2D:\n case Constants.F2I:\n case Constants.F2L:\n case Constants.F2D:\n case Constants.D2I:\n case Constants.D2L:\n case Constants.D2F:\n case Constants.I2B:\n case Constants.I2C:\n case Constants.I2S:\n case Constants.LCMP:\n case Constants.FCMPL:\n case Constants.FCMPG:\n case Constants.DCMPL:\n case Constants.DCMPG:\n case Constants.IRETURN:\n case Constants.LRETURN:\n case Constants.FRETURN:\n case Constants.DRETURN:\n case Constants.ARETURN:\n case Constants.RETURN:\n case Constants.ARRAYLENGTH:\n case Constants.ATHROW:\n case Constants.MONITORENTER:\n case Constants.MONITOREXIT:\n case Constants.ILOAD_0:\n case Constants.ILOAD_1:\n case Constants.ILOAD_2:\n case Constants.ILOAD_3:\n case Constants.LLOAD_0:\n case Constants.LLOAD_1:\n case Constants.LLOAD_2:\n case Constants.LLOAD_3:\n case Constants.FLOAD_0:\n case Constants.FLOAD_1:\n case Constants.FLOAD_2:\n case Constants.FLOAD_3:\n case Constants.DLOAD_0:\n case Constants.DLOAD_1:\n case Constants.DLOAD_2:\n case Constants.DLOAD_3:\n case Constants.ALOAD_0:\n case Constants.ALOAD_1:\n case Constants.ALOAD_2:\n case Constants.ALOAD_3:\n case Constants.ISTORE_0:\n case Constants.ISTORE_1:\n case Constants.ISTORE_2:\n case Constants.ISTORE_3:\n case Constants.LSTORE_0:\n case Constants.LSTORE_1:\n case Constants.LSTORE_2:\n case Constants.LSTORE_3:\n case Constants.FSTORE_0:\n case Constants.FSTORE_1:\n case Constants.FSTORE_2:\n case Constants.FSTORE_3:\n case Constants.DSTORE_0:\n case Constants.DSTORE_1:\n case Constants.DSTORE_2:\n case Constants.DSTORE_3:\n case Constants.ASTORE_0:\n case Constants.ASTORE_1:\n case Constants.ASTORE_2:\n case Constants.ASTORE_3:\n currentOffset += 1;\n break;\n case Constants.IFEQ:\n case Constants.IFNE:\n case Constants.IFLT:\n case Constants.IFGE:\n case Constants.IFGT:\n case Constants.IFLE:\n case Constants.IF_ICMPEQ:\n case Constants.IF_ICMPNE:\n case Constants.IF_ICMPLT:\n case Constants.IF_ICMPGE:\n case Constants.IF_ICMPGT:\n case Constants.IF_ICMPLE:\n case Constants.IF_ACMPEQ:\n case Constants.IF_ACMPNE:\n case Constants.GOTO:\n case Constants.JSR:\n case Constants.IFNULL:\n case Constants.IFNONNULL:\n createLabel(bytecodeOffset + readShort(currentOffset + 1), labels);\n currentOffset += 3;\n break;\n case Constants.ASM_IFEQ:\n case Constants.ASM_IFNE:\n case Constants.ASM_IFLT:\n case Constants.ASM_IFGE:\n case Constants.ASM_IFGT:\n case Constants.ASM_IFLE:\n case Constants.ASM_IF_ICMPEQ:\n case Constants.ASM_IF_ICMPNE:\n case Constants.ASM_IF_ICMPLT:\n case Constants.ASM_IF_ICMPGE:\n case Constants.ASM_IF_ICMPGT:\n case Constants.ASM_IF_ICMPLE:\n case Constants.ASM_IF_ACMPEQ:\n case Constants.ASM_IF_ACMPNE:\n case Constants.ASM_GOTO:\n case Constants.ASM_JSR:\n case Constants.ASM_IFNULL:\n case Constants.ASM_IFNONNULL:\n createLabel(bytecodeOffset + readUnsignedShort(currentOffset + 1), labels);\n currentOffset += 3;\n break;\n case Constants.GOTO_W:\n case Constants.JSR_W:\n case Constants.ASM_GOTO_W:\n createLabel(bytecodeOffset + readInt(currentOffset + 1), labels);\n currentOffset += 5;\n break;\n case Constants.WIDE:\n switch (classBuffer[currentOffset + 1] & 0xFF) {\n case Constants.ILOAD:\n case Constants.FLOAD:\n case Constants.ALOAD:\n case Constants.LLOAD:\n case Constants.DLOAD:\n case Constants.ISTORE:\n case Constants.FSTORE:\n case Constants.ASTORE:\n case Constants.LSTORE:\n case Constants.DSTORE:\n case Constants.RET:\n currentOffset += 4;\n break;\n case Constants.IINC:\n currentOffset += 6;\n break;\n default:\n throw new IllegalArgumentException();\n }\n break;\n case Constants.TABLESWITCH:\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (bytecodeOffset & 3);\n // Read the default label and the number of table entries.\n createLabel(bytecodeOffset + readInt(currentOffset), labels);\n int numTableEntries = readInt(currentOffset + 8) - readInt(currentOffset + 4) + 1;\n currentOffset += 12;\n // Read the table labels.\n while (numTableEntries-- > 0) {\n createLabel(bytecodeOffset + readInt(currentOffset), labels);\n currentOffset += 4;\n }\n break;\n case Constants.LOOKUPSWITCH:\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (bytecodeOffset & 3);\n // Read the default label and the number of switch cases.\n createLabel(bytecodeOffset + readInt(currentOffset), labels);\n int numSwitchCases = readInt(currentOffset + 4);\n currentOffset += 8;\n // Read the switch labels.\n while (numSwitchCases-- > 0) {\n createLabel(bytecodeOffset + readInt(currentOffset + 4), labels);\n currentOffset += 8;\n }\n break;\n case Constants.ILOAD:\n case Constants.LLOAD:\n case Constants.FLOAD:\n case Constants.DLOAD:\n case Constants.ALOAD:\n case Constants.ISTORE:\n case Constants.LSTORE:\n case Constants.FSTORE:\n case Constants.DSTORE:\n case Constants.ASTORE:\n case Constants.RET:\n case Constants.BIPUSH:\n case Constants.NEWARRAY:\n case Constants.LDC:\n currentOffset += 2;\n break;\n case Constants.SIPUSH:\n case Constants.LDC_W:\n case Constants.LDC2_W:\n case Constants.GETSTATIC:\n case Constants.PUTSTATIC:\n case Constants.GETFIELD:\n case Constants.PUTFIELD:\n case Constants.INVOKEVIRTUAL:\n case Constants.INVOKESPECIAL:\n case Constants.INVOKESTATIC:\n case Constants.NEW:\n case Constants.ANEWARRAY:\n case Constants.CHECKCAST:\n case Constants.INSTANCEOF:\n case Constants.IINC:\n currentOffset += 3;\n break;\n case Constants.INVOKEINTERFACE:\n case Constants.INVOKEDYNAMIC:\n currentOffset += 5;\n break;\n case Constants.MULTIANEWARRAY:\n currentOffset += 4;\n break;\n default:\n throw new IllegalArgumentException();\n }\n }\n // Read the 'exception_table_length' and 'exception_table' field to create a label for each\n // referenced instruction, and to make methodVisitor visit the corresponding try catch blocks.\n int exceptionTableLength = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (exceptionTableLength-- > 0) {\n Label start = createLabel(readUnsignedShort(currentOffset), labels);\n Label end = createLabel(readUnsignedShort(currentOffset + 2), labels);\n Label handler = createLabel(readUnsignedShort(currentOffset + 4), labels);\n String catchType = readUTF8(cpInfoOffsets[readUnsignedShort(currentOffset + 6)], charBuffer);\n currentOffset += 8;\n methodVisitor.visitTryCatchBlock(start, end, handler, catchType);\n }\n // Read the Code attributes to create a label for each referenced instruction (the variables\n // are ordered as in Section 4.7 of the JVMS). Attribute offsets exclude the\n // attribute_name_index and attribute_length fields.\n // - The offset of the current 'stack_map_frame' in the StackMap[Table] attribute, or 0.\n // Initially, this is the offset of the first 'stack_map_frame' entry. Then this offset is\n // updated after each stack_map_frame is read.\n int stackMapFrameOffset = 0;\n // - The end offset of the StackMap[Table] attribute, or 0.\n int stackMapTableEndOffset = 0;\n // - Whether the stack map frames are compressed (i.e. in a StackMapTable) or not.\n boolean compressedFrames = true;\n // - The offset of the LocalVariableTable attribute, or 0.\n int localVariableTableOffset = 0;\n // - The offset of the LocalVariableTypeTable attribute, or 0.\n int localVariableTypeTableOffset = 0;\n // - The offset of each 'type_annotation' entry in the RuntimeVisibleTypeAnnotations\n // attribute, or null.\n int[] visibleTypeAnnotationOffsets = null;\n // - The offset of each 'type_annotation' entry in the RuntimeInvisibleTypeAnnotations\n // attribute, or null.\n int[] invisibleTypeAnnotationOffsets = null;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n if (Constants.LOCAL_VARIABLE_TABLE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_DEBUG) == 0) {\n localVariableTableOffset = currentOffset;\n // Parse the attribute to find the corresponding (debug only) labels.\n int currentLocalVariableTableOffset = currentOffset;\n int localVariableTableLength = readUnsignedShort(currentLocalVariableTableOffset);\n currentLocalVariableTableOffset += 2;\n while (localVariableTableLength-- > 0) {\n int startPc = readUnsignedShort(currentLocalVariableTableOffset);\n createDebugLabel(startPc, labels);\n int length = readUnsignedShort(currentLocalVariableTableOffset + 2);\n createDebugLabel(startPc + length, labels);\n // Skip the name_index, descriptor_index and index fields (2 bytes each).\n currentLocalVariableTableOffset += 10;\n }\n }\n } else if (Constants.LOCAL_VARIABLE_TYPE_TABLE.equals(attributeName)) {\n localVariableTypeTableOffset = currentOffset;\n // Here we do not extract the labels corresponding to the attribute content. We assume they\n // are the same or a subset of those of the LocalVariableTable attribute.\n } else if (Constants.LINE_NUMBER_TABLE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_DEBUG) == 0) {\n // Parse the attribute to find the corresponding (debug only) labels.\n int currentLineNumberTableOffset = currentOffset;\n int lineNumberTableLength = readUnsignedShort(currentLineNumberTableOffset);\n currentLineNumberTableOffset += 2;\n while (lineNumberTableLength-- > 0) {\n int startPc = readUnsignedShort(currentLineNumberTableOffset);\n int lineNumber = readUnsignedShort(currentLineNumberTableOffset + 2);\n currentLineNumberTableOffset += 4;\n createDebugLabel(startPc, labels);\n labels[startPc].addLineNumber(lineNumber);\n }\n }\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n visibleTypeAnnotationOffsets = readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ true);\n // Here we do not extract the labels corresponding to the attribute content. This would\n // require a full parsing of the attribute, which would need to be repeated when parsing\n // the bytecode instructions (see below). Instead, the content of the attribute is read one\n // type annotation at a time (i.e. after a type annotation has been visited, the next type\n // annotation is read), and the labels it contains are also extracted one annotation at a\n // time. This assumes that type annotations are ordered by increasing bytecode offset.\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n invisibleTypeAnnotationOffsets = readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ false);\n // Same comment as above for the RuntimeVisibleTypeAnnotations attribute.\n } else if (Constants.STACK_MAP_TABLE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_FRAMES) == 0) {\n stackMapFrameOffset = currentOffset + 2;\n stackMapTableEndOffset = currentOffset + attributeLength;\n }\n // Here we do not extract the labels corresponding to the attribute content. This would\n // require a full parsing of the attribute, which would need to be repeated when parsing\n // the bytecode instructions (see below). Instead, the content of the attribute is read one\n // frame at a time (i.e. after a frame has been visited, the next frame is read), and the\n // labels it contains are also extracted one frame at a time. Thanks to the ordering of\n // frames, having only a \"one frame lookahead\" is not a problem, i.e. it is not possible to\n // see an offset smaller than the offset of the current instruction and for which no Label\n // exist. Except for UNINITIALIZED type offsets. We solve this by parsing the stack map\n // table without a full decoding (see below).\n } else if (\"StackMap\".equals(attributeName)) {\n if ((context.parsingOptions & SKIP_FRAMES) == 0) {\n stackMapFrameOffset = currentOffset + 2;\n stackMapTableEndOffset = currentOffset + attributeLength;\n compressedFrames = false;\n }\n // IMPORTANT! Here we assume that the frames are ordered, as in the StackMapTable attribute,\n // although this is not guaranteed by the attribute format. This allows an incremental\n // extraction of the labels corresponding to this attribute (see the comment above for the\n // StackMapTable attribute).\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, codeOffset, labels);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n // Initialize the context fields related to stack map frames, and generate the first\n // (implicit) stack map frame, if needed.\n final boolean expandFrames = (context.parsingOptions & EXPAND_FRAMES) != 0;\n if (stackMapFrameOffset != 0) {\n // The bytecode offset of the first explicit frame is not offset_delta + 1 but only\n // offset_delta. Setting the implicit frame offset to -1 allows us to use of the\n // \"offset_delta + 1\" rule in all cases.\n context.currentFrameOffset = -1;\n context.currentFrameType = 0;\n context.currentFrameLocalCount = 0;\n context.currentFrameLocalCountDelta = 0;\n context.currentFrameLocalTypes = new Object[maxLocals];\n context.currentFrameStackCount = 0;\n context.currentFrameStackTypes = new Object[maxStack];\n if (expandFrames) {\n computeImplicitFrame(context);\n }\n // Find the labels for UNINITIALIZED frame types. Instead of decoding each element of the\n // stack map table, we look for 3 consecutive bytes that \"look like\" an UNINITIALIZED type\n // (tag ITEM_Uninitialized, offset within bytecode bounds, NEW instruction at this offset).\n // We may find false positives (i.e. not real UNINITIALIZED types), but this should be rare,\n // and the only consequence will be the creation of an unneeded label. This is better than\n // creating a label for each NEW instruction, and faster than fully decoding the whole stack\n // map table.\n for (int offset = stackMapFrameOffset; offset < stackMapTableEndOffset - 2; ++offset) {\n if (classBuffer[offset] == Frame.ITEM_UNINITIALIZED) {\n int potentialBytecodeOffset = readUnsignedShort(offset + 1);\n if (potentialBytecodeOffset >= 0 && potentialBytecodeOffset < codeLength && (classBuffer[bytecodeStartOffset + potentialBytecodeOffset] & 0xFF) == Opcodes.NEW) {\n createLabel(potentialBytecodeOffset, labels);\n }\n }\n }\n }\n if (expandFrames && (context.parsingOptions & EXPAND_ASM_INSNS) != 0) {\n // Expanding the ASM specific instructions can introduce F_INSERT frames, even if the method\n // does not currently have any frame. These inserted frames must be computed by simulating the\n // effect of the bytecode instructions, one by one, starting from the implicit first frame.\n // For this, MethodWriter needs to know maxLocals before the first instruction is visited. To\n // ensure this, we visit the implicit first frame here (passing only maxLocals - the rest is\n // computed in MethodWriter).\n methodVisitor.visitFrame(Opcodes.F_NEW, maxLocals, null, 0, null);\n }\n // Visit the bytecode instructions. First, introduce state variables for the incremental parsing\n // of the type annotations.\n // Index of the next runtime visible type annotation to read (in the\n // visibleTypeAnnotationOffsets array).\n int currentVisibleTypeAnnotationIndex = 0;\n // The bytecode offset of the next runtime visible type annotation to read, or -1.\n int currentVisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(visibleTypeAnnotationOffsets, 0);\n // Index of the next runtime invisible type annotation to read (in the\n // invisibleTypeAnnotationOffsets array).\n int currentInvisibleTypeAnnotationIndex = 0;\n // The bytecode offset of the next runtime invisible type annotation to read, or -1.\n int currentInvisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(invisibleTypeAnnotationOffsets, 0);\n // Whether a F_INSERT stack map frame must be inserted before the current instruction.\n boolean insertFrame = false;\n // The delta to subtract from a goto_w or jsr_w opcode to get the corresponding goto or jsr\n // opcode, or 0 if goto_w and jsr_w must be left unchanged (i.e. when expanding ASM specific\n // instructions).\n final int wideJumpOpcodeDelta = (context.parsingOptions & EXPAND_ASM_INSNS) == 0 ? Constants.WIDE_JUMP_OPCODE_DELTA : 0;\n currentOffset = bytecodeStartOffset;\n while (currentOffset < bytecodeEndOffset) {\n final int currentBytecodeOffset = currentOffset - bytecodeStartOffset;\n // Visit the label and the line number(s) for this bytecode offset, if any.\n Label currentLabel = labels[currentBytecodeOffset];\n if (currentLabel != null) {\n currentLabel.accept(methodVisitor, (context.parsingOptions & SKIP_DEBUG) == 0);\n }\n // Visit the stack map frame for this bytecode offset, if any.\n while (stackMapFrameOffset != 0 && (context.currentFrameOffset == currentBytecodeOffset || context.currentFrameOffset == -1)) {\n // If there is a stack map frame for this offset, make methodVisitor visit it, and read the\n // next stack map frame if there is one.\n if (context.currentFrameOffset != -1) {\n if (!compressedFrames || expandFrames) {\n methodVisitor.visitFrame(Opcodes.F_NEW, context.currentFrameLocalCount, context.currentFrameLocalTypes, context.currentFrameStackCount, context.currentFrameStackTypes);\n } else {\n methodVisitor.visitFrame(context.currentFrameType, context.currentFrameLocalCountDelta, context.currentFrameLocalTypes, context.currentFrameStackCount, context.currentFrameStackTypes);\n }\n // Since there is already a stack map frame for this bytecode offset, there is no need to\n // insert a new one.\n insertFrame = false;\n }\n if (stackMapFrameOffset < stackMapTableEndOffset) {\n stackMapFrameOffset = readStackMapFrame(stackMapFrameOffset, compressedFrames, expandFrames, context);\n } else {\n stackMapFrameOffset = 0;\n }\n }\n // Insert a stack map frame for this bytecode offset, if requested by setting insertFrame to\n // true during the previous iteration. The actual frame content is computed in MethodWriter.\n if (insertFrame) {\n if ((context.parsingOptions & EXPAND_FRAMES) != 0) {\n methodVisitor.visitFrame(Constants.F_INSERT, 0, null, 0, null);\n }\n insertFrame = false;\n }\n // Visit the instruction at this bytecode offset.\n int opcode = classBuffer[currentOffset] & 0xFF;\n switch (opcode) {\n case Constants.NOP:\n case Constants.ACONST_NULL:\n case Constants.ICONST_M1:\n case Constants.ICONST_0:\n case Constants.ICONST_1:\n case Constants.ICONST_2:\n case Constants.ICONST_3:\n case Constants.ICONST_4:\n case Constants.ICONST_5:\n case Constants.LCONST_0:\n case Constants.LCONST_1:\n case Constants.FCONST_0:\n case Constants.FCONST_1:\n case Constants.FCONST_2:\n case Constants.DCONST_0:\n case Constants.DCONST_1:\n case Constants.IALOAD:\n case Constants.LALOAD:\n case Constants.FALOAD:\n case Constants.DALOAD:\n case Constants.AALOAD:\n case Constants.BALOAD:\n case Constants.CALOAD:\n case Constants.SALOAD:\n case Constants.IASTORE:\n case Constants.LASTORE:\n case Constants.FASTORE:\n case Constants.DASTORE:\n case Constants.AASTORE:\n case Constants.BASTORE:\n case Constants.CASTORE:\n case Constants.SASTORE:\n case Constants.POP:\n case Constants.POP2:\n case Constants.DUP:\n case Constants.DUP_X1:\n case Constants.DUP_X2:\n case Constants.DUP2:\n case Constants.DUP2_X1:\n case Constants.DUP2_X2:\n case Constants.SWAP:\n case Constants.IADD:\n case Constants.LADD:\n case Constants.FADD:\n case Constants.DADD:\n case Constants.ISUB:\n case Constants.LSUB:\n case Constants.FSUB:\n case Constants.DSUB:\n case Constants.IMUL:\n case Constants.LMUL:\n case Constants.FMUL:\n case Constants.DMUL:\n case Constants.IDIV:\n case Constants.LDIV:\n case Constants.FDIV:\n case Constants.DDIV:\n case Constants.IREM:\n case Constants.LREM:\n case Constants.FREM:\n case Constants.DREM:\n case Constants.INEG:\n case Constants.LNEG:\n case Constants.FNEG:\n case Constants.DNEG:\n case Constants.ISHL:\n case Constants.LSHL:\n case Constants.ISHR:\n case Constants.LSHR:\n case Constants.IUSHR:\n case Constants.LUSHR:\n case Constants.IAND:\n case Constants.LAND:\n case Constants.IOR:\n case Constants.LOR:\n case Constants.IXOR:\n case Constants.LXOR:\n case Constants.I2L:\n case Constants.I2F:\n case Constants.I2D:\n case Constants.L2I:\n case Constants.L2F:\n case Constants.L2D:\n case Constants.F2I:\n case Constants.F2L:\n case Constants.F2D:\n case Constants.D2I:\n case Constants.D2L:\n case Constants.D2F:\n case Constants.I2B:\n case Constants.I2C:\n case Constants.I2S:\n case Constants.LCMP:\n case Constants.FCMPL:\n case Constants.FCMPG:\n case Constants.DCMPL:\n case Constants.DCMPG:\n case Constants.IRETURN:\n case Constants.LRETURN:\n case Constants.FRETURN:\n case Constants.DRETURN:\n case Constants.ARETURN:\n case Constants.RETURN:\n case Constants.ARRAYLENGTH:\n case Constants.ATHROW:\n case Constants.MONITORENTER:\n case Constants.MONITOREXIT:\n methodVisitor.visitInsn(opcode);\n currentOffset += 1;\n break;\n case Constants.ILOAD_0:\n case Constants.ILOAD_1:\n case Constants.ILOAD_2:\n case Constants.ILOAD_3:\n case Constants.LLOAD_0:\n case Constants.LLOAD_1:\n case Constants.LLOAD_2:\n case Constants.LLOAD_3:\n case Constants.FLOAD_0:\n case Constants.FLOAD_1:\n case Constants.FLOAD_2:\n case Constants.FLOAD_3:\n case Constants.DLOAD_0:\n case Constants.DLOAD_1:\n case Constants.DLOAD_2:\n case Constants.DLOAD_3:\n case Constants.ALOAD_0:\n case Constants.ALOAD_1:\n case Constants.ALOAD_2:\n case Constants.ALOAD_3:\n opcode -= Constants.ILOAD_0;\n methodVisitor.visitVarInsn(Opcodes.ILOAD + (opcode >> 2), opcode & 0x3);\n currentOffset += 1;\n break;\n case Constants.ISTORE_0:\n case Constants.ISTORE_1:\n case Constants.ISTORE_2:\n case Constants.ISTORE_3:\n case Constants.LSTORE_0:\n case Constants.LSTORE_1:\n case Constants.LSTORE_2:\n case Constants.LSTORE_3:\n case Constants.FSTORE_0:\n case Constants.FSTORE_1:\n case Constants.FSTORE_2:\n case Constants.FSTORE_3:\n case Constants.DSTORE_0:\n case Constants.DSTORE_1:\n case Constants.DSTORE_2:\n case Constants.DSTORE_3:\n case Constants.ASTORE_0:\n case Constants.ASTORE_1:\n case Constants.ASTORE_2:\n case Constants.ASTORE_3:\n opcode -= Constants.ISTORE_0;\n methodVisitor.visitVarInsn(Opcodes.ISTORE + (opcode >> 2), opcode & 0x3);\n currentOffset += 1;\n break;\n case Constants.IFEQ:\n case Constants.IFNE:\n case Constants.IFLT:\n case Constants.IFGE:\n case Constants.IFGT:\n case Constants.IFLE:\n case Constants.IF_ICMPEQ:\n case Constants.IF_ICMPNE:\n case Constants.IF_ICMPLT:\n case Constants.IF_ICMPGE:\n case Constants.IF_ICMPGT:\n case Constants.IF_ICMPLE:\n case Constants.IF_ACMPEQ:\n case Constants.IF_ACMPNE:\n case Constants.GOTO:\n case Constants.JSR:\n case Constants.IFNULL:\n case Constants.IFNONNULL:\n methodVisitor.visitJumpInsn(opcode, labels[currentBytecodeOffset + readShort(currentOffset + 1)]);\n currentOffset += 3;\n break;\n case Constants.GOTO_W:\n case Constants.JSR_W:\n methodVisitor.visitJumpInsn(opcode - wideJumpOpcodeDelta, labels[currentBytecodeOffset + readInt(currentOffset + 1)]);\n currentOffset += 5;\n break;\n case Constants.ASM_IFEQ:\n case Constants.ASM_IFNE:\n case Constants.ASM_IFLT:\n case Constants.ASM_IFGE:\n case Constants.ASM_IFGT:\n case Constants.ASM_IFLE:\n case Constants.ASM_IF_ICMPEQ:\n case Constants.ASM_IF_ICMPNE:\n case Constants.ASM_IF_ICMPLT:\n case Constants.ASM_IF_ICMPGE:\n case Constants.ASM_IF_ICMPGT:\n case Constants.ASM_IF_ICMPLE:\n case Constants.ASM_IF_ACMPEQ:\n case Constants.ASM_IF_ACMPNE:\n case Constants.ASM_GOTO:\n case Constants.ASM_JSR:\n case Constants.ASM_IFNULL:\n case Constants.ASM_IFNONNULL: {\n // A forward jump with an offset > 32767. In this case we automatically replace ASM_GOTO\n // with GOTO_W, ASM_JSR with JSR_W and ASM_IFxxx with IFNOTxxx GOTO_W L:...,\n // where IFNOTxxx is the \"opposite\" opcode of ASMS_IFxxx (e.g. IFNE for ASM_IFEQ) and\n // where designates the instruction just after the GOTO_W.\n // First, change the ASM specific opcodes ASM_IFEQ ... ASM_JSR, ASM_IFNULL and\n // ASM_IFNONNULL to IFEQ ... JSR, IFNULL and IFNONNULL.\n opcode = opcode < Constants.ASM_IFNULL ? opcode - Constants.ASM_OPCODE_DELTA : opcode - Constants.ASM_IFNULL_OPCODE_DELTA;\n Label target = labels[currentBytecodeOffset + readUnsignedShort(currentOffset + 1)];\n if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) {\n // Replace GOTO with GOTO_W and JSR with JSR_W.\n methodVisitor.visitJumpInsn(opcode + Constants.WIDE_JUMP_OPCODE_DELTA, target);\n } else {\n // Compute the \"opposite\" of opcode. This can be done by flipping the least\n // significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ\n // (with a pre and post offset by 1).\n opcode = opcode < Opcodes.GOTO ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1;\n Label endif = createLabel(currentBytecodeOffset + 3, labels);\n methodVisitor.visitJumpInsn(opcode, endif);\n methodVisitor.visitJumpInsn(Constants.GOTO_W, target);\n // endif designates the instruction just after GOTO_W, and is visited as part of the\n // next instruction. Since it is a jump target, we need to insert a frame here.\n insertFrame = true;\n }\n currentOffset += 3;\n break;\n }\n case Constants.ASM_GOTO_W:\n // Replace ASM_GOTO_W with GOTO_W.\n methodVisitor.visitJumpInsn(Constants.GOTO_W, labels[currentBytecodeOffset + readInt(currentOffset + 1)]);\n // The instruction just after is a jump target (because ASM_GOTO_W is used in patterns\n // IFNOTxxx ASM_GOTO_W L:..., see MethodWriter), so we need to insert a frame\n // here.\n insertFrame = true;\n currentOffset += 5;\n break;\n case Constants.WIDE:\n opcode = classBuffer[currentOffset + 1] & 0xFF;\n if (opcode == Opcodes.IINC) {\n methodVisitor.visitIincInsn(readUnsignedShort(currentOffset + 2), readShort(currentOffset + 4));\n currentOffset += 6;\n } else {\n methodVisitor.visitVarInsn(opcode, readUnsignedShort(currentOffset + 2));\n currentOffset += 4;\n }\n break;\n case Constants.TABLESWITCH: {\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (currentBytecodeOffset & 3);\n // Read the instruction.\n Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)];\n int low = readInt(currentOffset + 4);\n int high = readInt(currentOffset + 8);\n currentOffset += 12;\n Label[] table = new Label[high - low + 1];\n for (int i = 0; i < table.length; ++i) {\n table[i] = labels[currentBytecodeOffset + readInt(currentOffset)];\n currentOffset += 4;\n }\n methodVisitor.visitTableSwitchInsn(low, high, defaultLabel, table);\n break;\n }\n case Constants.LOOKUPSWITCH: {\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (currentBytecodeOffset & 3);\n // Read the instruction.\n Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)];\n int numPairs = readInt(currentOffset + 4);\n currentOffset += 8;\n int[] keys = new int[numPairs];\n Label[] values = new Label[numPairs];\n for (int i = 0; i < numPairs; ++i) {\n keys[i] = readInt(currentOffset);\n values[i] = labels[currentBytecodeOffset + readInt(currentOffset + 4)];\n currentOffset += 8;\n }\n methodVisitor.visitLookupSwitchInsn(defaultLabel, keys, values);\n break;\n }\n case Constants.ILOAD:\n case Constants.LLOAD:\n case Constants.FLOAD:\n case Constants.DLOAD:\n case Constants.ALOAD:\n case Constants.ISTORE:\n case Constants.LSTORE:\n case Constants.FSTORE:\n case Constants.DSTORE:\n case Constants.ASTORE:\n case Constants.RET:\n methodVisitor.visitVarInsn(opcode, classBuffer[currentOffset + 1] & 0xFF);\n currentOffset += 2;\n break;\n case Constants.BIPUSH:\n case Constants.NEWARRAY:\n methodVisitor.visitIntInsn(opcode, classBuffer[currentOffset + 1]);\n currentOffset += 2;\n break;\n case Constants.SIPUSH:\n methodVisitor.visitIntInsn(opcode, readShort(currentOffset + 1));\n currentOffset += 3;\n break;\n case Constants.LDC:\n methodVisitor.visitLdcInsn(readConst(classBuffer[currentOffset + 1] & 0xFF, charBuffer));\n currentOffset += 2;\n break;\n case Constants.LDC_W:\n case Constants.LDC2_W:\n methodVisitor.visitLdcInsn(readConst(readUnsignedShort(currentOffset + 1), charBuffer));\n currentOffset += 3;\n break;\n case Constants.GETSTATIC:\n case Constants.PUTSTATIC:\n case Constants.GETFIELD:\n case Constants.PUTFIELD:\n case Constants.INVOKEVIRTUAL:\n case Constants.INVOKESPECIAL:\n case Constants.INVOKESTATIC:\n case Constants.INVOKEINTERFACE: {\n int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)];\n String owner = readClass(cpInfoOffset, charBuffer);\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n if (opcode < Opcodes.INVOKEVIRTUAL) {\n methodVisitor.visitFieldInsn(opcode, owner, name, descriptor);\n } else {\n boolean isInterface = classBuffer[cpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG;\n methodVisitor.visitMethodInsn(opcode, owner, name, descriptor, isInterface);\n }\n if (opcode == Opcodes.INVOKEINTERFACE) {\n currentOffset += 5;\n } else {\n currentOffset += 3;\n }\n break;\n }\n case Constants.INVOKEDYNAMIC: {\n int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)];\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)];\n Handle handle = (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n Object[] bootstrapMethodArguments = new Object[readUnsignedShort(bootstrapMethodOffset + 2)];\n bootstrapMethodOffset += 4;\n for (int i = 0; i < bootstrapMethodArguments.length; i++) {\n bootstrapMethodArguments[i] = readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n bootstrapMethodOffset += 2;\n }\n methodVisitor.visitInvokeDynamicInsn(name, descriptor, handle, bootstrapMethodArguments);\n currentOffset += 5;\n break;\n }\n case Constants.NEW:\n case Constants.ANEWARRAY:\n case Constants.CHECKCAST:\n case Constants.INSTANCEOF:\n methodVisitor.visitTypeInsn(opcode, readClass(currentOffset + 1, charBuffer));\n currentOffset += 3;\n break;\n case Constants.IINC:\n methodVisitor.visitIincInsn(classBuffer[currentOffset + 1] & 0xFF, classBuffer[currentOffset + 2]);\n currentOffset += 3;\n break;\n case Constants.MULTIANEWARRAY:\n methodVisitor.visitMultiANewArrayInsn(readClass(currentOffset + 1, charBuffer), classBuffer[currentOffset + 3] & 0xFF);\n currentOffset += 4;\n break;\n default:\n throw new AssertionError();\n }\n // Visit the runtime visible instruction annotations, if any.\n while (visibleTypeAnnotationOffsets != null && currentVisibleTypeAnnotationIndex < visibleTypeAnnotationOffsets.length && currentVisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) {\n if (currentVisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) {\n // Parse the target_type, target_info and target_path fields.\n int currentAnnotationOffset = readTypeAnnotationTarget(context, visibleTypeAnnotationOffsets[currentVisibleTypeAnnotationIndex]);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitInsnAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n currentVisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(visibleTypeAnnotationOffsets, ++currentVisibleTypeAnnotationIndex);\n }\n // Visit the runtime invisible instruction annotations, if any.\n while (invisibleTypeAnnotationOffsets != null && currentInvisibleTypeAnnotationIndex < invisibleTypeAnnotationOffsets.length && currentInvisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) {\n if (currentInvisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) {\n // Parse the target_type, target_info and target_path fields.\n int currentAnnotationOffset = readTypeAnnotationTarget(context, invisibleTypeAnnotationOffsets[currentInvisibleTypeAnnotationIndex]);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitInsnAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n currentInvisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(invisibleTypeAnnotationOffsets, ++currentInvisibleTypeAnnotationIndex);\n }\n }\n if (labels[codeLength] != null) {\n methodVisitor.visitLabel(labels[codeLength]);\n }\n // Visit LocalVariableTable and LocalVariableTypeTable attributes.\n if (localVariableTableOffset != 0 && (context.parsingOptions & SKIP_DEBUG) == 0) {\n // The (start_pc, index, signature_index) fields of each entry of the LocalVariableTypeTable.\n int[] typeTable = null;\n if (localVariableTypeTableOffset != 0) {\n typeTable = new int[readUnsignedShort(localVariableTypeTableOffset) * 3];\n currentOffset = localVariableTypeTableOffset + 2;\n int typeTableIndex = typeTable.length;\n while (typeTableIndex > 0) {\n // Store the offset of 'signature_index', and the value of 'index' and 'start_pc'.\n typeTable[--typeTableIndex] = currentOffset + 6;\n typeTable[--typeTableIndex] = readUnsignedShort(currentOffset + 8);\n typeTable[--typeTableIndex] = readUnsignedShort(currentOffset);\n currentOffset += 10;\n }\n }\n int localVariableTableLength = readUnsignedShort(localVariableTableOffset);\n currentOffset = localVariableTableOffset + 2;\n while (localVariableTableLength-- > 0) {\n int startPc = readUnsignedShort(currentOffset);\n int length = readUnsignedShort(currentOffset + 2);\n String name = readUTF8(currentOffset + 4, charBuffer);\n String descriptor = readUTF8(currentOffset + 6, charBuffer);\n int index = readUnsignedShort(currentOffset + 8);\n currentOffset += 10;\n String signature = null;\n if (typeTable != null) {\n for (int i = 0; i < typeTable.length; i += 3) {\n if (typeTable[i] == startPc && typeTable[i + 1] == index) {\n signature = readUTF8(typeTable[i + 2], charBuffer);\n break;\n }\n }\n }\n methodVisitor.visitLocalVariable(name, descriptor, signature, labels[startPc], labels[startPc + length], index);\n }\n }\n // Visit the local variable type annotations of the RuntimeVisibleTypeAnnotations attribute.\n if (visibleTypeAnnotationOffsets != null) {\n for (int typeAnnotationOffset : visibleTypeAnnotationOffsets) {\n int targetType = readByte(typeAnnotationOffset);\n if (targetType == TypeReference.LOCAL_VARIABLE || targetType == TypeReference.RESOURCE_VARIABLE) {\n // Parse the target_type, target_info and target_path fields.\n currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitLocalVariableAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, context.currentLocalVariableAnnotationRangeStarts, context.currentLocalVariableAnnotationRangeEnds, context.currentLocalVariableAnnotationRangeIndices, annotationDescriptor,\n /* visible = */ true), currentOffset,\n /* named = */ true, charBuffer);\n }\n }\n }\n // Visit the local variable type annotations of the RuntimeInvisibleTypeAnnotations attribute.\n if (invisibleTypeAnnotationOffsets != null) {\n for (int typeAnnotationOffset : invisibleTypeAnnotationOffsets) {\n int targetType = readByte(typeAnnotationOffset);\n if (targetType == TypeReference.LOCAL_VARIABLE || targetType == TypeReference.RESOURCE_VARIABLE) {\n // Parse the target_type, target_info and target_path fields.\n currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitLocalVariableAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, context.currentLocalVariableAnnotationRangeStarts, context.currentLocalVariableAnnotationRangeEnds, context.currentLocalVariableAnnotationRangeIndices, annotationDescriptor,\n /* visible = */ false), currentOffset,\n /* named = */ true, charBuffer);\n }\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in MethodWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n methodVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the max stack and max locals values.\n methodVisitor.visitMaxs(maxStack, maxLocals);\n }\n\n /**\n * Returns the label corresponding to the given bytecode offset. The default implementation of\n * this method creates a label for the given offset if it has not been already created.\n *\n * @param bytecodeOffset a bytecode offset in a method.\n * @param labels the already created labels, indexed by their offset. If a label already exists\n * for bytecodeOffset this method must not create a new one. Otherwise it must store the new\n * label in this array.\n * @return a non null Label, which must be equal to labels[bytecodeOffset].\n */\n protected Label readLabel(final int bytecodeOffset, final Label[] labels) {\n if (labels[bytecodeOffset] == null) {\n labels[bytecodeOffset] = new Label();\n }\n return labels[bytecodeOffset];\n }\n\n /**\n * Creates a label without the {@link Label#FLAG_DEBUG_ONLY} flag set, for the given bytecode\n * offset. The label is created with a call to {@link #readLabel} and its {@link\n * Label#FLAG_DEBUG_ONLY} flag is cleared.\n *\n * @param bytecodeOffset a bytecode offset in a method.\n * @param labels the already created labels, indexed by their offset.\n * @return a Label without the {@link Label#FLAG_DEBUG_ONLY} flag set.\n */\n private Label createLabel(final int bytecodeOffset, final Label[] labels) {\n Label label = readLabel(bytecodeOffset, labels);\n label.flags &= ~Label.FLAG_DEBUG_ONLY;\n return label;\n }\n\n /**\n * Creates a label with the {@link Label#FLAG_DEBUG_ONLY} flag set, if there is no already\n * existing label for the given bytecode offset (otherwise does nothing). The label is created\n * with a call to {@link #readLabel}.\n *\n * @param bytecodeOffset a bytecode offset in a method.\n * @param labels the already created labels, indexed by their offset.\n */\n private void createDebugLabel(final int bytecodeOffset, final Label[] labels) {\n if (labels[bytecodeOffset] == null) {\n readLabel(bytecodeOffset, labels).flags |= Label.FLAG_DEBUG_ONLY;\n }\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse annotations, type annotations and parameter annotations\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Parses a Runtime[In]VisibleTypeAnnotations attribute to find the offset of each type_annotation\n * entry it contains, to find the corresponding labels, and to visit the try catch block\n * annotations.\n *\n * @param methodVisitor the method visitor to be used to visit the try catch block annotations.\n * @param context information about the class being parsed.\n * @param runtimeTypeAnnotationsOffset the start offset of a Runtime[In]VisibleTypeAnnotations\n * attribute, excluding the attribute_info's attribute_name_index and attribute_length fields.\n * @param visible true if the attribute to parse is a RuntimeVisibleTypeAnnotations attribute,\n * false it is a RuntimeInvisibleTypeAnnotations attribute.\n * @return the start offset of each entry of the Runtime[In]VisibleTypeAnnotations_attribute's\n * 'annotations' array field.\n */\n private int[] readTypeAnnotations(final MethodVisitor methodVisitor, final Context context, final int runtimeTypeAnnotationsOffset, final boolean visible) {\n char[] charBuffer = context.charBuffer;\n int currentOffset = runtimeTypeAnnotationsOffset;\n // Read the num_annotations field and create an array to store the type_annotation offsets.\n int[] typeAnnotationsOffsets = new int[readUnsignedShort(currentOffset)];\n currentOffset += 2;\n // Parse the 'annotations' array field.\n for (int i = 0; i < typeAnnotationsOffsets.length; ++i) {\n typeAnnotationsOffsets[i] = currentOffset;\n // Parse the type_annotation's target_type and the target_info fields. The size of the\n // target_info field depends on the value of target_type.\n int targetType = readInt(currentOffset);\n switch (targetType >>> 24) {\n case TypeReference.LOCAL_VARIABLE:\n case TypeReference.RESOURCE_VARIABLE:\n // A localvar_target has a variable size, which depends on the value of their table_length\n // field. It also references bytecode offsets, for which we need labels.\n int tableLength = readUnsignedShort(currentOffset + 1);\n currentOffset += 3;\n while (tableLength-- > 0) {\n int startPc = readUnsignedShort(currentOffset);\n int length = readUnsignedShort(currentOffset + 2);\n // Skip the index field (2 bytes).\n currentOffset += 6;\n createLabel(startPc, context.currentMethodLabels);\n createLabel(startPc + length, context.currentMethodLabels);\n }\n break;\n case TypeReference.CAST:\n case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:\n case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT:\n currentOffset += 4;\n break;\n case TypeReference.CLASS_EXTENDS:\n case TypeReference.CLASS_TYPE_PARAMETER_BOUND:\n case TypeReference.METHOD_TYPE_PARAMETER_BOUND:\n case TypeReference.THROWS:\n case TypeReference.EXCEPTION_PARAMETER:\n case TypeReference.INSTANCEOF:\n case TypeReference.NEW:\n case TypeReference.CONSTRUCTOR_REFERENCE:\n case TypeReference.METHOD_REFERENCE:\n currentOffset += 3;\n break;\n case TypeReference.CLASS_TYPE_PARAMETER:\n case TypeReference.METHOD_TYPE_PARAMETER:\n case TypeReference.METHOD_FORMAL_PARAMETER:\n case TypeReference.FIELD:\n case TypeReference.METHOD_RETURN:\n case TypeReference.METHOD_RECEIVER:\n default:\n // TypeReference type which can't be used in Code attribute, or which is unknown.\n throw new IllegalArgumentException();\n }\n // Parse the rest of the type_annotation structure, starting with the target_path structure\n // (whose size depends on its path_length field).\n int pathLength = readByte(currentOffset);\n if ((targetType >>> 24) == TypeReference.EXCEPTION_PARAMETER) {\n // Parse the target_path structure and create a corresponding TypePath.\n TypePath path = pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset);\n currentOffset += 1 + 2 * pathLength;\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentOffset = readElementValues(methodVisitor.visitTryCatchAnnotation(targetType & 0xFFFFFF00, path, annotationDescriptor, visible), currentOffset,\n /* named = */ true, charBuffer);\n } else {\n // We don't want to visit the other target_type annotations, so we just skip them (which\n // requires some parsing because the element_value_pairs array has a variable size). First,\n // skip the target_path structure:\n currentOffset += 3 + 2 * pathLength;\n // Then skip the num_element_value_pairs and element_value_pairs fields (by reading them\n // with a null AnnotationVisitor).\n currentOffset = readElementValues(\n /* annotationVisitor = */ null, currentOffset, /* named = */ true, charBuffer);\n }\n }\n return typeAnnotationsOffsets;\n }\n\n /**\n * Returns the bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or\n * -1 if there is no such type_annotation of if it does not have a bytecode offset.\n *\n * @param typeAnnotationOffsets the offset of each 'type_annotation' entry in a\n * Runtime[In]VisibleTypeAnnotations attribute, or {@literal null}.\n * @param typeAnnotationIndex the index a 'type_annotation' entry in typeAnnotationOffsets.\n * @return bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or -1\n * if there is no such type_annotation of if it does not have a bytecode offset.\n */\n private int getTypeAnnotationBytecodeOffset(final int[] typeAnnotationOffsets, final int typeAnnotationIndex) {\n if (typeAnnotationOffsets == null || typeAnnotationIndex >= typeAnnotationOffsets.length || readByte(typeAnnotationOffsets[typeAnnotationIndex]) < TypeReference.INSTANCEOF) {\n return -1;\n }\n return readUnsignedShort(typeAnnotationOffsets[typeAnnotationIndex] + 1);\n }\n\n /**\n * Parses the header of a JVMS type_annotation structure to extract its target_type, target_info\n * and target_path (the result is stored in the given context), and returns the start offset of\n * the rest of the type_annotation structure.\n *\n * @param context information about the class being parsed. This is where the extracted\n * target_type and target_path must be stored.\n * @param typeAnnotationOffset the start offset of a type_annotation structure.\n * @return the start offset of the rest of the type_annotation structure.\n */\n private int readTypeAnnotationTarget(final Context context, final int typeAnnotationOffset) {\n int currentOffset = typeAnnotationOffset;\n // Parse and store the target_type structure.\n int targetType = readInt(typeAnnotationOffset);\n switch (targetType >>> 24) {\n case TypeReference.CLASS_TYPE_PARAMETER:\n case TypeReference.METHOD_TYPE_PARAMETER:\n case TypeReference.METHOD_FORMAL_PARAMETER:\n targetType &= 0xFFFF0000;\n currentOffset += 2;\n break;\n case TypeReference.FIELD:\n case TypeReference.METHOD_RETURN:\n case TypeReference.METHOD_RECEIVER:\n targetType &= 0xFF000000;\n currentOffset += 1;\n break;\n case TypeReference.LOCAL_VARIABLE:\n case TypeReference.RESOURCE_VARIABLE:\n targetType &= 0xFF000000;\n int tableLength = readUnsignedShort(currentOffset + 1);\n currentOffset += 3;\n context.currentLocalVariableAnnotationRangeStarts = new Label[tableLength];\n context.currentLocalVariableAnnotationRangeEnds = new Label[tableLength];\n context.currentLocalVariableAnnotationRangeIndices = new int[tableLength];\n for (int i = 0; i < tableLength; ++i) {\n int startPc = readUnsignedShort(currentOffset);\n int length = readUnsignedShort(currentOffset + 2);\n int index = readUnsignedShort(currentOffset + 4);\n currentOffset += 6;\n context.currentLocalVariableAnnotationRangeStarts[i] = createLabel(startPc, context.currentMethodLabels);\n context.currentLocalVariableAnnotationRangeEnds[i] = createLabel(startPc + length, context.currentMethodLabels);\n context.currentLocalVariableAnnotationRangeIndices[i] = index;\n }\n break;\n case TypeReference.CAST:\n case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:\n case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT:\n targetType &= 0xFF0000FF;\n currentOffset += 4;\n break;\n case TypeReference.CLASS_EXTENDS:\n case TypeReference.CLASS_TYPE_PARAMETER_BOUND:\n case TypeReference.METHOD_TYPE_PARAMETER_BOUND:\n case TypeReference.THROWS:\n case TypeReference.EXCEPTION_PARAMETER:\n targetType &= 0xFFFFFF00;\n currentOffset += 3;\n break;\n case TypeReference.INSTANCEOF:\n case TypeReference.NEW:\n case TypeReference.CONSTRUCTOR_REFERENCE:\n case TypeReference.METHOD_REFERENCE:\n targetType &= 0xFF000000;\n currentOffset += 3;\n break;\n default:\n throw new IllegalArgumentException();\n }\n context.currentTypeAnnotationTarget = targetType;\n // Parse and store the target_path structure.\n int pathLength = readByte(currentOffset);\n context.currentTypeAnnotationTargetPath = pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset);\n // Return the start offset of the rest of the type_annotation structure.\n return currentOffset + 1 + 2 * pathLength;\n }\n\n /**\n * Reads a Runtime[In]VisibleParameterAnnotations attribute and makes the given visitor visit it.\n *\n * @param methodVisitor the visitor that must visit the parameter annotations.\n * @param context information about the class being parsed.\n * @param runtimeParameterAnnotationsOffset the start offset of a\n * Runtime[In]VisibleParameterAnnotations attribute, excluding the attribute_info's\n * attribute_name_index and attribute_length fields.\n * @param visible true if the attribute to parse is a RuntimeVisibleParameterAnnotations\n * attribute, false it is a RuntimeInvisibleParameterAnnotations attribute.\n */\n private void readParameterAnnotations(final MethodVisitor methodVisitor, final Context context, final int runtimeParameterAnnotationsOffset, final boolean visible) {\n int currentOffset = runtimeParameterAnnotationsOffset;\n int numParameters = classFileBuffer[currentOffset++] & 0xFF;\n methodVisitor.visitAnnotableParameterCount(numParameters, visible);\n char[] charBuffer = context.charBuffer;\n for (int i = 0; i < numParameters; ++i) {\n int numAnnotations = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentOffset = readElementValues(methodVisitor.visitParameterAnnotation(i, annotationDescriptor, visible), currentOffset,\n /* named = */ true, charBuffer);\n }\n }\n }\n\n /**\n * Reads the element values of a JVMS 'annotation' structure and makes the given visitor visit\n * them. This method can also be used to read the values of the JVMS 'array_value' field of an\n * annotation's 'element_value'.\n *\n * @param annotationVisitor the visitor that must visit the values.\n * @param annotationOffset the start offset of an 'annotation' structure (excluding its type_index\n * field) or of an 'array_value' structure.\n * @param named if the annotation values are named or not. This should be true to parse the values\n * of a JVMS 'annotation' structure, and false to parse the JVMS 'array_value' of an\n * annotation's element_value.\n * @param charBuffer the buffer used to read strings in the constant pool.\n * @return the end offset of the JVMS 'annotation' or 'array_value' structure.\n */\n private int readElementValues(final AnnotationVisitor annotationVisitor, final int annotationOffset, final boolean named, final char[] charBuffer) {\n int currentOffset = annotationOffset;\n // Read the num_element_value_pairs field (or num_values field for an array_value).\n int numElementValuePairs = readUnsignedShort(currentOffset);\n currentOffset += 2;\n if (named) {\n // Parse the element_value_pairs array.\n while (numElementValuePairs-- > 0) {\n String elementName = readUTF8(currentOffset, charBuffer);\n currentOffset = readElementValue(annotationVisitor, currentOffset + 2, elementName, charBuffer);\n }\n } else {\n // Parse the array_value array.\n while (numElementValuePairs-- > 0) {\n currentOffset = readElementValue(annotationVisitor, currentOffset, /* named = */ null, charBuffer);\n }\n }\n if (annotationVisitor != null) {\n annotationVisitor.visitEnd();\n }\n return currentOffset;\n }\n\n /**\n * Reads a JVMS 'element_value' structure and makes the given visitor visit it.\n *\n * @param annotationVisitor the visitor that must visit the element_value structure.\n * @param elementValueOffset the start offset in {@link #classFileBuffer} of the element_value\n * structure to be read.\n * @param elementName the name of the element_value structure to be read, or {@literal null}.\n * @param charBuffer the buffer used to read strings in the constant pool.\n * @return the end offset of the JVMS 'element_value' structure.\n */\n private int readElementValue(final AnnotationVisitor annotationVisitor, final int elementValueOffset, final String elementName, final char[] charBuffer) {\n int currentOffset = elementValueOffset;\n if (annotationVisitor == null) {\n switch (classFileBuffer[currentOffset] & 0xFF) {\n case 'e': // enum_const_value\n return currentOffset + 5;\n case '@': // annotation_value\n return readElementValues(null, currentOffset + 3, /* named = */ true, charBuffer);\n case '[': // array_value\n return readElementValues(null, currentOffset + 1, /* named = */ false, charBuffer);\n default:\n return currentOffset + 3;\n }\n }\n switch (classFileBuffer[currentOffset++] & 0xFF) {\n case 'B': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]));\n currentOffset += 2;\n break;\n case 'C': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]));\n currentOffset += 2;\n break;\n case 'D': // const_value_index, CONSTANT_Double\n case 'F': // const_value_index, CONSTANT_Float\n case 'I': // const_value_index, CONSTANT_Integer\n case 'J': // const_value_index, CONSTANT_Long\n annotationVisitor.visit(elementName, readConst(readUnsignedShort(currentOffset), charBuffer));\n currentOffset += 2;\n break;\n case 'S': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]));\n currentOffset += 2;\n break;\n case 'Z': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]) == 0 ? Boolean.FALSE : Boolean.TRUE);\n currentOffset += 2;\n break;\n case 's': // const_value_index, CONSTANT_Utf8\n annotationVisitor.visit(elementName, readUTF8(currentOffset, charBuffer));\n currentOffset += 2;\n break;\n case 'e': // enum_const_value\n annotationVisitor.visitEnum(elementName, readUTF8(currentOffset, charBuffer), readUTF8(currentOffset + 2, charBuffer));\n currentOffset += 4;\n break;\n case 'c': // class_info\n annotationVisitor.visit(elementName, Type.getType(readUTF8(currentOffset, charBuffer)));\n currentOffset += 2;\n break;\n case '@': // annotation_value\n currentOffset = readElementValues(annotationVisitor.visitAnnotation(elementName, readUTF8(currentOffset, charBuffer)), currentOffset + 2, true, charBuffer);\n break;\n case '[': // array_value\n int numValues = readUnsignedShort(currentOffset);\n currentOffset += 2;\n if (numValues == 0) {\n return readElementValues(annotationVisitor.visitArray(elementName), currentOffset - 2,\n /* named = */ false, charBuffer);\n }\n switch (classFileBuffer[currentOffset] & 0xFF) {\n case 'B':\n byte[] byteValues = new byte[numValues];\n for (int i = 0; i < numValues; i++) {\n byteValues[i] = (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, byteValues);\n break;\n case 'Z':\n boolean[] booleanValues = new boolean[numValues];\n for (int i = 0; i < numValues; i++) {\n booleanValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]) != 0;\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, booleanValues);\n break;\n case 'S':\n short[] shortValues = new short[numValues];\n for (int i = 0; i < numValues; i++) {\n shortValues[i] = (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, shortValues);\n break;\n case 'C':\n char[] charValues = new char[numValues];\n for (int i = 0; i < numValues; i++) {\n charValues[i] = (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, charValues);\n break;\n case 'I':\n int[] intValues = new int[numValues];\n for (int i = 0; i < numValues; i++) {\n intValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, intValues);\n break;\n case 'J':\n long[] longValues = new long[numValues];\n for (int i = 0; i < numValues; i++) {\n longValues[i] = readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, longValues);\n break;\n case 'F':\n float[] floatValues = new float[numValues];\n for (int i = 0; i < numValues; i++) {\n floatValues[i] = Float.intBitsToFloat(readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]));\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, floatValues);\n break;\n case 'D':\n double[] doubleValues = new double[numValues];\n for (int i = 0; i < numValues; i++) {\n doubleValues[i] = Double.longBitsToDouble(readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]));\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, doubleValues);\n break;\n default:\n currentOffset = readElementValues(annotationVisitor.visitArray(elementName), currentOffset - 2,\n /* named = */ false, charBuffer);\n break;\n }\n break;\n default:\n throw new IllegalArgumentException();\n }\n return currentOffset;\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse stack map frames\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Computes the implicit frame of the method currently being parsed (as defined in the given\n * {@link Context}) and stores it in the given context.\n *\n * @param context information about the class being parsed.\n */\n private void computeImplicitFrame(final Context context) {\n String methodDescriptor = context.currentMethodDescriptor;\n Object[] locals = context.currentFrameLocalTypes;\n int numLocal = 0;\n if ((context.currentMethodAccessFlags & Opcodes.ACC_STATIC) == 0) {\n if (\"\".equals(context.currentMethodName)) {\n locals[numLocal++] = Opcodes.UNINITIALIZED_THIS;\n } else {\n locals[numLocal++] = readClass(header + 2, context.charBuffer);\n }\n }\n // Parse the method descriptor, one argument type descriptor at each iteration. Start by\n // skipping the first method descriptor character, which is always '('.\n int currentMethodDescritorOffset = 1;\n while (true) {\n int currentArgumentDescriptorStartOffset = currentMethodDescritorOffset;\n switch (methodDescriptor.charAt(currentMethodDescritorOffset++)) {\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n locals[numLocal++] = Opcodes.INTEGER;\n break;\n case 'F':\n locals[numLocal++] = Opcodes.FLOAT;\n break;\n case 'J':\n locals[numLocal++] = Opcodes.LONG;\n break;\n case 'D':\n locals[numLocal++] = Opcodes.DOUBLE;\n break;\n case '[':\n while (methodDescriptor.charAt(currentMethodDescritorOffset) == '[') {\n ++currentMethodDescritorOffset;\n }\n if (methodDescriptor.charAt(currentMethodDescritorOffset) == 'L') {\n ++currentMethodDescritorOffset;\n while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') {\n ++currentMethodDescritorOffset;\n }\n }\n locals[numLocal++] = methodDescriptor.substring(currentArgumentDescriptorStartOffset, ++currentMethodDescritorOffset);\n break;\n case 'L':\n while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') {\n ++currentMethodDescritorOffset;\n }\n locals[numLocal++] = methodDescriptor.substring(currentArgumentDescriptorStartOffset + 1, currentMethodDescritorOffset++);\n break;\n default:\n context.currentFrameLocalCount = numLocal;\n return;\n }\n }\n }\n\n /**\n * Reads a JVMS 'stack_map_frame' structure and stores the result in the given {@link Context}\n * object. This method can also be used to read a full_frame structure, excluding its frame_type\n * field (this is used to parse the legacy StackMap attributes).\n *\n * @param stackMapFrameOffset the start offset in {@link #classFileBuffer} of the\n * stack_map_frame_value structure to be read, or the start offset of a full_frame structure\n * (excluding its frame_type field).\n * @param compressed true to read a 'stack_map_frame' structure, false to read a 'full_frame'\n * structure without its frame_type field.\n * @param expand if the stack map frame must be expanded. See {@link #EXPAND_FRAMES}.\n * @param context where the parsed stack map frame must be stored.\n * @return the end offset of the JVMS 'stack_map_frame' or 'full_frame' structure.\n */\n private int readStackMapFrame(final int stackMapFrameOffset, final boolean compressed, final boolean expand, final Context context) {\n int currentOffset = stackMapFrameOffset;\n final char[] charBuffer = context.charBuffer;\n final Label[] labels = context.currentMethodLabels;\n int frameType;\n if (compressed) {\n // Read the frame_type field.\n frameType = classFileBuffer[currentOffset++] & 0xFF;\n } else {\n frameType = Frame.FULL_FRAME;\n context.currentFrameOffset = -1;\n }\n int offsetDelta;\n context.currentFrameLocalCountDelta = 0;\n if (frameType < Frame.SAME_LOCALS_1_STACK_ITEM_FRAME) {\n offsetDelta = frameType;\n context.currentFrameType = Opcodes.F_SAME;\n context.currentFrameStackCount = 0;\n } else if (frameType < Frame.RESERVED) {\n offsetDelta = frameType - Frame.SAME_LOCALS_1_STACK_ITEM_FRAME;\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels);\n context.currentFrameType = Opcodes.F_SAME1;\n context.currentFrameStackCount = 1;\n } else if (frameType >= Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {\n offsetDelta = readUnsignedShort(currentOffset);\n currentOffset += 2;\n if (frameType == Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels);\n context.currentFrameType = Opcodes.F_SAME1;\n context.currentFrameStackCount = 1;\n } else if (frameType >= Frame.CHOP_FRAME && frameType < Frame.SAME_FRAME_EXTENDED) {\n context.currentFrameType = Opcodes.F_CHOP;\n context.currentFrameLocalCountDelta = Frame.SAME_FRAME_EXTENDED - frameType;\n context.currentFrameLocalCount -= context.currentFrameLocalCountDelta;\n context.currentFrameStackCount = 0;\n } else if (frameType == Frame.SAME_FRAME_EXTENDED) {\n context.currentFrameType = Opcodes.F_SAME;\n context.currentFrameStackCount = 0;\n } else if (frameType < Frame.FULL_FRAME) {\n int local = expand ? context.currentFrameLocalCount : 0;\n for (int k = frameType - Frame.SAME_FRAME_EXTENDED; k > 0; k--) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameLocalTypes, local++, charBuffer, labels);\n }\n context.currentFrameType = Opcodes.F_APPEND;\n context.currentFrameLocalCountDelta = frameType - Frame.SAME_FRAME_EXTENDED;\n context.currentFrameLocalCount += context.currentFrameLocalCountDelta;\n context.currentFrameStackCount = 0;\n } else {\n final int numberOfLocals = readUnsignedShort(currentOffset);\n currentOffset += 2;\n context.currentFrameType = Opcodes.F_FULL;\n context.currentFrameLocalCountDelta = numberOfLocals;\n context.currentFrameLocalCount = numberOfLocals;\n for (int local = 0; local < numberOfLocals; ++local) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameLocalTypes, local, charBuffer, labels);\n }\n final int numberOfStackItems = readUnsignedShort(currentOffset);\n currentOffset += 2;\n context.currentFrameStackCount = numberOfStackItems;\n for (int stack = 0; stack < numberOfStackItems; ++stack) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameStackTypes, stack, charBuffer, labels);\n }\n }\n } else {\n throw new IllegalArgumentException();\n }\n context.currentFrameOffset += offsetDelta + 1;\n createLabel(context.currentFrameOffset, labels);\n return currentOffset;\n }\n\n /**\n * Reads a JVMS 'verification_type_info' structure and stores it at the given index in the given\n * array.\n *\n * @param verificationTypeInfoOffset the start offset of the 'verification_type_info' structure to\n * read.\n * @param frame the array where the parsed type must be stored.\n * @param index the index in 'frame' where the parsed type must be stored.\n * @param charBuffer the buffer used to read strings in the constant pool.\n * @param labels the labels of the method currently being parsed, indexed by their offset. If the\n * parsed type is an ITEM_Uninitialized, a new label for the corresponding NEW instruction is\n * stored in this array if it does not already exist.\n * @return the end offset of the JVMS 'verification_type_info' structure.\n */\n private int readVerificationTypeInfo(final int verificationTypeInfoOffset, final Object[] frame, final int index, final char[] charBuffer, final Label[] labels) {\n int currentOffset = verificationTypeInfoOffset;\n int tag = classFileBuffer[currentOffset++] & 0xFF;\n switch (tag) {\n case Frame.ITEM_TOP:\n frame[index] = Opcodes.TOP;\n break;\n case Frame.ITEM_INTEGER:\n frame[index] = Opcodes.INTEGER;\n break;\n case Frame.ITEM_FLOAT:\n frame[index] = Opcodes.FLOAT;\n break;\n case Frame.ITEM_DOUBLE:\n frame[index] = Opcodes.DOUBLE;\n break;\n case Frame.ITEM_LONG:\n frame[index] = Opcodes.LONG;\n break;\n case Frame.ITEM_NULL:\n frame[index] = Opcodes.NULL;\n break;\n case Frame.ITEM_UNINITIALIZED_THIS:\n frame[index] = Opcodes.UNINITIALIZED_THIS;\n break;\n case Frame.ITEM_OBJECT:\n frame[index] = readClass(currentOffset, charBuffer);\n currentOffset += 2;\n break;\n case Frame.ITEM_UNINITIALIZED:\n frame[index] = createLabel(readUnsignedShort(currentOffset), labels);\n currentOffset += 2;\n break;\n default:\n throw new IllegalArgumentException();\n }\n return currentOffset;\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse attributes\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Returns the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array\n * field entry.\n *\n * @return the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array\n * field entry.\n */\n final int getFirstAttributeOffset() {\n // Skip the access_flags, this_class, super_class, and interfaces_count fields (using 2 bytes\n // each), as well as the interfaces array field (2 bytes per interface).\n int currentOffset = header + 8 + readUnsignedShort(header + 6) * 2;\n // Read the fields_count field.\n int fieldsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n // Skip the 'fields' array field.\n while (fieldsCount-- > 0) {\n // Invariant: currentOffset is the offset of a field_info structure.\n // Skip the access_flags, name_index and descriptor_index fields (2 bytes each), and read the\n // attributes_count field.\n int attributesCount = readUnsignedShort(currentOffset + 6);\n currentOffset += 8;\n // Skip the 'attributes' array field.\n while (attributesCount-- > 0) {\n // Invariant: currentOffset is the offset of an attribute_info structure.\n // Read the attribute_length field (2 bytes after the start of the attribute_info) and skip\n // this many bytes, plus 6 for the attribute_name_index and attribute_length fields\n // (yielding the total size of the attribute_info structure).\n currentOffset += 6 + readInt(currentOffset + 2);\n }\n }\n // Skip the methods_count and 'methods' fields, using the same method as above.\n int methodsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (methodsCount-- > 0) {\n int attributesCount = readUnsignedShort(currentOffset + 6);\n currentOffset += 8;\n while (attributesCount-- > 0) {\n currentOffset += 6 + readInt(currentOffset + 2);\n }\n }\n // Skip the ClassFile's attributes_count field.\n return currentOffset + 2;\n }\n\n /**\n * Reads the BootstrapMethods attribute to compute the offset of each bootstrap method.\n *\n * @param maxStringLength a conservative estimate of the maximum length of the strings contained\n * in the constant pool of the class.\n * @return the offsets of the bootstrap methods.\n */\n private int[] readBootstrapMethodsAttribute(final int maxStringLength) {\n char[] charBuffer = new char[maxStringLength];\n int currentAttributeOffset = getFirstAttributeOffset();\n int[] currentBootstrapMethodOffsets = null;\n for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentAttributeOffset, charBuffer);\n int attributeLength = readInt(currentAttributeOffset + 2);\n currentAttributeOffset += 6;\n if (Constants.BOOTSTRAP_METHODS.equals(attributeName)) {\n // Read the num_bootstrap_methods field and create an array of this size.\n currentBootstrapMethodOffsets = new int[readUnsignedShort(currentAttributeOffset)];\n // Compute and store the offset of each 'bootstrap_methods' array field entry.\n int currentBootstrapMethodOffset = currentAttributeOffset + 2;\n for (int j = 0; j < currentBootstrapMethodOffsets.length; ++j) {\n currentBootstrapMethodOffsets[j] = currentBootstrapMethodOffset;\n // Skip the bootstrap_method_ref and num_bootstrap_arguments fields (2 bytes each),\n // as well as the bootstrap_arguments array field (of size num_bootstrap_arguments * 2).\n currentBootstrapMethodOffset += 4 + readUnsignedShort(currentBootstrapMethodOffset + 2) * 2;\n }\n return currentBootstrapMethodOffsets;\n }\n currentAttributeOffset += attributeLength;\n }\n throw new IllegalArgumentException();\n }\n\n /**\n * Reads a non standard JVMS 'attribute' structure in {@link #classFileBuffer}.\n *\n * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of\n * the class. Any attribute whose type is not equal to the type of one the prototypes will not\n * be parsed: its byte array value will be passed unchanged to the ClassWriter.\n * @param type the type of the attribute.\n * @param offset the start offset of the JVMS 'attribute' structure in {@link #classFileBuffer}.\n * The 6 attribute header bytes (attribute_name_index and attribute_length) are not taken into\n * account here.\n * @param length the length of the attribute's content (excluding the 6 attribute header bytes).\n * @param charBuffer the buffer to be used to read strings in the constant pool.\n * @param codeAttributeOffset the start offset of the enclosing Code attribute in {@link\n * #classFileBuffer}, or -1 if the attribute to be read is not a code attribute. The 6\n * attribute header bytes (attribute_name_index and attribute_length) are not taken into\n * account here.\n * @param labels the labels of the method's code, or {@literal null} if the attribute to be read\n * is not a code attribute.\n * @return the attribute that has been read.\n */\n private Attribute readAttribute(final Attribute[] attributePrototypes, final String type, final int offset, final int length, final char[] charBuffer, final int codeAttributeOffset, final Label[] labels) {\n for (Attribute attributePrototype : attributePrototypes) {\n if (attributePrototype.type.equals(type)) {\n return attributePrototype.read(this, offset, length, charBuffer, codeAttributeOffset, labels);\n }\n }\n return new Attribute(type).read(this, offset, length, null, -1, null);\n }\n // -----------------------------------------------------------------------------------------------\n // Utility methods: low level parsing\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the number of entries in the class's constant pool table.\n *\n * @return the number of entries in the class's constant pool table.\n */\n public int getItemCount() {\n return cpInfoOffsets.length;\n }\n\n /**\n * Returns the start offset in this {@link ClassReader} of a JVMS 'cp_info' structure (i.e. a\n * constant pool entry), plus one. This method is intended for {@link Attribute} sub classes,\n * and is normally not needed by class generators or adapters.\n *\n * @param constantPoolEntryIndex the index a constant pool entry in the class's constant pool\n * table.\n * @return the start offset in this {@link ClassReader} of the corresponding JVMS 'cp_info'\n * structure, plus one.\n */\n public int getItem(final int constantPoolEntryIndex) {\n return cpInfoOffsets[constantPoolEntryIndex];\n }\n\n /**\n * Returns a conservative estimate of the maximum length of the strings contained in the class's\n * constant pool table.\n *\n * @return a conservative estimate of the maximum length of the strings contained in the class's\n * constant pool table.\n */\n public int getMaxStringLength() {\n return maxStringLength;\n }\n\n /**\n * Reads a byte value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public int readByte(final int offset) {\n return classFileBuffer[offset] & 0xFF;\n }\n\n /**\n * Reads an unsigned short value in this {@link ClassReader}. This method is intended for\n * {@link Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start index of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public int readUnsignedShort(final int offset) {\n byte[] classBuffer = classFileBuffer;\n return ((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF);\n }\n\n /**\n * Reads a signed short value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public short readShort(final int offset) {\n byte[] classBuffer = classFileBuffer;\n return (short) (((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF));\n }\n\n /**\n * Reads a signed int value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public int readInt(final int offset) {\n byte[] classBuffer = classFileBuffer;\n return ((classBuffer[offset] & 0xFF) << 24) | ((classBuffer[offset + 1] & 0xFF) << 16) | ((classBuffer[offset + 2] & 0xFF) << 8) | (classBuffer[offset + 3] & 0xFF);\n }\n\n /**\n * Reads a signed long value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public long readLong(final int offset) {\n long l1 = readInt(offset);\n long l0 = readInt(offset + 4) & 0xFFFFFFFFL;\n return (l1 << 32) | l0;\n }\n\n /**\n * Reads a CONSTANT_Utf8 constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Utf8 entry in the class's constant pool table.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Utf8 entry.\n */\n // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility).\n public String readUTF8(final int offset, final char[] charBuffer) {\n int constantPoolEntryIndex = readUnsignedShort(offset);\n if (offset == 0 || constantPoolEntryIndex == 0) {\n return null;\n }\n return readUtf(constantPoolEntryIndex, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Utf8 constant pool entry in {@link #classFileBuffer}.\n *\n * @param constantPoolEntryIndex the index of a CONSTANT_Utf8 entry in the class's constant pool\n * table.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Utf8 entry.\n */\n final String readUtf(final int constantPoolEntryIndex, final char[] charBuffer) {\n String value = constantUtf8Values[constantPoolEntryIndex];\n if (value != null) {\n return value;\n }\n int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex];\n return constantUtf8Values[constantPoolEntryIndex] = readUtf(cpInfoOffset + 2, readUnsignedShort(cpInfoOffset), charBuffer);\n }\n\n /**\n * Reads an UTF8 string in {@link #classFileBuffer}.\n *\n * @param utfOffset the start offset of the UTF8 string to be read.\n * @param utfLength the length of the UTF8 string to be read.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified UTF8 string.\n */\n private String readUtf(final int utfOffset, final int utfLength, final char[] charBuffer) {\n int currentOffset = utfOffset;\n int endOffset = currentOffset + utfLength;\n int strLength = 0;\n byte[] classBuffer = classFileBuffer;\n while (currentOffset < endOffset) {\n int currentByte = classBuffer[currentOffset++];\n if ((currentByte & 0x80) == 0) {\n charBuffer[strLength++] = (char) (currentByte & 0x7F);\n } else if ((currentByte & 0xE0) == 0xC0) {\n charBuffer[strLength++] = (char) (((currentByte & 0x1F) << 6) + (classBuffer[currentOffset++] & 0x3F));\n } else {\n charBuffer[strLength++] = (char) (((currentByte & 0xF) << 12) + ((classBuffer[currentOffset++] & 0x3F) << 6) + (classBuffer[currentOffset++] & 0x3F));\n }\n }\n return new String(charBuffer, 0, strLength);\n }\n\n /**\n * Reads a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, CONSTANT_Module or\n * CONSTANT_Package constant pool entry in {@link #classFileBuffer}. This method is intended\n * for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in {@link #classFileBuffer}, whose\n * value is the index of a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType,\n * CONSTANT_Module or CONSTANT_Package entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified constant pool entry.\n */\n private String readStringish(final int offset, final char[] charBuffer) {\n // Get the start offset of the cp_info structure (plus one), and read the CONSTANT_Utf8 entry\n // designated by the first two bytes of this cp_info.\n return readUTF8(cpInfoOffsets[readUnsignedShort(offset)], charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Class constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Class entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Class entry.\n */\n public String readClass(final int offset, final char[] charBuffer) {\n return readStringish(offset, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Module constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Module entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Module entry.\n */\n public String readModule(final int offset, final char[] charBuffer) {\n return readStringish(offset, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Package constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Package entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Package entry.\n */\n public String readPackage(final int offset, final char[] charBuffer) {\n return readStringish(offset, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Dynamic constant pool entry in {@link #classFileBuffer}.\n *\n * @param constantPoolEntryIndex the index of a CONSTANT_Dynamic entry in the class's constant\n * pool table.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the ConstantDynamic corresponding to the specified CONSTANT_Dynamic entry.\n */\n private ConstantDynamic readConstantDynamic(final int constantPoolEntryIndex, final char[] charBuffer) {\n ConstantDynamic constantDynamic = constantDynamicValues[constantPoolEntryIndex];\n if (constantDynamic != null) {\n return constantDynamic;\n }\n int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)];\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)];\n Handle handle = (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n Object[] bootstrapMethodArguments = new Object[readUnsignedShort(bootstrapMethodOffset + 2)];\n bootstrapMethodOffset += 4;\n for (int i = 0; i < bootstrapMethodArguments.length; i++) {\n bootstrapMethodArguments[i] = readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n bootstrapMethodOffset += 2;\n }\n return constantDynamicValues[constantPoolEntryIndex] = new ConstantDynamic(name, descriptor, handle, bootstrapMethodArguments);\n }\n\n /**\n * Reads a numeric or string constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param constantPoolEntryIndex the index of a CONSTANT_Integer, CONSTANT_Float, CONSTANT_Long,\n * CONSTANT_Double, CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType,\n * CONSTANT_MethodHandle or CONSTANT_Dynamic entry in the class's constant pool.\n * @param charBuffer the buffer to be used to read strings. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the {@link Integer}, {@link Float}, {@link Long}, {@link Double}, {@link String},\n * {@link Type}, {@link Handle} or {@link ConstantDynamic} corresponding to the specified\n * constant pool entry.\n */\n public Object readConst(final int constantPoolEntryIndex, final char[] charBuffer) {\n int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex];\n switch (classFileBuffer[cpInfoOffset - 1]) {\n case Symbol.CONSTANT_INTEGER_TAG:\n return readInt(cpInfoOffset);\n case Symbol.CONSTANT_FLOAT_TAG:\n return Float.intBitsToFloat(readInt(cpInfoOffset));\n case Symbol.CONSTANT_LONG_TAG:\n return readLong(cpInfoOffset);\n case Symbol.CONSTANT_DOUBLE_TAG:\n return Double.longBitsToDouble(readLong(cpInfoOffset));\n case Symbol.CONSTANT_CLASS_TAG:\n return Type.getObjectType(readUTF8(cpInfoOffset, charBuffer));\n case Symbol.CONSTANT_STRING_TAG:\n return readUTF8(cpInfoOffset, charBuffer);\n case Symbol.CONSTANT_METHOD_TYPE_TAG:\n return Type.getMethodType(readUTF8(cpInfoOffset, charBuffer));\n case Symbol.CONSTANT_METHOD_HANDLE_TAG:\n int referenceKind = readByte(cpInfoOffset);\n int referenceCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 1)];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(referenceCpInfoOffset + 2)];\n String owner = readClass(referenceCpInfoOffset, charBuffer);\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n boolean isInterface = classFileBuffer[referenceCpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG;\n return new Handle(referenceKind, owner, name, descriptor, isInterface);\n case Symbol.CONSTANT_DYNAMIC_TAG:\n return readConstantDynamic(constantPoolEntryIndex, charBuffer);\n default:\n throw new IllegalArgumentException();\n }\n }\n}\n", "file_name": "ClassReader.java", "human_label": "Read a signed long value.", "level": "class_runnable", "lineno": "3123", "name": "readLong", "oracle_context": "{ \"apis\" : \"[readInt]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils.asm", "project": "hasor-master" }, { "_id": "636767a51a6d9265ec01859d", "all_context": "{ \"class_level\" : \"import static io.protostuff.StringSerializer.STRING;\\nimport java.io.DataOutput;\\nimport java.io.IOException;\\nimport java.io.OutputStream;\\nimport java.io.UnsupportedEncodingException;\\nimport java.nio.ByteBuffer;\\nbyte[] bytes;\\nString EMPTY_STRING;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByteString EMPTY;\\nint hash;\\nwrap(byte[] bytes);\\ngetBytes();\\nwriteTo(DataOutput out,ByteString bs);\\nwriteTo(Output output,ByteString bs,int fieldNumber,boolean repeated);\\ntoString();\\nByteString(byte[] bytes);\\nbyteAt(int index);\\nsize();\\nisEmpty();\\ncopyFrom(byte[] bytes,int offset,int size);\\ncopyFrom(byte[] bytes);\\ncopyFrom(String text,String charsetName);\\ncopyFromUtf8(String text);\\ncopyTo(byte[] target,int offset);\\ncopyTo(byte[] target,int sourceOffset,int targetOffset,int size);\\ntoByteArray();\\nasReadOnlyByteBuffer();\\ntoStringUtf8();\\nequals(Object o);\\nequals(ByteString bs,ByteString other,boolean checkHash);\\nequals(byte[] data);\\nequals(byte[] data,int offset,int len);\\nhashCode();\\nstringDefaultValue(String bytes);\\nbytesDefaultValue(String bytes);\\nbyteArrayDefaultValue(String bytes);\\nwriteTo(OutputStream out,ByteString bs);\\n\", \"repo_level\" : \"\" }", "class_name": "ByteString", "code": "public boolean equals(final byte[] data,int offset,final int len){\n final byte[] bytes=this.bytes;\n if (len != bytes.length) return false;\n for (int i=0; i < len; ) {\n if (bytes[i++] != data[offset++]) {\n return false;\n }\n }\n return true;\n}\n", "docstring": "/** \n * Returns true if the contents of the internal array and the provided array match.\n */\n", "end_lineno": "353", "file_content": "//========================================================================\n//Copyright 2007-2009 David Yu dyuproject@gmail.com\n//------------------------------------------------------------------------\n//Licensed under the Apache License, Version 2.0 (the \"License\");\n//you may not use this file except in compliance with the License.\n//You may obtain a copy of the License at \n//http://www.apache.org/licenses/LICENSE-2.0\n//Unless required by applicable law or agreed to in writing, software\n//distributed under the License is distributed on an \"AS IS\" BASIS,\n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//See the License for the specific language governing permissions and\n//limitations under the License.\n//========================================================================\n\n// Protocol Buffers - Google's data interchange format\n// Copyright 2008 Google Inc. All rights reserved.\n// http://code.google.com/p/protobuf/\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\npackage io.protostuff;\n\nimport static io.protostuff.StringSerializer.STRING;\n\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.nio.ByteBuffer;\n\n/**\n * Immutable array of bytes.\n * \n * @author crazybob@google.com Bob Lee\n * @author kenton@google.com Kenton Varda\n * @author David Yu\n */\npublic final class ByteString\n{\n // START EXTRA\n // internal package access to avoid double memory allocation\n static ByteString wrap(byte[] bytes)\n {\n return new ByteString(bytes);\n }\n\n // internal package access to avoid double memory allocation\n byte[] getBytes()\n {\n return bytes;\n }\n\n /**\n * Writes the bytes to the {@link OutputStream}.\n */\n public static void writeTo(OutputStream out, ByteString bs) throws IOException\n {\n out.write(bs.bytes);\n }\n\n /**\n * Writes the bytes to the {@link DataOutput}.\n */\n public static void writeTo(DataOutput out, ByteString bs) throws IOException\n {\n out.write(bs.bytes);\n }\n\n /**\n * Writes the bytes to the {@link Output}.\n */\n public static void writeTo(Output output, ByteString bs, int fieldNumber,\n boolean repeated) throws IOException\n {\n output.writeByteArray(fieldNumber, bs.bytes, repeated);\n }\n\n @Override\n public String toString()\n {\n return String.format(\"\",\n Integer.toHexString(System.identityHashCode(this)), size());\n }\n\n // END EXTRA\n private final byte[] bytes;\n\n private ByteString(final byte[] bytes)\n {\n this.bytes = bytes;\n }\n\n /**\n * Gets the byte at the given index.\n * \n * @throws ArrayIndexOutOfBoundsException\n * {@code index} is < 0 or >= size\n */\n public byte byteAt(final int index)\n {\n return bytes[index];\n }\n\n /**\n * Gets the number of bytes.\n */\n public int size()\n {\n return bytes.length;\n }\n\n /**\n * Returns {@code true} if the size is {@code 0}, {@code false} otherwise.\n */\n public boolean isEmpty()\n {\n return bytes.length == 0;\n }\n\n // =================================================================\n // byte[] -> ByteString\n\n /**\n * Empty String.\n */\n public static final String EMPTY_STRING = \"\";\n\n /**\n * Empty byte array.\n */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n\n /**\n * Empty ByteString.\n */\n public static final ByteString EMPTY = new ByteString(EMPTY_BYTE_ARRAY);\n\n /**\n * Copies the given bytes into a {@code ByteString}.\n */\n public static ByteString copyFrom(final byte[] bytes, final int offset,\n final int size)\n {\n final byte[] copy = new byte[size];\n System.arraycopy(bytes, offset, copy, 0, size);\n return new ByteString(copy);\n }\n\n /**\n * Copies the given bytes into a {@code ByteString}.\n */\n public static ByteString copyFrom(final byte[] bytes)\n {\n return copyFrom(bytes, 0, bytes.length);\n }\n\n /**\n * Encodes {@code text} into a sequence of bytes using the named charset and returns the result as a\n * {@code ByteString}.\n */\n public static ByteString copyFrom(final String text, final String charsetName)\n {\n try\n {\n return new ByteString(text.getBytes(charsetName));\n }\n catch (UnsupportedEncodingException e)\n {\n throw new RuntimeException(charsetName + \" not supported?\", e);\n }\n }\n\n /**\n * Encodes {@code text} into a sequence of UTF-8 bytes and returns the result as a {@code ByteString}.\n */\n public static ByteString copyFromUtf8(final String text)\n {\n return new ByteString(STRING.ser(text));\n /*\n * @try { return new ByteString(text.getBytes(\"UTF-8\")); } catch (UnsupportedEncodingException e) { throw new\n * RuntimeException(\"UTF-8 not supported?\", e); }\n */\n }\n\n // =================================================================\n // ByteString -> byte[]\n\n /**\n * Copies bytes into a buffer at the given offset.\n * \n * @param target\n * buffer to copy into\n * @param offset\n * in the target buffer\n */\n public void copyTo(final byte[] target, final int offset)\n {\n System.arraycopy(bytes, 0, target, offset, bytes.length);\n }\n\n /**\n * Copies bytes into a buffer.\n * \n * @param target\n * buffer to copy into\n * @param sourceOffset\n * offset within these bytes\n * @param targetOffset\n * offset within the target buffer\n * @param size\n * number of bytes to copy\n */\n public void copyTo(final byte[] target, final int sourceOffset,\n final int targetOffset,\n final int size)\n {\n System.arraycopy(bytes, sourceOffset, target, targetOffset, size);\n }\n\n /**\n * Copies bytes to a {@code byte[]}.\n */\n public byte[] toByteArray()\n {\n final int size = bytes.length;\n final byte[] copy = new byte[size];\n System.arraycopy(bytes, 0, copy, 0, size);\n return copy;\n }\n\n /**\n * Constructs a new read-only {@code java.nio.ByteBuffer} with the same backing byte array.\n */\n public ByteBuffer asReadOnlyByteBuffer()\n {\n final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);\n return byteBuffer.asReadOnlyBuffer();\n }\n\n /*\n * @ Constructs a new {@code String} by decoding the bytes using the specified charset.\n */\n /*\n * @public String unsignedIntToString(final String charsetName) throws UnsupportedEncodingException { return new String(bytes,\n * charsetName); }\n */\n\n /**\n * Constructs a new {@code String} by decoding the bytes as UTF-8.\n */\n public String toStringUtf8()\n {\n return STRING.deser(bytes);\n /*\n * @try { return new String(bytes, \"UTF-8\"); } catch (UnsupportedEncodingException e) { throw new\n * RuntimeException(\"UTF-8 not supported?\", e); }\n */\n }\n\n // =================================================================\n // equals() and hashCode()\n\n @Override\n public boolean equals(final Object o)\n {\n return o == this || (o instanceof ByteString && equals(this, (ByteString) o, false));\n }\n\n /**\n * Returns true if the contents of both match.\n */\n public static boolean equals(ByteString bs, ByteString other, boolean checkHash)\n {\n final int size = bs.bytes.length;\n if (size != other.bytes.length)\n {\n return false;\n }\n\n if (checkHash)\n {\n // volatile reads\n final int h1 = bs.hash, h2 = other.hash;\n if (h1 != 0 && h2 != 0 && h1 != h2)\n {\n return false;\n }\n }\n\n final byte[] thisBytes = bs.bytes;\n final byte[] otherBytes = other.bytes;\n for (int i = 0; i < size; i++)\n {\n if (thisBytes[i] != otherBytes[i])\n {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Returns true if the contents of the internal array and the provided array match.\n */\n public boolean equals(final byte[] data)\n {\n return equals(data, 0, data.length);\n }\n\n /**\n * Returns true if the contents of the internal array and the provided array match.\n */\n public boolean equals(final byte[] data, int offset, final int len)\n {\n final byte[] bytes = this.bytes;\n if (len != bytes.length)\n return false;\n\n for (int i = 0; i < len;)\n {\n if (bytes[i++] != data[offset++])\n {\n return false;\n }\n }\n\n return true;\n }\n\n private volatile int hash = 0;\n\n @Override\n public int hashCode()\n {\n int h = hash;\n\n if (h == 0)\n {\n final byte[] thisBytes = bytes;\n final int size = bytes.length;\n\n h = size;\n for (int i = 0; i < size; i++)\n {\n h = h * 31 + thisBytes[i];\n }\n if (h == 0)\n {\n h = 1;\n }\n\n hash = h;\n }\n\n return h;\n }\n\n // =================================================================\n // Input stream\n\n /*\n * @ Creates an {@code InputStream} which can be used to read the bytes.\n */\n /*\n * @public InputStream newInput() { return new ByteArrayInputStream(bytes); }\n */\n\n /*\n * @ Creates a {@link CodedInputStream} which can be used to read the bytes. Using this is more efficient than\n * creating a {@link CodedInputStream} wrapping the result of {@link #newInput()}.\n */\n /*\n * @public CodedInputStream newCodedInput() { // We trust CodedInputStream not to modify the bytes, or to give\n * anyone // else access to them. return CodedInputStream.newInstance(bytes); }\n */\n\n // =================================================================\n // Output stream\n\n /*\n * @ Creates a new {@link Output} with the given initial capacity.\n */\n /*\n * @public static Output newOutput(final int initialCapacity) { return new Output(new\n * ByteArrayOutputStream(initialCapacity)); }\n */\n\n /*\n * @ Creates a new {@link Output}.\n */\n /*\n * @public static Output newOutput() { return newOutput(32); }\n */\n\n /*\n * @ Outputs to a {@code ByteString} instance. Call {@link #toByteString()} to create the {@code ByteString}\n * instance.\n */\n /*\n * @public static final class Output extends FilterOutputStream { private final ByteArrayOutputStream bout;\n * \n * /** Constructs a new output with the given initial capacity.\n * \n * @ private Output(final ByteArrayOutputStream bout) { super(bout); this.bout = bout; }\n * \n * /** Creates a {@code ByteString} instance from this {@code Output}.\n * \n * @ public ByteString toByteString() { final byte[] byteArray = bout.toByteArray(); return new\n * ByteString(byteArray); } }\n * \n * /** Constructs a new ByteString builder, which allows you to efficiently construct a {@code ByteString} by\n * writing to a {@link CodedOutputStream}. Using this is much more efficient than calling {@code newOutput()} and\n * wrapping that in a {@code CodedOutputStream}.\n * \n *

This is package-private because it's a somewhat confusing interface. Users can call {@link\n * Message#toByteString()} instead of calling this directly.\n * \n * @param size The target byte size of the {@code ByteString}. You must write exactly this many bytes before\n * building the result.\n * \n * @ static CodedBuilder newCodedBuilder(final int size) { return new CodedBuilder(size); }\n * \n * /** See {@link ByteString#newCodedBuilder(int)}. *@ static final class CodedBuilder { private final\n * CodedOutputStream output; private final byte[] buffer;\n * \n * private CodedBuilder(final int size) { buffer = new byte[size]; output = CodedOutputStream.newInstance(buffer); }\n * \n * public ByteString build() { output.checkNoSpaceLeft();\n * \n * // We can be confident that the CodedOutputStream will not modify the // underlying bytes anymore because it\n * already wrote all of them. So, // no need to make a copy. return new ByteString(buffer); }\n * \n * public CodedOutputStream getCodedOutput() { return output; } }\n */\n\n // moved from Internal.java\n\n /**\n * Helper called by generated code to construct default values for string fields.\n *

\n * The protocol compiler does not actually contain a UTF-8 decoder -- it just pushes UTF-8-encoded text around\n * without touching it. The one place where this presents a problem is when generating Java string literals. Unicode\n * characters in the string literal would normally need to be encoded using a Unicode escape sequence, which would\n * require decoding them. To get around this, protoc instead embeds the UTF-8 bytes into the generated code and\n * leaves it to the runtime library to decode them.\n *

\n * It gets worse, though. If protoc just generated a byte array, like: new byte[] {0x12, 0x34, 0x56, 0x78} Java\n * actually generates *code* which allocates an array and then fills in each value. This is much less efficient than\n * just embedding the bytes directly into the bytecode. To get around this, we need another work-around. String\n * literals are embedded directly, so protoc actually generates a string literal corresponding to the bytes. The\n * easiest way to do this is to use the ISO-8859-1 character set, which corresponds to the first 256 characters of\n * the Unicode range. Protoc can then use good old CEscape to generate the string.\n *

\n * So we have a string literal which represents a set of bytes which represents another string. This function --\n * stringDefaultValue -- converts from the generated string to the string we actually want. The generated code calls\n * this automatically.\n */\n public static String stringDefaultValue(String bytes)\n {\n try\n {\n return new String(bytes.getBytes(\"ISO-8859-1\"), \"UTF-8\");\n }\n catch (UnsupportedEncodingException e)\n {\n // This should never happen since all JVMs are required to implement\n // both of the above character sets.\n throw new IllegalStateException(\n \"Java VM does not support a standard character set.\", e);\n }\n }\n\n /**\n * Helper called by generated code to construct default values for bytes fields.\n *

\n * This is a lot like {@link #stringDefaultValue}, but for bytes fields. In this case we only need the second of the\n * two hacks -- allowing us to embed raw bytes as a string literal with ISO-8859-1 encoding.\n */\n public static ByteString bytesDefaultValue(String bytes)\n {\n return new ByteString(byteArrayDefaultValue(bytes));\n }\n\n /**\n * Helper called by generated code to construct default values for byte array fields.\n *

\n * This is a lot like {@link #stringDefaultValue}, but for bytes fields. In this case we only need the second of the\n * two hacks -- allowing us to embed raw bytes as a string literal with ISO-8859-1 encoding.\n */\n public static byte[] byteArrayDefaultValue(String bytes)\n {\n try\n {\n return bytes.getBytes(\"ISO-8859-1\");\n }\n catch (UnsupportedEncodingException e)\n {\n // This should never happen since all JVMs are required to implement\n // ISO-8859-1.\n throw new IllegalStateException(\n \"Java VM does not support a standard character set.\", e);\n }\n }\n}\n", "file_name": "ByteString.java", "human_label": "Return true if the contents of the internal array bytes and the provided array data match.", "level": "class_runnable", "lineno": "335", "name": "equals", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[byte[]]\", \"vars\" : \"[length]\" }", "package": "io.protostuff", "project": "protostuff-master" }, { "_id": "6367670b1a6d9265ec0179ff", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static Byte[] nullToEmpty(final Byte[] array){\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n}\n", "docstring": "/** \n *

Defensive programming technique to change a null reference to an empty one.

This method returns an empty array for a null input array.

As a memory optimizing technique an empty array passed in will be overridden with the empty public static references in this class.

\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n", "end_lineno": "617", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

\n *\n *

This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

\n *\n *

#ThreadSafe#

\n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

\n *\n *

This method can be used to initialize:

\n *
\n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
\n *\n *

This method returns null for a null input array.

\n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

Shallow clones an array returning a typecast result and handling\n * null.

\n *\n *

The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

Produces a new array containing the elements between\n * the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n *

The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

\n *\n *
\n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new long array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new int array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new short array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new char array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new byte array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new double array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new float array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new boolean array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

Any multi-dimensional aspects of the arrays are ignored.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

\n *\n *

If the input array is null, 0 is returned.

\n *\n *
\n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
\n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

\n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

Reverses the order of the given array.

\n *\n *

There is no special handling for multi-dimensional arrays.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given object in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

Finds the index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given object within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the object is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

\n *\n *

The method returns false if a null array\n * is passed in.

\n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Characters to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Character to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive chars to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Longs to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Long to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive longs to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Integers to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Integer to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive ints to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Shorts to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Short to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive shorts to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Bytes to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Bytes to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive bytes to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Doubles to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Doubles to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive doubles to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Floats to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Floats to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive floats to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Booleans to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Booleans to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive booleans to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive longs is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive ints is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive chars is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive floats is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive longs is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive ints is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive chars is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive floats is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

\n *\n *
\n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Return an EMPTY_BYTE_OBJECT_ARRAY array for a null or empty input array.", "level": "self_contained", "lineno": "599", "name": "nullToEmpty", "oracle_context": "{ \"apis\" : \"[ArrayUtils]\", \"classes\" : \"[ArrayUtils]\", \"vars\" : \"[length, EMPTY_BYTE_OBJECT_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "6367677f1a6d9265ec018347", "all_context": "{ \"class_level\" : \"import org.apache.log4j.AppenderSkeleton;\\nimport org.apache.log4j.helpers.LogLog;\\nimport org.apache.log4j.spi.LoggingEvent;\\nimport java.io.IOException;\\nimport java.io.PrintWriter;\\nimport java.io.InterruptedIOException;\\nimport java.net.ServerSocket;\\nimport java.net.Socket;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.Vector;\\nSocketHandler sh;\\nint port;\\nVector writers;\\nVector connections;\\nServerSocket serverSocket;\\nint MAX_CONNECTIONS;\\nactivateOptions();\\ngetPort();\\nsetPort(int port);\\nclose();\\nappend(LoggingEvent event);\\nfinalize();\\nsend(String message);\\nrun();\\nSocketHandler(int port);\\nrequiresLayout();\\n\", \"repo_level\" : \"public interface AppenderSkeleton {public void activateOptions();\\npublic void addFilter(Filter newFilter);\\nprotected void append(LoggingEvent event);\\npublic void clearFilters();\\npublic void finalize();\\npublic ErrorHandler getErrorHandler();\\npublic Filter getFilter();\\nfinal Filter getFirstFilter();\\npublic Layout getLayout();\\nfinal String getName();\\npublic Priority getThreshold();\\npublic boolean isAsSevereAsThreshold(Priority priority);\\nsynchronized void doAppend(LoggingEvent event);\\nsynchronized void setErrorHandler(ErrorHandler eh);\\npublic void setLayout(Layout layout);\\npublic void setName(String name);\\npublic void setThreshold(Priority threshold);\\n }\\npublic interface LogLog {public void setInternalDebugging(boolean enabled);\\nstatic void debug(String msg);\\nstatic void debug(String msg,Throwable t);\\nstatic void error(String msg);\\nstatic void error(String msg,Throwable t);\\nstatic void setQuietMode(boolean quietMode);\\nstatic void warn(String msg);\\nstatic void warn(String msg,Throwable t);\\n }\\npublic interface LoggingEvent {public LocationInfo getLocationInformation();\\npublic Level getLevel();\\npublic String getLoggerName();\\npublic Category getLogger();\\npublic Object getMessage();\\npublic String getNDC();\\npublic Object getMDC(String key);\\npublic void getMDCCopy();\\npublic String getRenderedMessage();\\nstatic long getStartTime();\\npublic String getThreadName();\\npublic ThrowableInformation getThrowableInformation();\\npublic String[] getThrowableStrRep();\\nfinal void setProperty(String propName,String propValue);\\nfinal String getProperty(String key);\\nfinal boolean locationInformationExists();\\nfinal long getTimeStamp();\\npublic Set getPropertyKeySet();\\npublic Map getProperties();\\npublic String getFQNOfLoggerClass();\\npublic Object removeProperty(String propName);\\n }\\n\" }", "class_name": "TelnetAppender", "code": "public synchronized void send(final String message){\n Iterator ce=connections.iterator();\n for (Iterator e=writers.iterator(); e.hasNext(); ) {\n ce.next();\n PrintWriter writer=(PrintWriter)e.next();\n writer.print(message);\n if (writer.checkError()) {\n ce.remove();\n e.remove();\n }\n }\n}\n", "docstring": "/** \n * sends a message to each of the clients in telnet-friendly output. \n */\n", "end_lineno": "187", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.log4j.net;\n\nimport org.apache.log4j.AppenderSkeleton;\nimport org.apache.log4j.helpers.LogLog;\nimport org.apache.log4j.spi.LoggingEvent;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.io.InterruptedIOException;\nimport java.net.ServerSocket;\nimport java.net.Socket;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.Vector;\n\n/**\n

The TelnetAppender is a log4j appender that specializes in\n writing to a read-only socket. The output is provided in a\n telnet-friendly way so that a log can be monitored over TCP/IP.\n Clients using telnet connect to the socket and receive log data.\n This is handy for remote monitoring, especially when monitoring a\n servlet.\n\n

Here is a list of the available configuration options:\n\n \n \n \n \n \n \n \n\n \n \n \n \n \n
NameRequirementDescriptionSample Value
PortoptionalThis parameter determines the port to use for announcing log events. The default port is 23 (telnet).5875
\n\n @author Jay Funnell\n*/\n\npublic class TelnetAppender extends AppenderSkeleton {\n\n private SocketHandler sh;\n private int port = 23;\n\n /** \n This appender requires a layout to format the text to the\n attached client(s). */\n public boolean requiresLayout() {\n return true;\n }\n\n /** all of the options have been set, create the socket handler and\n wait for connections. */\n public void activateOptions() {\n try {\n sh = new SocketHandler(port);\n sh.start();\n }\n catch(InterruptedIOException e) {\n Thread.currentThread().interrupt();\n e.printStackTrace();\n } catch(IOException e) {\n e.printStackTrace();\n } catch(RuntimeException e) {\n e.printStackTrace();\n }\n super.activateOptions();\n }\n\n public\n int getPort() {\n return port;\n }\n\n public\n void setPort(int port) {\n this.port = port;\n }\n\n\n /** shuts down the appender. */\n public void close() {\n if (sh != null) {\n sh.close();\n try {\n sh.join();\n } catch(InterruptedException ex) {\n Thread.currentThread().interrupt();\n }\n }\n }\n\n /** Handles a log event. For this appender, that means writing the\n message to each connected client. */\n protected void append(LoggingEvent event) {\n if(sh != null) {\n sh.send(layout.format(event));\n if(layout.ignoresThrowable()) {\n String[] s = event.getThrowableStrRep();\n if (s != null) {\n StringBuffer buf = new StringBuffer();\n for(int i = 0; i < s.length; i++) {\n buf.append(s[i]);\n buf.append(\"\\r\\n\");\n }\n sh.send(buf.toString());\n }\n }\n }\n }\n\n //---------------------------------------------------------- SocketHandler:\n\n /** The SocketHandler class is used to accept connections from\n clients. It is threaded so that clients can connect/disconnect\n asynchronously. */\n protected class SocketHandler extends Thread {\n\n private Vector writers = new Vector();\n private Vector connections = new Vector();\n private ServerSocket serverSocket;\n private int MAX_CONNECTIONS = 20;\n\n public void finalize() {\n close();\n }\n \n /** \n * make sure we close all network connections when this handler is destroyed.\n * @since 1.2.15 \n */\n public void close() {\n synchronized(this) {\n for(Enumeration e = connections.elements();e.hasMoreElements();) {\n try {\n ((Socket)e.nextElement()).close();\n } catch(InterruptedIOException ex) {\n Thread.currentThread().interrupt();\n } catch(IOException ex) {\n } catch(RuntimeException ex) {\n }\n }\n }\n\n try {\n serverSocket.close();\n } catch(InterruptedIOException ex) {\n Thread.currentThread().interrupt();\n } catch(IOException ex) {\n } catch(RuntimeException ex) {\n }\n }\n\n /** sends a message to each of the clients in telnet-friendly output. */\n public synchronized void send(final String message) {\n Iterator ce = connections.iterator();\n for(Iterator e = writers.iterator();e.hasNext();) {\n ce.next();\n PrintWriter writer = (PrintWriter)e.next();\n writer.print(message);\n if(writer.checkError()) {\n ce.remove();\n e.remove();\n }\n }\n }\n\n /** \n\tContinually accepts client connections. Client connections\n are refused when MAX_CONNECTIONS is reached. \n */\n public void run() {\n while(!serverSocket.isClosed()) {\n try {\n Socket newClient = serverSocket.accept();\n PrintWriter pw = new PrintWriter(newClient.getOutputStream());\n if(connections.size() < MAX_CONNECTIONS) {\n synchronized(this) {\n connections.addElement(newClient);\n writers.addElement(pw);\n pw.print(\"TelnetAppender v1.0 (\" + connections.size()\n\t\t + \" active connections)\\r\\n\\r\\n\");\n pw.flush();\n }\n } else {\n pw.print(\"Too many connections.\\r\\n\");\n pw.flush();\n newClient.close();\n }\n } catch(Exception e) {\n if (e instanceof InterruptedIOException || e instanceof InterruptedException) {\n Thread.currentThread().interrupt();\n }\n if (!serverSocket.isClosed()) {\n LogLog.error(\"Encountered error while in SocketHandler loop.\", e);\n }\n break;\n }\n }\n\n try {\n serverSocket.close();\n } catch(InterruptedIOException ex) {\n Thread.currentThread().interrupt();\n } catch(IOException ex) {\n }\n }\n\n public SocketHandler(int port) throws IOException {\n serverSocket = new ServerSocket(port);\n setName(\"TelnetAppender-\" + getName() + \"-\" + port);\n }\n\n }\n}\n", "file_name": "TelnetAppender.java", "human_label": "Send a message to each of the connections in telnet-friendly output. ", "level": "class_runnable", "lineno": "175", "name": "send", "oracle_context": "{ \"apis\" : \"[iterator, hasNext, next, print, checkError, remove]\", \"classes\" : \"[Iterator, PrintWriter]\", \"vars\" : \"[connections, writers]\" }", "package": "org.apache.log4j.net", "project": "logging-log4j1-main" }, { "_id": "6367670a1a6d9265ec0179e8", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static Boolean[] nullToEmpty(final Boolean[] array){\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n}\n", "docstring": "/** \n *

Defensive programming technique to change a null reference to an empty one.

This method returns an empty array for a null input array.

As a memory optimizing technique an empty array passed in will be overridden with the empty public static references in this class.

\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n", "end_lineno": "677", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

\n *\n *

This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

\n *\n *

#ThreadSafe#

\n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

\n *\n *

This method can be used to initialize:

\n *
\n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
\n *\n *

This method returns null for a null input array.

\n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

Shallow clones an array returning a typecast result and handling\n * null.

\n *\n *

The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

Produces a new array containing the elements between\n * the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n *

The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

\n *\n *
\n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new long array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new int array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new short array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new char array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new byte array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new double array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new float array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new boolean array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

Any multi-dimensional aspects of the arrays are ignored.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

\n *\n *

If the input array is null, 0 is returned.

\n *\n *
\n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
\n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

\n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

Reverses the order of the given array.

\n *\n *

There is no special handling for multi-dimensional arrays.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given object in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

Finds the index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given object within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the object is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

\n *\n *

The method returns false if a null array\n * is passed in.

\n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Characters to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Character to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive chars to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Longs to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Long to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive longs to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Integers to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Integer to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive ints to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Shorts to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Short to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive shorts to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Bytes to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Bytes to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive bytes to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Doubles to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Doubles to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive doubles to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Floats to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Floats to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive floats to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Booleans to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Booleans to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive booleans to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive longs is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive ints is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive chars is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive floats is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive longs is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive ints is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive chars is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive floats is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

\n *\n *
\n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Return an EMPTY_BOOLEAN_OBJECT_ARRAY array for a null or empty input array.", "level": "self_contained", "lineno": "659", "name": "nullToEmpty", "oracle_context": "{ \"apis\" : \"[ArrayUtils]\", \"classes\" : \"[ArrayUtils]\", \"vars\" : \"[length, EMPTY_BOOLEAN_OBJECT_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "6367677f1a6d9265ec01834b", "all_context": "{ \"class_level\" : \"import org.apache.log4j.spi.LoggingEvent;\\nLoggingEvent[] buf;\\nint numElements;\\nint first;\\nint next;\\nint maxSize;\\nBoundedFIFO(int maxSize);\\nget();\\ngetMaxSize();\\nisFull();\\nlength();\\nmin(int a,int b);\\nresize(int newSize);\\nwasEmpty();\\nwasFull();\\n\", \"repo_level\" : \"public interface LoggingEvent {public LocationInfo getLocationInformation();\\npublic Level getLevel();\\npublic String getLoggerName();\\npublic Category getLogger();\\npublic Object getMessage();\\npublic String getNDC();\\npublic Object getMDC(String key);\\npublic void getMDCCopy();\\npublic String getRenderedMessage();\\nstatic long getStartTime();\\npublic String getThreadName();\\npublic ThrowableInformation getThrowableInformation();\\npublic String[] getThrowableStrRep();\\nfinal void setProperty(String propName,String propValue);\\nfinal String getProperty(String key);\\nfinal boolean locationInformationExists();\\nfinal long getTimeStamp();\\npublic Set getPropertyKeySet();\\npublic Map getProperties();\\npublic String getFQNOfLoggerClass();\\npublic Object removeProperty(String propName);\\n }\\n\" }", "class_name": "BoundedFIFO", "code": "public void put(LoggingEvent o){\n if (numElements != maxSize) {\n buf[next]=o;\n if (++next == maxSize) {\n next=0;\n }\n numElements++;\n }\n}\n", "docstring": "/** \n * Place a {@link LoggingEvent} in the buffer. If the buffer is fullthen the event is silently dropped. It is the caller's responsability to make sure that the buffer has free space. \n */\n", "end_lineno": "83", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Contributors: Mathias Bogaert\n// joelr@viair.com\n\npackage org.apache.log4j.helpers;\n\nimport org.apache.log4j.spi.LoggingEvent;\n\n/**\n BoundedFIFO serves as the bounded first-in-first-out\n buffer heavily used by the {@link org.apache.log4j.AsyncAppender}.\n \n @author Ceki Gülcü \n @since version 0.9.1 */\npublic class BoundedFIFO {\n \n LoggingEvent[] buf;\n int numElements = 0;\n int first = 0;\n int next = 0;\n int maxSize;\n\n /**\n Instantiate a new BoundedFIFO with a maximum size passed as argument.\n */\n public\n BoundedFIFO(int maxSize) {\n if(maxSize < 1) {\n throw new IllegalArgumentException(\"The maxSize argument (\"+maxSize+\n\t\t\t \") is not a positive integer.\");\n }\n this.maxSize = maxSize;\n buf = new LoggingEvent[maxSize];\n }\n \n /**\n Get the first element in the buffer. Returns null if\n there are no elements in the buffer. */\n public\n LoggingEvent get() {\n if(numElements == 0) \n return null;\n \n LoggingEvent r = buf[first];\n buf[first] = null; // help garbage collection\n\n if(++first == maxSize) {\n\tfirst = 0;\n }\n numElements--; \n return r; \n }\n\n /**\n Place a {@link LoggingEvent} in the buffer. If the buffer is full\n then the event is silently dropped. It is the caller's\n responsability to make sure that the buffer has free space. */\n public \n void put(LoggingEvent o) {\n if(numElements != maxSize) { \n buf[next] = o; \n if(++next == maxSize) {\n\tnext = 0;\n }\n numElements++;\n }\n }\n\n /**\n Get the maximum size of the buffer.\n */\n public \n int getMaxSize() {\n return maxSize;\n }\n\n /**\n Return true if the buffer is full, that is, whether\n the number of elements in the buffer equals the buffer size. */\n public \n boolean isFull() {\n return numElements == maxSize;\n }\n\n /**\n Get the number of elements in the buffer. This number is\n guaranteed to be in the range 0 to maxSize\n (inclusive).\n */\n public\n int length() {\n return numElements;\n } \n\n\n int min(int a, int b) {\n return a < b ? a : b;\n }\n\n\n /**\n Resize the buffer to a new size. If the new size is smaller than\n the old size events might be lost.\n \n @since 1.1\n */\n synchronized\n public \n void resize(int newSize) {\n if(newSize == maxSize) \n return;\n\n\n LoggingEvent[] tmp = new LoggingEvent[newSize];\n\n // we should not copy beyond the buf array\n int len1 = maxSize - first;\n\n // we should not copy beyond the tmp array\n len1 = min(len1, newSize);\n\n // er.. how much do we actually need to copy?\n // We should not copy more than the actual number of elements.\n len1 = min(len1, numElements);\n\n // Copy from buf starting a first, to tmp, starting at position 0, len1 elements.\n System.arraycopy(buf, first, tmp, 0, len1);\n \n // Are there any uncopied elements and is there still space in the new array?\n int len2 = 0;\n if((len1 < numElements) && (len1 < newSize)) {\n len2 = numElements - len1;\n len2 = min(len2, newSize - len1);\n System.arraycopy(buf, 0, tmp, len1, len2);\n }\n \n this.buf = tmp;\n this.maxSize = newSize; \n this.first=0; \n this.numElements = len1+len2;\n this.next = this.numElements;\n if(this.next == this.maxSize) // this should never happen, but again, it just might.\n this.next = 0;\n }\n\n \n /**\n Returns true if there is just one element in the\n buffer. In other words, if there were no elements before the last\n {@link #put} operation completed. */\n public\n boolean wasEmpty() {\n return numElements == 1;\n }\n\n /**\n Returns true if the number of elements in the\n buffer plus 1 equals the maximum buffer size, returns\n false otherwise. */\n public\n boolean wasFull() {\n return (numElements+1 == maxSize);\n }\n\n}\n", "file_name": "BoundedFIFO.java", "human_label": "Place a LoggingEvent in the buffer buf.", "level": "class_runnable", "lineno": "70", "name": "put", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[numElements, maxSize, buf, next]\" }", "package": "org.apache.log4j.helpers", "project": "logging-log4j1-main" }, { "_id": "636767df1a6d9265ec018744", "all_context": "{ \"class_level\" : \"import lombok.Getter;\\nimport lombok.RequiredArgsConstructor;\\nimport lombok.extern.slf4j.Slf4j;\\nimport org.apache.skywalking.oap.server.core.profiling.ebpf.storage.EBPFProfilingDataRecord;\\nimport org.apache.skywalking.oap.server.core.query.type.EBPFProfilingAnalyzation;\\nimport org.apache.skywalking.oap.server.core.query.type.EBPFProfilingAnalyzeAggregateType;\\nimport org.apache.skywalking.oap.server.core.query.type.EBPFProfilingAnalyzeTimeRange;\\nimport org.apache.skywalking.oap.server.core.query.type.EBPFProfilingTree;\\nimport org.apache.skywalking.oap.server.core.storage.StorageModule;\\nimport org.apache.skywalking.oap.server.core.storage.profiling.ebpf.IEBPFProfilingDataDAO;\\nimport org.apache.skywalking.oap.server.library.module.ModuleManager;\\nimport org.apache.skywalking.oap.server.library.util.CollectionUtils;\\nimport java.io.IOException;\\nimport java.util.ArrayList;\\nimport java.util.Collection;\\nimport java.util.Collections;\\nimport java.util.List;\\nimport java.util.Objects;\\nimport java.util.concurrent.ExecutorService;\\nimport java.util.concurrent.Executors;\\nimport java.util.concurrent.TimeUnit;\\nimport java.util.stream.Collectors;\\nimport java.util.stream.Stream;\\nEBPFProfilingAnalyzeCollector ANALYZE_COLLECTOR;\\nLong FETCH_DATA_DURATION;\\nModuleManager moduleManager;\\nIEBPFProfilingDataDAO dataDAO;\\nlong maxQueryTimeoutInSecond;\\nExecutorService fetchDataThreadPool;\\nlong minTime;\\nlong maxTime;\\nEBPFProfilingAnalyzer(ModuleManager moduleManager,int maxDurationOfQuery,int fetchDataThreadPoolSize);\\ngenerateTrees(EBPFProfilingAnalyzation analyzation,Stream stackStream);\\nbuildTimeRanges(List timeRanges);\\nbuildTimeRanges(long start,long end);\\ngetDataDAO();\\nanalyze(List scheduleIdList,List ranges,EBPFProfilingAnalyzeAggregateType aggregateType);\\n\", \"repo_level\" : \"public interface EBPFProfilingDataRecord {public String id();\\npublic EBPFProfilingDataRecord storage2Entity(Convert2Entity converter);\\npublic void entity2Storage(EBPFProfilingDataRecord storageData,Convert2Storage converter);\\n }\\npublic interface EBPFProfilingAnalyzation { }\\npublic interface EBPFProfilingAnalyzeTimeRange { }\\npublic interface EBPFProfilingTree { }\\npublic interface StorageModule {public Class[] services();\\n }\\npublic interface IEBPFProfilingDataDAO { List queryData(List scheduleIdList,long beginTime,long endTime);\\n }\\npublic interface ModuleManager {public void init(ApplicationConfiguration applicationConfiguration);\\npublic boolean has(String moduleName);\\npublic ModuleProviderHolder find(String moduleName);\\n }\\npublic interface CollectionUtils {static boolean isEmpty(Map map);\\nstatic boolean isEmpty(List list);\\nstatic boolean isEmpty(Set set);\\nstatic boolean isNotEmpty(List list);\\nstatic boolean isNotEmpty(Set set);\\nstatic boolean isNotEmpty(Map map);\\nstatic boolean isNotEmpty(T[] array);\\nstatic boolean isEmpty(byte[] array);\\nstatic boolean isNotEmpty(byte[] array);\\n }\\n\" }", "class_name": "EBPFProfilingAnalyzer", "code": "protected List buildTimeRanges(long start,long end){\n if (start >= end) {\n return null;\n }\n end+=1;\n final List timeRanges=new ArrayList<>();\n do {\n long batchEnd=Math.min(start + FETCH_DATA_DURATION,end);\n timeRanges.add(new TimeRange(start,batchEnd));\n start=batchEnd;\n }\n while (start < end);\n return timeRanges;\n}\n", "docstring": "/** \n * Split time ranges to insure the start time and end time is small then {@link #FETCH_DATA_DURATION}\n */\n", "end_lineno": "138", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.core.profiling.ebpf.analyze;\n\nimport lombok.Getter;\nimport lombok.RequiredArgsConstructor;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.skywalking.oap.server.core.profiling.ebpf.storage.EBPFProfilingDataRecord;\nimport org.apache.skywalking.oap.server.core.query.type.EBPFProfilingAnalyzation;\nimport org.apache.skywalking.oap.server.core.query.type.EBPFProfilingAnalyzeAggregateType;\nimport org.apache.skywalking.oap.server.core.query.type.EBPFProfilingAnalyzeTimeRange;\nimport org.apache.skywalking.oap.server.core.query.type.EBPFProfilingTree;\nimport org.apache.skywalking.oap.server.core.storage.StorageModule;\nimport org.apache.skywalking.oap.server.core.storage.profiling.ebpf.IEBPFProfilingDataDAO;\nimport org.apache.skywalking.oap.server.library.module.ModuleManager;\nimport org.apache.skywalking.oap.server.library.util.CollectionUtils;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\n/**\n * eBPF Profiling Analyzer working on data query and combine them for generate the Flame Graph.\n */\n@Slf4j\npublic class EBPFProfilingAnalyzer {\n\n private static final EBPFProfilingAnalyzeCollector ANALYZE_COLLECTOR = new EBPFProfilingAnalyzeCollector();\n private static final Long FETCH_DATA_DURATION = TimeUnit.SECONDS.toMillis(10);\n\n private final ModuleManager moduleManager;\n protected IEBPFProfilingDataDAO dataDAO;\n private long maxQueryTimeoutInSecond;\n private final ExecutorService fetchDataThreadPool;\n\n public EBPFProfilingAnalyzer(ModuleManager moduleManager, int maxDurationOfQuery, int fetchDataThreadPoolSize) {\n this.moduleManager = moduleManager;\n this.maxQueryTimeoutInSecond = maxDurationOfQuery;\n this.fetchDataThreadPool = Executors.newFixedThreadPool(fetchDataThreadPoolSize);\n }\n\n /**\n * search data and analyze\n */\n public EBPFProfilingAnalyzation analyze(List scheduleIdList,\n List ranges,\n EBPFProfilingAnalyzeAggregateType aggregateType) throws IOException {\n EBPFProfilingAnalyzation analyzation = new EBPFProfilingAnalyzation();\n\n // query data\n long queryDataMaxTimestamp = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(maxQueryTimeoutInSecond);\n final Stream stackStream = buildTimeRanges(ranges).parallelStream().map(r -> {\n try {\n return fetchDataThreadPool.submit(() -> getDataDAO().queryData(scheduleIdList, r.getMinTime(), r.getMaxTime()))\n .get(queryDataMaxTimestamp - System.currentTimeMillis(), TimeUnit.MILLISECONDS);\n } catch (Exception e) {\n log.warn(e.getMessage(), e);\n return Collections.emptyList();\n }\n }).flatMap(Collection::stream).map(e -> {\n try {\n return EBPFProfilingStack.deserialize(e, aggregateType);\n } catch (Exception ex) {\n log.warn(\"could not deserialize the stack\", ex);\n return null;\n }\n }).filter(Objects::nonNull).distinct();\n\n // analyze tree\n generateTrees(analyzation, stackStream);\n\n return analyzation;\n }\n\n public void generateTrees(EBPFProfilingAnalyzation analyzation, Stream stackStream) {\n Collection stackTrees = stackStream\n // stack list cannot be empty\n .filter(s -> CollectionUtils.isNotEmpty(s.getSymbols()))\n // analyze the symbol and combine as trees\n .collect(Collectors.groupingBy(s -> s.getSymbols()\n .get(0), ANALYZE_COLLECTOR)).values();\n\n analyzation.getTrees().addAll(stackTrees);\n }\n\n protected List buildTimeRanges(List timeRanges) {\n return timeRanges.parallelStream()\n .map(r -> buildTimeRanges(r.getStart(), r.getEnd()))\n .filter(Objects::nonNull)\n .flatMap(Collection::stream)\n .collect(Collectors.toList());\n }\n\n /**\n * Split time ranges to insure the start time and end time is small then {@link #FETCH_DATA_DURATION}\n */\n protected List buildTimeRanges(long start, long end) {\n if (start >= end) {\n return null;\n }\n\n // include latest millisecond\n end += 1;\n\n final List timeRanges = new ArrayList<>();\n do {\n long batchEnd = Math.min(start + FETCH_DATA_DURATION, end);\n timeRanges.add(new TimeRange(start, batchEnd));\n start = batchEnd;\n }\n while (start < end);\n\n return timeRanges;\n }\n\n protected IEBPFProfilingDataDAO getDataDAO() {\n if (dataDAO == null) {\n dataDAO = moduleManager.find(StorageModule.NAME)\n .provider()\n .getService(IEBPFProfilingDataDAO.class);\n }\n return dataDAO;\n }\n\n /**\n * Split the query time with {@link #FETCH_DATA_DURATION}\n */\n @Getter\n @RequiredArgsConstructor\n private static class TimeRange {\n private final long minTime;\n private final long maxTime;\n }\n}", "file_name": "EBPFProfilingAnalyzer.java", "human_label": "Split time ranges to insure the start time and end time is small than FETCH_DATA_DURATION.", "level": "self_contained", "lineno": "118", "name": "buildTimeRanges", "oracle_context": "{ \"apis\" : \"[min, add]\", \"classes\" : \"[List]\", \"vars\" : \"[FETCH_DATA_DURATION]\" }", "package": "org.apache.skywalking.oap.server.core.profiling.ebpf.analyze", "project": "skywalking-master" }, { "_id": "636767031a6d9265ec0178e6", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static byte[] toPrimitive(final Byte[] array){\n if (array == null) {\n return null;\n }\n else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result=new byte[array.length];\n for (int i=0; i < array.length; i++) {\n result[i]=array[i].byteValue();\n }\n return result;\n}\n", "docstring": "/** \n *

Converts an array of object Bytes to primitives.

This method returns null for a null input array.

\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n", "end_lineno": "2804", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

\n *\n *

This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

\n *\n *

#ThreadSafe#

\n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

\n *\n *

This method can be used to initialize:

\n *
\n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
\n *\n *

This method returns null for a null input array.

\n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

Shallow clones an array returning a typecast result and handling\n * null.

\n *\n *

The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

Produces a new array containing the elements between\n * the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n *

The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

\n *\n *
\n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new long array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new int array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new short array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new char array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new byte array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new double array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new float array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new boolean array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

Any multi-dimensional aspects of the arrays are ignored.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

\n *\n *

If the input array is null, 0 is returned.

\n *\n *
\n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
\n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

\n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

Reverses the order of the given array.

\n *\n *

There is no special handling for multi-dimensional arrays.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given object in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

Finds the index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given object within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the object is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

\n *\n *

The method returns false if a null array\n * is passed in.

\n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Characters to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Character to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive chars to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Longs to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Long to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive longs to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Integers to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Integer to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive ints to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Shorts to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Short to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive shorts to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Bytes to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Bytes to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive bytes to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Doubles to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Doubles to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive doubles to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Floats to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Floats to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive floats to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Booleans to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Booleans to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive booleans to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive longs is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive ints is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive chars is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive floats is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive longs is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive ints is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive chars is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive floats is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

\n *\n *
\n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Convert an array of object Bytes to primitives, return null for a null input array.", "level": "self_contained", "lineno": "2784", "name": "toPrimitive", "oracle_context": "{ \"apis\" : \"[byteValue, ArrayUtils]\", \"classes\" : \"[byte[], ArrayUtils]\", \"vars\" : \"[length, EMPTY_BYTE_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636767dc1a6d9265ec0186be", "all_context": "{ \"class_level\" : \"import java.util.ArrayList;\\nimport java.util.List;\\nimport lombok.Setter;\\nimport org.apache.skywalking.oap.server.core.Const;\\nimport org.apache.skywalking.oap.server.core.UnexpectedException;\\nimport org.apache.skywalking.oap.server.core.analysis.DownSampling;\\nimport org.apache.skywalking.oap.server.core.analysis.TimeBucket;\\nimport org.apache.skywalking.oap.server.core.query.enumeration.Step;\\nimport org.apache.skywalking.oap.server.core.storage.model.Model;\\nimport org.apache.skywalking.oap.server.library.util.StringUtil;\\nimport org.joda.time.DateTime;\\nimport org.joda.time.Days;\\nimport org.joda.time.format.DateTimeFormat;\\nimport org.joda.time.format.DateTimeFormatter;\\nDateTimeFormatter TIME_BUCKET_FORMATTER;\\nDateTime DAY_ONE;\\nint DAY_STEP;\\nint SUPER_DATASET_DAY_STEP;\\nlatestWriteIndexName(Model model);\\nqueryIndexName(String tableName,long pointOfTB,Step step,boolean isRecord,boolean isSuperDataSet);\\nwriteIndexName(Model model,long timeBucket);\\nisolateTimeFromIndexName(String indexName);\\ncompressTimeBucket(long timeBucket,int dayStep);\\ncompressDateTime(DateTime time,int dayStep);\\nsuperDatasetIndexNames(String indexName,long startSecondTB,long endSecondTB);\\n\", \"repo_level\" : \"public interface Const { }\\npublic interface UnexpectedException { }\\npublic interface TimeBucket {static long getRecordTimeBucket(long time);\\nstatic long getMinuteTimeBucket(long time);\\nstatic long getTimestamp(long timeBucket);\\nstatic boolean isSecondBucket(long timeBucket);\\nstatic boolean isMinuteBucket(long timeBucket);\\nstatic boolean isHourBucket(long timeBucket);\\nstatic boolean isDayBucket(long timeBucket);\\nstatic long getTimestamp(long timeBucket,DownSampling downsampling);\\nstatic long getTimeBucket(long timestamp,DownSampling downsampling);\\n }\\npublic interface Model { }\\npublic interface StringUtil {static boolean isEmpty(String str);\\nstatic boolean isNotEmpty(String str);\\nstatic boolean isBlank(String str);\\nstatic boolean isNotBlank(String str);\\nstatic void setIfPresent(String value,Consumer setter);\\nstatic String join(char delimiter,String strings);\\nstatic boolean substringMatch(CharSequence str,int index,CharSequence substring);\\nstatic String cut(String str,int threshold);\\nstatic String trim(String str,char ch);\\n }\\n\" }", "class_name": "TimeSeriesUtils", "code": "static long compressTimeBucket(long timeBucket,int dayStep){\n if (dayStep > 1) {\n DateTime time=TIME_BUCKET_FORMATTER.parseDateTime(\"\" + timeBucket);\n int days=Days.daysBetween(DAY_ONE,time).getDays();\n int groupBucketOffset=days % dayStep;\n return Long.parseLong(time.minusDays(groupBucketOffset).toString(TIME_BUCKET_FORMATTER));\n }\n else {\n return timeBucket;\n }\n}\n", "docstring": "/** \n * Follow the dayStep to re-format the time bucket literal long value. Such as, in dayStep == 11, 20000105 re-formatted time bucket is 20000101, 20000115 re-formatted time bucket is 20000112, 20000123 re-formatted time bucket is 20000123\n */\n", "end_lineno": "163", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport lombok.Setter;\nimport org.apache.skywalking.oap.server.core.Const;\nimport org.apache.skywalking.oap.server.core.UnexpectedException;\nimport org.apache.skywalking.oap.server.core.analysis.DownSampling;\nimport org.apache.skywalking.oap.server.core.analysis.TimeBucket;\nimport org.apache.skywalking.oap.server.core.query.enumeration.Step;\nimport org.apache.skywalking.oap.server.core.storage.model.Model;\nimport org.apache.skywalking.oap.server.library.util.StringUtil;\nimport org.joda.time.DateTime;\nimport org.joda.time.Days;\nimport org.joda.time.format.DateTimeFormat;\nimport org.joda.time.format.DateTimeFormatter;\n\n/**\n * TimeSeriesUtils sets up and splits the time suffix of index name.\n */\npublic class TimeSeriesUtils {\n private static DateTimeFormatter TIME_BUCKET_FORMATTER = DateTimeFormat.forPattern(\"yyyyMMdd\");\n /**\n * We are far from the first day of 2000, so we set it as the day one to make sure the index based on {@link\n * #DAY_STEP} is consistently no matter whenever the OAP starts up.\n */\n private static final DateTime DAY_ONE = TIME_BUCKET_FORMATTER.parseDateTime(\"20000101\");\n @Setter\n private static int DAY_STEP = 1;\n @Setter\n private static int SUPER_DATASET_DAY_STEP = 1;\n\n /**\n * @return formatted latest index name, based on current timestamp.\n */\n public static String latestWriteIndexName(Model model) {\n String tableName = IndexController.INSTANCE.getTableName(model);\n long dayTimeBucket = TimeBucket.getTimeBucket(System.currentTimeMillis(), DownSampling.Day);\n if (model.isRecord() && model.isSuperDataset()) {\n return tableName + Const.LINE + compressTimeBucket(dayTimeBucket, SUPER_DATASET_DAY_STEP);\n }\n return tableName + Const.LINE + compressTimeBucket(dayTimeBucket, DAY_STEP);\n }\n\n /**\n * @return Concrete index name for super dataset index\n */\n public static String[] superDatasetIndexNames(String indexName, long startSecondTB, long endSecondTB) {\n if (startSecondTB == 0 || endSecondTB == 0) {\n return new String[] {indexName};\n }\n DateTime startDateTime = TIME_BUCKET_FORMATTER.parseDateTime(startSecondTB / 1000000 + \"\");\n DateTime endDateTime = TIME_BUCKET_FORMATTER.parseDateTime(endSecondTB / 1000000 + \"\");\n List timeRanges = new ArrayList<>(16);\n for (int i = 0; i <= Days.daysBetween(startDateTime, endDateTime).getDays(); i++) {\n timeRanges.add(startDateTime.plusDays(i));\n }\n if (timeRanges.isEmpty()) {\n return new String[] {indexName};\n } else {\n return timeRanges.stream()\n .map(item -> indexName + Const.LINE + compressDateTime(item, SUPER_DATASET_DAY_STEP))\n .distinct()\n .toArray(String[]::new);\n }\n }\n\n public static String queryIndexName(String tableName,\n long pointOfTB,\n Step step,\n boolean isRecord,\n boolean isSuperDataSet) {\n if (StringUtil.isBlank(tableName) || pointOfTB <= 0) {\n throw new IllegalArgumentException(\n \"Arguments [tableName]: \" + tableName + \" can not be blank and [pointOfTB]: \" + pointOfTB + \" can not <= 0\");\n }\n if (isRecord && isSuperDataSet) {\n return tableName + Const.LINE + compressTimeBucket(pointOfTB / 1000000, SUPER_DATASET_DAY_STEP);\n }\n switch (step) {\n case DAY:\n return tableName + Const.LINE + compressTimeBucket(pointOfTB, DAY_STEP);\n case HOUR:\n return tableName + Const.LINE + compressTimeBucket(pointOfTB / 100, DAY_STEP);\n case MINUTE:\n return tableName + Const.LINE + compressTimeBucket(pointOfTB / 10000, DAY_STEP);\n case SECOND:\n return tableName + Const.LINE + compressTimeBucket(pointOfTB / 1000000, DAY_STEP);\n }\n\n throw new UnexpectedException(\"Failed to get the index name from tableName:\" + tableName + \", pointOfTB:\" + pointOfTB + \", step:\" + step.name());\n }\n\n /**\n * @return index name based on model definition and given time bucket.\n */\n static String writeIndexName(Model model, long timeBucket) {\n String tableName = IndexController.INSTANCE.getTableName(model);\n if (model.isRecord() && model.isSuperDataset()) {\n return tableName + Const.LINE + compressTimeBucket(timeBucket / 1000000, SUPER_DATASET_DAY_STEP);\n } else {\n switch (model.getDownsampling()) {\n case None:\n return tableName;\n case Hour:\n return tableName + Const.LINE + compressTimeBucket(timeBucket / 100, DAY_STEP);\n case Minute:\n return tableName + Const.LINE + compressTimeBucket(timeBucket / 10000, DAY_STEP);\n case Day:\n return tableName + Const.LINE + compressTimeBucket(timeBucket, DAY_STEP);\n case Second:\n return tableName + Const.LINE + compressTimeBucket(timeBucket / 1000000, DAY_STEP);\n default:\n throw new UnexpectedException(\"Unexpected down sampling value, \" + model.getDownsampling());\n }\n }\n }\n\n /**\n * @return the index represented time, which is included in the index name.\n */\n static long isolateTimeFromIndexName(String indexName) {\n return Long.parseLong(indexName.substring(indexName.lastIndexOf(Const.LINE) + 1));\n }\n\n /**\n * Follow the dayStep to re-format the time bucket literal long value.\n *\n * Such as, in dayStep == 11,\n *\n * 20000105 re-formatted time bucket is 20000101, 20000115 re-formatted time bucket is 20000112, 20000123\n * re-formatted time bucket is 20000123\n */\n static long compressTimeBucket(long timeBucket, int dayStep) {\n if (dayStep > 1) {\n DateTime time = TIME_BUCKET_FORMATTER.parseDateTime(\"\" + timeBucket);\n int days = Days.daysBetween(DAY_ONE, time).getDays();\n int groupBucketOffset = days % dayStep;\n return Long.parseLong(time.minusDays(groupBucketOffset).toString(TIME_BUCKET_FORMATTER));\n } else {\n /*\n * No calculation required. dayStep is for lower traffic. For normally configuration, there is pointless to calculate.\n */\n return timeBucket;\n }\n }\n\n static long compressDateTime(DateTime time, int dayStep) {\n if (dayStep > 1) {\n int days = Days.daysBetween(DAY_ONE, time).getDays();\n int groupBucketOffset = days % dayStep;\n return Long.parseLong(time.minusDays(groupBucketOffset).toString(TIME_BUCKET_FORMATTER));\n } else {\n /**\n * No calculation required. dayStep is for lower traffic. For normally configuration, there is pointless to calculate.\n */\n return Long.parseLong(time.toString(TIME_BUCKET_FORMATTER));\n }\n }\n\n}\n", "file_name": "TimeSeriesUtils.java", "human_label": "Follow the dayStep to reformat the time bucket with TIME_BUCKET_FORMATTER. For example, if dayStep == 11, 20000105 re-formatted time bucket is 20000101, 20000115 re-formatted time bucket is 20000112, 20000123 re-formatted time bucket is 20000123.", "level": "project_runnable", "lineno": "143", "name": "compressTimeBucket", "oracle_context": "{ \"apis\" : \"[parseDateTime, getDays, daysBetween, parseLong, toString, minusDays]\", \"classes\" : \"[DateTime]\", \"vars\" : \"[TIME_BUCKET_FORMATTER, DAY_ONE]\" }", "package": "org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base", "project": "skywalking-master" }, { "_id": "636767a41a6d9265ec01856c", "all_context": "{ \"class_level\" : \"import java.io.UTFDataFormatException;\\nimport java.io.UnsupportedEncodingException;\\nimport static java.lang.Character.MIN_HIGH_SURROGATE;\\nimport static java.lang.Character.MIN_LOW_SURROGATE;\\nimport static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT;\\nint[] sizeTable;\\nchar[] DigitTens;\\nchar[] DigitOnes;\\nchar[] digits;\\nbyte[] INT_MIN_VALUE;\\nbyte[] LONG_MIN_VALUE;\\nint TWO_BYTE_LOWER_LIMIT;\\nint ONE_BYTE_EXCLUSIVE;\\nint THREE_BYTE_LOWER_LIMIT;\\nint TWO_BYTE_EXCLUSIVE;\\nint FOUR_BYTE_LOWER_LIMIT;\\nint THREE_BYTE_EXCLUSIVE;\\nint FIVE_BYTE_LOWER_LIMIT;\\nint FOUR_BYTE_EXCLUSIVE;\\nboolean CESU8_COMPAT;\\nStringSerializer();\\nputBytesFromInt(int i,int offset,int size,byte[] buf);\\nputBytesFromLong(long i,int offset,int size,byte[] buf);\\nstringSize(int x);\\nstringSize(long x);\\nwriteLong(long value,WriteSession session,LinkedBuffer lb);\\nwriteFloat(float value,WriteSession session,LinkedBuffer lb);\\nwriteDouble(double value,WriteSession session,LinkedBuffer lb);\\ncomputeUTF8Size(CharSequence str,int index,int len);\\nwriteUTF8(CharSequence str,int i,int len,byte[] buffer,int offset,int limit,WriteSession session,LinkedBuffer lb);\\nwriteUTF8(CharSequence str,int i,int len,WriteSession session,LinkedBuffer lb);\\nwriteUTF8(CharSequence str,WriteSession session,LinkedBuffer lb);\\nwriteAscii(CharSequence str,WriteSession session,LinkedBuffer lb);\\nwriteFixed2ByteInt(int value,byte[] buffer,int offset,boolean littleEndian);\\nwriteUTF8FixedDelimited(CharSequence str,WriteSession session,LinkedBuffer lb);\\nwriteUTF8FixedDelimited(CharSequence str,boolean littleEndian,WriteSession session,LinkedBuffer lb);\\nwriteUTF8OneByteDelimited(CharSequence str,int index,int len,WriteSession session,LinkedBuffer lb);\\nwriteUTF8VarDelimited(CharSequence str,int index,int len,int lowerLimit,int expectedSize,WriteSession session,LinkedBuffer lb);\\nwriteUTF8VarDelimited(CharSequence str,WriteSession session,LinkedBuffer lb);\\nSTRING();\\ndeser(byte[] nonNullValue);\\ndeser(byte[] nonNullValue,int offset,int len);\\ndeserCustomOnly(byte[] nonNullValue);\\nser(String nonNullValue);\\nreadUTF(byte[] buffer,int offset,int len);\\nhighSurrogate(int codePoint);\\nlowSurrogate(int codePoint);\\nwriteInt(int value,WriteSession session,LinkedBuffer lb);\\n\", \"repo_level\" : \"\" }", "class_name": "StringSerializer", "code": "public static int computeUTF8Size(final CharSequence str,final int index,final int len){\n int size=len;\n for (int i=index; i < len; i++) {\n final char c=str.charAt(i);\n if (c < 0x0080) continue;\n if (c < 0x0800) size++;\n else size+=2;\n }\n return size;\n}\n", "docstring": "/** \n * Computes the size of the utf8 string beginning at the specified {@code index} with the specified {@code length}.\n */\n", "end_lineno": "335", "file_content": "package io.protostuff;\r\n\r\nimport java.io.UTFDataFormatException;\r\nimport java.io.UnsupportedEncodingException;\r\n\r\nimport static java.lang.Character.MIN_HIGH_SURROGATE;\r\nimport static java.lang.Character.MIN_LOW_SURROGATE;\r\nimport static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT;\r\n\r\n/**\r\n * UTF-8 String serialization\r\n *\r\n * @author David Yu\r\n * @created Feb 4, 2010\r\n */\r\npublic final class StringSerializer\r\n{\r\n\r\n private StringSerializer()\r\n {\r\n }\r\n\r\n /**\r\n * From {@link java.lang.Integer#toString(int)}\r\n */\r\n static final int[] sizeTable = new int[] {\r\n 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE\r\n };\r\n\r\n static final char[] DigitTens = {\r\n '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',\r\n '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',\r\n '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',\r\n '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',\r\n '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',\r\n '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',\r\n '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',\r\n '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',\r\n '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',\r\n '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',\r\n };\r\n\r\n static final char[] DigitOnes = {\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n };\r\n\r\n static final char[] digits = {\r\n '0', '1', '2', '3', '4', '5',\r\n '6', '7', '8', '9', 'a', 'b',\r\n 'c', 'd', 'e', 'f', 'g', 'h',\r\n 'i', 'j', 'k', 'l', 'm', 'n',\r\n 'o', 'p', 'q', 'r', 's', 't',\r\n 'u', 'v', 'w', 'x', 'y', 'z'\r\n };\r\n\r\n static final byte[] INT_MIN_VALUE = new byte[] {\r\n (byte) '-',\r\n (byte) '2',\r\n (byte) '1', (byte) '4', (byte) '7',\r\n (byte) '4', (byte) '8', (byte) '3',\r\n (byte) '6', (byte) '4', (byte) '8'\r\n };\r\n\r\n static final byte[] LONG_MIN_VALUE = new byte[] {\r\n (byte) '-',\r\n (byte) '9',\r\n (byte) '2', (byte) '2', (byte) '3',\r\n (byte) '3', (byte) '7', (byte) '2',\r\n (byte) '0', (byte) '3', (byte) '6',\r\n (byte) '8', (byte) '5', (byte) '4',\r\n (byte) '7', (byte) '7', (byte) '5',\r\n (byte) '8', (byte) '0', (byte) '8'\r\n };\r\n\r\n static final int TWO_BYTE_LOWER_LIMIT = 1 << 7;\r\n\r\n static final int ONE_BYTE_EXCLUSIVE = TWO_BYTE_LOWER_LIMIT / 3 + 1;\r\n\r\n static final int THREE_BYTE_LOWER_LIMIT = 1 << 14;\r\n\r\n static final int TWO_BYTE_EXCLUSIVE = THREE_BYTE_LOWER_LIMIT / 3 + 1;\r\n\r\n static final int FOUR_BYTE_LOWER_LIMIT = 1 << 21;\r\n\r\n static final int THREE_BYTE_EXCLUSIVE = FOUR_BYTE_LOWER_LIMIT / 3 + 1;\r\n\r\n static final int FIVE_BYTE_LOWER_LIMIT = 1 << 28;\r\n\r\n static final int FOUR_BYTE_EXCLUSIVE = FIVE_BYTE_LOWER_LIMIT / 3 + 1;\r\n\r\n static void putBytesFromInt(int i, final int offset, final int size, final byte[] buf)\r\n {\r\n int q, r;\r\n int charPos = offset + size;\r\n char sign = 0;\r\n\r\n if (i < 0)\r\n {\r\n sign = '-';\r\n i = -i;\r\n }\r\n\r\n // Generate two digits per iteration\r\n while (i >= 65536)\r\n {\r\n q = i / 100;\r\n // really: r = i - (q * 100);\r\n r = i - ((q << 6) + (q << 5) + (q << 2));\r\n i = q;\r\n buf[--charPos] = (byte) DigitOnes[r];\r\n buf[--charPos] = (byte) DigitTens[r];\r\n }\r\n\r\n // Fall thru to fast mode for smaller numbers\r\n // assert(i <= 65536, i);\r\n for (;;)\r\n {\r\n q = (i * 52429) >>> (16 + 3);\r\n r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...\r\n buf[--charPos] = (byte) digits[r];\r\n i = q;\r\n if (i == 0)\r\n break;\r\n }\r\n if (sign != 0)\r\n {\r\n buf[--charPos] = (byte) sign;\r\n }\r\n }\r\n\r\n static void putBytesFromLong(long i, final int offset, int size, final byte[] buf)\r\n {\r\n long q;\r\n int r;\r\n int charPos = offset + size;\r\n char sign = 0;\r\n\r\n if (i < 0)\r\n {\r\n sign = '-';\r\n i = -i;\r\n }\r\n\r\n // Get 2 digits/iteration using longs until quotient fits into an int\r\n while (i > Integer.MAX_VALUE)\r\n {\r\n q = i / 100;\r\n // really: r = i - (q * 100);\r\n r = (int) (i - ((q << 6) + (q << 5) + (q << 2)));\r\n i = q;\r\n buf[--charPos] = (byte) DigitOnes[r];\r\n buf[--charPos] = (byte) DigitTens[r];\r\n }\r\n\r\n // Get 2 digits/iteration using ints\r\n int q2;\r\n int i2 = (int) i;\r\n while (i2 >= 65536)\r\n {\r\n q2 = i2 / 100;\r\n // really: r = i2 - (q * 100);\r\n r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));\r\n i2 = q2;\r\n buf[--charPos] = (byte) DigitOnes[r];\r\n buf[--charPos] = (byte) DigitTens[r];\r\n }\r\n\r\n // Fall thru to fast mode for smaller numbers\r\n // assert(i2 <= 65536, i2);\r\n for (;;)\r\n {\r\n q2 = (i2 * 52429) >>> (16 + 3);\r\n r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...\r\n buf[--charPos] = (byte) digits[r];\r\n i2 = q2;\r\n if (i2 == 0)\r\n break;\r\n }\r\n if (sign != 0)\r\n {\r\n buf[--charPos] = (byte) sign;\r\n }\r\n }\r\n\r\n // Requires positive x\r\n static int stringSize(int x)\r\n {\r\n for (int i = 0;; i++)\r\n {\r\n if (x <= sizeTable[i])\r\n return i + 1;\r\n }\r\n }\r\n\r\n // Requires positive x\r\n static int stringSize(long x)\r\n {\r\n long p = 10;\r\n for (int i = 1; i < 19; i++)\r\n {\r\n if (x < p)\r\n return i;\r\n p = 10 * p;\r\n }\r\n return 19;\r\n }\r\n\r\n /**\r\n * Writes the stringified int into the {@link LinkedBuffer}.\r\n */\r\n public static LinkedBuffer writeInt(final int value, final WriteSession session,\r\n LinkedBuffer lb)\r\n {\r\n if (value == Integer.MIN_VALUE)\r\n {\r\n final int valueLen = INT_MIN_VALUE.length;\r\n if (lb.offset + valueLen > lb.buffer.length)\r\n {\r\n // not enough size\r\n lb = new LinkedBuffer(session.nextBufferSize, lb);\r\n }\r\n\r\n System.arraycopy(INT_MIN_VALUE, 0, lb.buffer, lb.offset, valueLen);\r\n\r\n lb.offset += valueLen;\r\n session.size += valueLen;\r\n\r\n return lb;\r\n }\r\n\r\n final int size = (value < 0) ? stringSize(-value) + 1 : stringSize(value);\r\n\r\n if (lb.offset + size > lb.buffer.length)\r\n {\r\n // not enough size\r\n lb = new LinkedBuffer(session.nextBufferSize, lb);\r\n }\r\n\r\n putBytesFromInt(value, lb.offset, size, lb.buffer);\r\n\r\n lb.offset += size;\r\n session.size += size;\r\n\r\n return lb;\r\n }\r\n\r\n /**\r\n * Writes the stringified long into the {@link LinkedBuffer}.\r\n */\r\n public static LinkedBuffer writeLong(final long value, final WriteSession session,\r\n LinkedBuffer lb)\r\n {\r\n if (value == Long.MIN_VALUE)\r\n {\r\n final int valueLen = LONG_MIN_VALUE.length;\r\n if (lb.offset + valueLen > lb.buffer.length)\r\n {\r\n // TODO space efficiency (slower path)\r\n // not enough size\r\n lb = new LinkedBuffer(session.nextBufferSize, lb);\r\n }\r\n\r\n System.arraycopy(LONG_MIN_VALUE, 0, lb.buffer, lb.offset, valueLen);\r\n\r\n lb.offset += valueLen;\r\n session.size += valueLen;\r\n\r\n return lb;\r\n }\r\n\r\n final int size = (value < 0) ? stringSize(-value) + 1 : stringSize(value);\r\n\r\n if (lb.offset + size > lb.buffer.length)\r\n {\r\n // TODO space efficiency (slower path)\r\n // not enough size\r\n lb = new LinkedBuffer(session.nextBufferSize, lb);\r\n }\r\n\r\n putBytesFromLong(value, lb.offset, size, lb.buffer);\r\n\r\n lb.offset += size;\r\n session.size += size;\r\n\r\n return lb;\r\n }\r\n\r\n /**\r\n * Writes the stringified float into the {@link LinkedBuffer}. TODO - skip string conversion and write directly to\r\n * buffer\r\n */\r\n public static LinkedBuffer writeFloat(final float value, final WriteSession session,\r\n final LinkedBuffer lb)\r\n {\r\n return writeAscii(Float.toString(value), session, lb);\r\n }\r\n\r\n /**\r\n * Writes the stringified double into the {@link LinkedBuffer}. TODO - skip string conversion and write directly to\r\n * buffer\r\n */\r\n public static LinkedBuffer writeDouble(final double value, final WriteSession session,\r\n final LinkedBuffer lb)\r\n {\r\n return writeAscii(Double.toString(value), session, lb);\r\n }\r\n\r\n /**\r\n * Computes the size of the utf8 string beginning at the specified {@code index} with the specified {@code length}.\r\n */\r\n public static int computeUTF8Size(final CharSequence str, final int index, final int len)\r\n {\r\n int size = len;\r\n for (int i = index; i < len; i++)\r\n {\r\n final char c = str.charAt(i);\r\n if (c < 0x0080)\r\n continue;\r\n\r\n if (c < 0x0800)\r\n size++;\r\n else\r\n size += 2;\r\n }\r\n return size;\r\n }\r\n\r\n /**\r\n * Slow path. It checks the limit before every write. Shared with StreamedStringSerializer.\r\n */\r\n static LinkedBuffer writeUTF8(final CharSequence str, int i, final int len,\r\n byte[] buffer, int offset, int limit,\r\n final WriteSession session, LinkedBuffer lb)\r\n {\r\n for (char c = 0;; c = 0)\r\n {\r\n while (i != len && offset != limit && (c = str.charAt(i++)) < 0x0080)\r\n buffer[offset++] = (byte) c;\r\n\r\n if (i == len && c < 0x0080)\r\n {\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n return lb;\r\n }\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n\r\n continue;\r\n }\r\n\r\n if (c < 0x0800)\r\n {\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0xC0 | ((c >> 6) & 0x1F));\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0x80 | ((c >> 0) & 0x3F));\r\n }\r\n else if (Character.isHighSurrogate((char) c) && i < len && Character.isLowSurrogate((char) str.charAt(i)))\r\n {\r\n // We have a surrogate pair, so use the 4-byte encoding.\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n int codePoint = Character.toCodePoint((char) c, (char) str.charAt(i));\r\n\r\n buffer[offset++] = (byte) (0xF0 | ((codePoint >> 18) & 0x07));\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0x80 | ((codePoint >> 12) & 0x3F));\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0x80 | ((codePoint >> 6) & 0x3F));\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0x80 | ((codePoint >> 0) & 0x3F));\r\n\r\n i++;\r\n }\r\n else\r\n {\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0xE0 | ((c >> 12) & 0x0F));\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0x80 | ((c >> 6) & 0x3F));\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0x80 | ((c >> 0) & 0x3F));\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Fast path. The {@link LinkedBuffer}'s capacity is >= string length.\r\n */\r\n static LinkedBuffer writeUTF8(final CharSequence str, int i, final int len,\r\n final WriteSession session, final LinkedBuffer lb)\r\n {\r\n final byte[] buffer = lb.buffer;\r\n for (int c = 0, offset = lb.offset, adjustableLimit = offset + len;; c = 0)\r\n {\r\n while (i != len && (c = str.charAt(i++)) < 0x0080)\r\n buffer[offset++] = (byte) c;\r\n\r\n if (i == len && c < 0x0080)\r\n {\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n return lb;\r\n }\r\n\r\n if (c < 0x0800)\r\n {\r\n if (++adjustableLimit > buffer.length)\r\n {\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n return writeUTF8(str, i - 1, len, buffer, offset, buffer.length, session, lb);\r\n }\r\n\r\n buffer[offset++] = (byte) (0xC0 | ((c >> 6) & 0x1F));\r\n buffer[offset++] = (byte) (0x80 | ((c >> 0) & 0x3F));\r\n }\r\n else if (Character.isHighSurrogate((char) c) && i < len && Character.isLowSurrogate((char) str.charAt(i)))\r\n {\r\n // We have a surrogate pair, so use the 4-byte encoding.\r\n adjustableLimit += 3;\r\n if (adjustableLimit > buffer.length)\r\n {\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n return writeUTF8(str, i - 1, len, buffer, offset, buffer.length, session, lb);\r\n }\r\n\r\n int codePoint = Character.toCodePoint((char) c, (char) str.charAt(i));\r\n buffer[offset++] = (byte) (0xF0 | ((codePoint >> 18) & 0x07));\r\n buffer[offset++] = (byte) (0x80 | ((codePoint >> 12) & 0x3F));\r\n buffer[offset++] = (byte) (0x80 | ((codePoint >> 6) & 0x3F));\r\n buffer[offset++] = (byte) (0x80 | ((codePoint >> 0) & 0x3F));\r\n\r\n i++;\r\n }\r\n else\r\n {\r\n adjustableLimit += 2;\r\n if (adjustableLimit > buffer.length)\r\n {\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n return writeUTF8(str, i - 1, len, buffer, offset, buffer.length, session, lb);\r\n }\r\n\r\n buffer[offset++] = (byte) (0xE0 | ((c >> 12) & 0x0F));\r\n buffer[offset++] = (byte) (0x80 | ((c >> 6) & 0x3F));\r\n buffer[offset++] = (byte) (0x80 | ((c >> 0) & 0x3F));\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Writes the utf8-encoded bytes from the string into the {@link LinkedBuffer}.\r\n */\r\n public static LinkedBuffer writeUTF8(final CharSequence str, final WriteSession session,\r\n final LinkedBuffer lb)\r\n {\r\n final int len = str.length();\r\n if (len == 0)\r\n return lb;\r\n\r\n return lb.offset + len > lb.buffer.length ? writeUTF8(str, 0, len, lb.buffer, lb.offset,\r\n lb.buffer.length, session, lb) : writeUTF8(str, 0, len, session, lb);\r\n }\r\n\r\n /**\r\n * Writes the ascii bytes from the string into the {@link LinkedBuffer}. It is the responsibility of the caller to\r\n * know in advance that the string is 100% ascii. E.g if you convert a double/float to a string, you are sure it\r\n * only contains ascii chars.\r\n */\r\n public static LinkedBuffer writeAscii(final CharSequence str, final WriteSession session,\r\n LinkedBuffer lb)\r\n {\r\n final int len = str.length();\r\n if (len == 0)\r\n return lb;\r\n\r\n byte[] buffer = lb.buffer;\r\n int offset = lb.offset, limit = lb.buffer.length;\r\n\r\n // actual size\r\n session.size += len;\r\n\r\n if (offset + len > limit)\r\n {\r\n // slow path\r\n for (int i = 0; i < len; i++)\r\n {\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n lb.offset = offset;\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n buffer[offset++] = (byte) str.charAt(i);\r\n }\r\n }\r\n else\r\n {\r\n // fast path\r\n for (int i = 0; i < len; i++)\r\n buffer[offset++] = (byte) str.charAt(i);\r\n }\r\n\r\n lb.offset = offset;\r\n\r\n return lb;\r\n }\r\n\r\n static void writeFixed2ByteInt(final int value, final byte[] buffer, int offset,\r\n final boolean littleEndian)\r\n {\r\n if (littleEndian)\r\n {\r\n buffer[offset++] = (byte) value;\r\n buffer[offset] = (byte) ((value >>> 8) & 0xFF);\r\n }\r\n else\r\n {\r\n buffer[offset++] = (byte) ((value >>> 8) & 0xFF);\r\n buffer[offset] = (byte) value;\r\n }\r\n }\r\n\r\n /**\r\n * The length of the utf8 bytes is written first (big endian) before the string - which is fixed 2-bytes. Same\r\n * behavior as {@link java.io.DataOutputStream#writeUTF(String)}.\r\n */\r\n public static LinkedBuffer writeUTF8FixedDelimited(final CharSequence str,\r\n final WriteSession session, LinkedBuffer lb)\r\n {\r\n return writeUTF8FixedDelimited(str, false, session, lb);\r\n }\r\n\r\n /**\r\n * The length of the utf8 bytes is written first before the string - which is fixed 2-bytes.\r\n */\r\n public static LinkedBuffer writeUTF8FixedDelimited(final CharSequence str,\r\n final boolean littleEndian, final WriteSession session, LinkedBuffer lb)\r\n {\r\n final int lastSize = session.size, len = str.length(), withIntOffset = lb.offset + 2;\r\n\r\n if (withIntOffset > lb.buffer.length)\r\n {\r\n // not enough space for int (2 bytes).\r\n // create a new buffer.\r\n lb = new LinkedBuffer(len + 2 > session.nextBufferSize ? len + 2 : session.nextBufferSize,\r\n lb);\r\n\r\n lb.offset = 2;\r\n\r\n if (len == 0)\r\n {\r\n writeFixed2ByteInt(0, lb.buffer, 0, littleEndian);\r\n // update size\r\n session.size += 2;\r\n return lb;\r\n }\r\n\r\n // fast path\r\n final LinkedBuffer rb = writeUTF8(str, 0, len, session, lb);\r\n\r\n writeFixed2ByteInt((session.size - lastSize), lb.buffer, 0, littleEndian);\r\n\r\n // update size\r\n session.size += 2;\r\n\r\n return rb;\r\n }\r\n\r\n if (len == 0)\r\n {\r\n writeFixed2ByteInt(0, lb.buffer, lb.offset, littleEndian);\r\n lb.offset = withIntOffset;\r\n // update size\r\n session.size += 2;\r\n return lb;\r\n }\r\n\r\n if (withIntOffset + len > lb.buffer.length)\r\n {\r\n // not enough space for the string.\r\n lb.offset = withIntOffset;\r\n\r\n // slow path\r\n final LinkedBuffer rb = writeUTF8(str, 0, len,\r\n lb.buffer, withIntOffset, lb.buffer.length, session, lb);\r\n\r\n writeFixed2ByteInt((session.size - lastSize), lb.buffer,\r\n withIntOffset - 2, littleEndian);\r\n\r\n // update size\r\n session.size += 2;\r\n\r\n return rb;\r\n }\r\n\r\n // everything fits\r\n lb.offset = withIntOffset;\r\n\r\n final LinkedBuffer rb = writeUTF8(str, 0, len, session, lb);\r\n\r\n writeFixed2ByteInt((session.size - lastSize), lb.buffer,\r\n withIntOffset - 2, littleEndian);\r\n\r\n // update size\r\n session.size += 2;\r\n\r\n return rb;\r\n }\r\n\r\n private static LinkedBuffer writeUTF8OneByteDelimited(final CharSequence str, final int index,\r\n final int len, final WriteSession session, LinkedBuffer lb)\r\n {\r\n final int lastSize = session.size;\r\n\r\n if (lb.offset == lb.buffer.length)\r\n {\r\n // create a new buffer.\r\n lb = new LinkedBuffer(len + 1 > session.nextBufferSize ? len + 1 : session.nextBufferSize,\r\n lb);\r\n\r\n lb.offset = 1;\r\n\r\n // fast path\r\n final LinkedBuffer rb = writeUTF8(str, index, len, session, lb);\r\n\r\n lb.buffer[0] = (byte) (session.size - lastSize);\r\n\r\n // update size\r\n session.size++;\r\n\r\n return rb;\r\n }\r\n\r\n final int withIntOffset = lb.offset + 1;\r\n if (withIntOffset + len > lb.buffer.length)\r\n {\r\n // not enough space for the string.\r\n lb.offset = withIntOffset;\r\n\r\n final byte[] buffer = lb.buffer;\r\n\r\n // slow path\r\n final LinkedBuffer rb = writeUTF8(str, index, len, buffer, withIntOffset, buffer.length,\r\n session, lb);\r\n\r\n buffer[withIntOffset - 1] = (byte) (session.size - lastSize);\r\n\r\n // update size\r\n session.size++;\r\n\r\n return rb;\r\n }\r\n\r\n // everything fits\r\n lb.offset = withIntOffset;\r\n\r\n final LinkedBuffer rb = writeUTF8(str, index, len, session, lb);\r\n\r\n lb.buffer[withIntOffset - 1] = (byte) (session.size - lastSize);\r\n\r\n // update size\r\n session.size++;\r\n\r\n return rb;\r\n }\r\n\r\n private static LinkedBuffer writeUTF8VarDelimited(final CharSequence str, final int index,\r\n final int len, final int lowerLimit, int expectedSize,\r\n final WriteSession session, LinkedBuffer lb)\r\n {\r\n int lastSize = session.size, offset = lb.offset, withIntOffset = offset + expectedSize;\r\n\r\n if (withIntOffset > lb.buffer.length)\r\n {\r\n // not enough space for the varint.\r\n // create a new buffer.\r\n lb = new LinkedBuffer(len + expectedSize > session.nextBufferSize ? len + expectedSize\r\n : session.nextBufferSize,\r\n lb);\r\n offset = lb.start;\r\n lb.offset = withIntOffset = offset + expectedSize;\r\n\r\n // fast path\r\n final LinkedBuffer rb = writeUTF8(str, index, len, session, lb);\r\n\r\n int size = session.size - lastSize;\r\n\r\n if (size < lowerLimit)\r\n {\r\n // move one space to the left since the varint is 1-byte smaller\r\n System.arraycopy(lb.buffer, withIntOffset, lb.buffer, withIntOffset - 1,\r\n lb.offset - withIntOffset);\r\n\r\n expectedSize--;\r\n lb.offset--;\r\n }\r\n\r\n // update size\r\n session.size += expectedSize;\r\n\r\n for (; --expectedSize > 0; size >>>= 7)\r\n lb.buffer[offset++] = (byte) ((size & 0x7F) | 0x80);\r\n\r\n lb.buffer[offset] = (byte) (size);\r\n\r\n return rb;\r\n }\r\n\r\n if (withIntOffset + len > lb.buffer.length)\r\n {\r\n // not enough space for the string.\r\n lb.offset = withIntOffset;\r\n\r\n // slow path\r\n final LinkedBuffer rb = writeUTF8(str, index, len,\r\n lb.buffer, withIntOffset, lb.buffer.length, session, lb);\r\n\r\n int size = session.size - lastSize;\r\n\r\n if (size < lowerLimit)\r\n {\r\n // move one space to the left since the varint is 1-byte smaller\r\n System.arraycopy(lb.buffer, withIntOffset, lb.buffer, withIntOffset - 1,\r\n lb.offset - withIntOffset);\r\n\r\n expectedSize--;\r\n lb.offset--;\r\n }\r\n\r\n // update size\r\n session.size += expectedSize;\r\n\r\n for (; --expectedSize > 0; size >>>= 7)\r\n lb.buffer[offset++] = (byte) ((size & 0x7F) | 0x80);\r\n\r\n lb.buffer[offset] = (byte) (size);\r\n\r\n return rb;\r\n }\r\n\r\n // everything fits\r\n lb.offset = withIntOffset;\r\n\r\n final LinkedBuffer rb = writeUTF8(str, index, len, session, lb);\r\n\r\n int size = session.size - lastSize;\r\n\r\n if (size < lowerLimit)\r\n {\r\n // move one space to the left since the varint is 1-byte smaller\r\n System.arraycopy(lb.buffer, withIntOffset, lb.buffer, withIntOffset - 1,\r\n lb.offset - withIntOffset);\r\n\r\n expectedSize--;\r\n lb.offset--;\r\n }\r\n\r\n // update size\r\n session.size += expectedSize;\r\n\r\n for (; --expectedSize > 0; size >>>= 7)\r\n lb.buffer[offset++] = (byte) ((size & 0x7F) | 0x80);\r\n\r\n lb.buffer[offset] = (byte) (size);\r\n\r\n return rb;\r\n }\r\n\r\n /**\r\n * The length of the utf8 bytes is written first before the string - which is a variable int (1 to 5 bytes).\r\n */\r\n public static LinkedBuffer writeUTF8VarDelimited(final CharSequence str, final WriteSession session,\r\n LinkedBuffer lb)\r\n {\r\n final int len = str.length();\r\n if (len == 0)\r\n {\r\n if (lb.offset == lb.buffer.length)\r\n {\r\n // buffer full\r\n lb = new LinkedBuffer(session.nextBufferSize, lb);\r\n }\r\n\r\n // write zero\r\n lb.buffer[lb.offset++] = 0x00;\r\n // update size\r\n session.size++;\r\n return lb;\r\n }\r\n\r\n if (len < ONE_BYTE_EXCLUSIVE)\r\n {\r\n // the varint will be max 1-byte. (even if all chars are non-ascii)\r\n return writeUTF8OneByteDelimited(str, 0, len, session, lb);\r\n }\r\n\r\n if (len < TWO_BYTE_EXCLUSIVE)\r\n {\r\n // the varint will be max 2-bytes and could be 1-byte. (even if all non-ascii)\r\n return writeUTF8VarDelimited(str, 0, len, TWO_BYTE_LOWER_LIMIT, 2,\r\n session, lb);\r\n }\r\n\r\n if (len < THREE_BYTE_EXCLUSIVE)\r\n {\r\n // the varint will be max 3-bytes and could be 2-bytes. (even if all non-ascii)\r\n return writeUTF8VarDelimited(str, 0, len, THREE_BYTE_LOWER_LIMIT, 3,\r\n session, lb);\r\n }\r\n\r\n if (len < FOUR_BYTE_EXCLUSIVE)\r\n {\r\n // the varint will be max 4-bytes and could be 3-bytes. (even if all non-ascii)\r\n return writeUTF8VarDelimited(str, 0, len, FOUR_BYTE_LOWER_LIMIT, 4,\r\n session, lb);\r\n }\r\n\r\n // the varint will be max 5-bytes and could be 4-bytes. (even if all non-ascii)\r\n return writeUTF8VarDelimited(str, 0, len, FIVE_BYTE_LOWER_LIMIT, 5, session, lb);\r\n }\r\n\r\n public static final class STRING\r\n {\r\n static final boolean CESU8_COMPAT = Boolean.getBoolean(\"io.protostuff.cesu8_compat\");\r\n\r\n private STRING()\r\n {\r\n }\r\n\r\n public static String deser(byte[] nonNullValue)\r\n {\r\n return deser(nonNullValue, 0, nonNullValue.length);\r\n }\r\n\r\n public static String deser(byte[] nonNullValue, int offset, int len)\r\n {\r\n final String result;\r\n try\r\n {\r\n // Try to use the built in deserialization first, since we expect\r\n // that the most likely case is a valid UTF-8 encoded byte array.\r\n // Additionally, the built in serialization method has one less\r\n // char[] copy than readUTF.\r\n //\r\n // If, however, there are invalid/malformed characters, i.e. 3-byte\r\n // surrogates / 3-byte surrogate pairs, we should fall back to the\r\n // readUTF method as it should be able to properly handle 3-byte surrogates\r\n // (and therefore 6-byte surrogate pairs) in Java 8+.\r\n //\r\n // While Protostuff and many other applications, still use 3-byte surrogates\r\n // / 6-byte surrogate pairs, the standard 'forbids' their use, and Java 8\r\n // has started to enforce the standard, resulting in 'corrupted' data in\r\n // strings when decoding using new String(nonNullValue, \"UTF-8\");\r\n //\r\n // While the readUTF should be able to handle both Standard Unicode\r\n // (i.e. new String().getBytes(\"UTF-8\") and the Legacy Unicode\r\n // (with 3-byte surrogates, used in CESU-8 and Modified UTF-8),\r\n // we don't want to introduce an unexpected loss of data due to\r\n // some unforseen bug. As a result, a fallback mechanism is in\r\n // place such that the worst case scenario results in the previous\r\n // implementation's behaviour.\r\n //\r\n // For the Java 8 change, see: https://bugs.openjdk.java.net/browse/JDK-7096080\r\n\r\n result = new String(nonNullValue, offset, len, \"UTF-8\");\r\n\r\n // Check if we should scan the string to make sure there were no\r\n // corrupt characters caused by 3-byte / 6-byte surrogate pairs.\r\n //\r\n // In general, this *should* only be required for systems reading\r\n // data stored using legacy protostuff. Moving forward, the data\r\n // should be readable by new String(\"UTF-8\"), so the scan is unnecessary.\r\n if (CESU8_COMPAT && result.indexOf(0xfffd) != -1)\r\n {\r\n // If it contains the REPLACEMENT character, then there's a strong\r\n // possibility of it containing 3-byte surrogates / 6-byte surrogate\r\n // pairs, and we should try decoding using readUTF to handle it.\r\n try\r\n {\r\n return readUTF(nonNullValue, offset, len);\r\n }\r\n catch (UTFDataFormatException e)\r\n {\r\n // Unexpected, but most systems previously using\r\n // Protostuff don't expect error to occur from\r\n // String deserialization, so we use this just in case.\r\n return result;\r\n }\r\n }\r\n }\r\n catch (UnsupportedEncodingException e)\r\n {\r\n throw new RuntimeException(e);\r\n }\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Deserialize using readUTF only.\r\n *\r\n * @param nonNullValue\r\n * @return\r\n */\r\n static String deserCustomOnly(byte[] nonNullValue)\r\n {\r\n try\r\n {\r\n // Same behaviour as deser(), but does NOT\r\n // fall back to old implementation.\r\n return readUTF(nonNullValue, 0, nonNullValue.length);\r\n }\r\n catch (UTFDataFormatException e)\r\n {\r\n throw new RuntimeException(e);\r\n }\r\n }\r\n\r\n public static byte[] ser(String nonNullValue)\r\n {\r\n try\r\n {\r\n return nonNullValue.getBytes(\"UTF-8\");\r\n }\r\n catch (UnsupportedEncodingException e)\r\n {\r\n throw new RuntimeException(e);\r\n }\r\n }\r\n\r\n /**\r\n * Reads the string from a byte[] using that was encoded a using Modified UTF-8 format. Additionally supports\r\n * 4-byte surrogates, de-serializing them as surrogate pairs.\r\n *\r\n * See: http://en.wikipedia.org/wiki/UTF-8#Description for encoding details.\r\n */\r\n private static String readUTF(byte[] buffer, int offset, int len) throws UTFDataFormatException\r\n {\r\n char[] charArray = new char[len];\r\n\r\n int i = 0;\r\n int c = 0;\r\n\r\n // Optimizaiton: Assume that the characters are all 7-bits encodable\r\n // (which is most likely the standard case).\r\n // If they're not, break out and take the 'slow' path.\r\n for (; i < len; i++)\r\n {\r\n int ch = (int) buffer[offset + i] & 0xff;\r\n\r\n // If it's not 7-bit character, break out\r\n if (ch > 127)\r\n break;\r\n\r\n charArray[c++] = (char) ch;\r\n }\r\n\r\n // 'Slow' path\r\n while (i < len)\r\n {\r\n int ch = (int) buffer[offset + i] & 0xff;\r\n\r\n // Determine how to decode based on 'bits of code point'\r\n // See: http://en.wikipedia.org/wiki/UTF-8#Description\r\n int upperBits = ch >> 4;\r\n\r\n if (upperBits <= 7)\r\n {\r\n // 1-byte: 0xxxxxxx\r\n charArray[c++] = (char) ch;\r\n i++;\r\n }\r\n else if (upperBits == 0x0C || upperBits == 0x0D)\r\n {\r\n // 2-byte: 110xxxxx 10xxxxxx\r\n i += 2;\r\n\r\n if (i > len)\r\n throw new UTFDataFormatException(\"Malformed input: Partial character at end\");\r\n\r\n int ch2 = (int) buffer[offset + i - 1];\r\n\r\n // Make sure the second byte has the form 10xxxxxx\r\n if ((ch2 & 0xC0) != 0x80)\r\n throw new UTFDataFormatException(\"Malformed input around byte \" + i);\r\n\r\n charArray[c++] = (char) (((ch & 0x1F) << 6) | (ch2 & 0x3F));\r\n }\r\n else if (upperBits == 0xE)\r\n {\r\n // 3-byte: 1110xxxx 10xxxxxx 10xxxxxx\r\n i += 3;\r\n\r\n if (i > len)\r\n throw new UTFDataFormatException(\"Malformed input: Partial character at end\");\r\n\r\n int ch2 = (int) buffer[offset + i - 2];\r\n int ch3 = (int) buffer[offset + i - 1];\r\n\r\n // Check the 10xxxxxx 10xxxxxx of second two bytes\r\n if (((ch2 & 0xC0) != 0x80) || ((ch3 & 0xC0) != 0x80))\r\n throw new UTFDataFormatException(\"Malformed input around byte \" + (i - 1));\r\n\r\n charArray[c++] = (char) (((ch & 0x0F) << 12) | ((ch2 & 0x3F) << 6) | (ch3 & 0x3F));\r\n }\r\n else\r\n {\r\n // 4-byte: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\r\n upperBits = ch >> 3;\r\n if (upperBits == 0x1E)\r\n {\r\n // Because we're now in the UTF-32 bit range, we must\r\n // break it down into the UTF-16 surrogate pairs for\r\n // Java's String class (which is UTF-16).\r\n\r\n i += 4;\r\n if (i > len)\r\n throw new UTFDataFormatException(\"Malformed input: Partial character at end\");\r\n\r\n int ch2 = (int) buffer[offset + i - 3];\r\n int ch3 = (int) buffer[offset + i - 2];\r\n int ch4 = (int) buffer[offset + i - 1];\r\n\r\n int value =\r\n ((ch & 0x07) << 18) |\r\n ((ch2 & 0x3F) << 12) |\r\n ((ch3 & 0x3F) << 6) |\r\n ((ch4 & 0x3F));\r\n\r\n charArray[c++] = highSurrogate(value);\r\n charArray[c++] = lowSurrogate(value);\r\n }\r\n else\r\n {\r\n // Anything above\r\n throw new UTFDataFormatException(\"Malformed input at byte \" + i);\r\n }\r\n }\r\n }\r\n\r\n return new String(charArray, 0, c);\r\n }\r\n }\r\n\r\n\r\n public static char highSurrogate(int codePoint) {\r\n return (char) ((codePoint >>> 10)\r\n + (MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)));\r\n }\r\n\r\n public static char lowSurrogate(int codePoint) {\r\n return (char) ((codePoint & 0x3ff) + MIN_LOW_SURROGATE);\r\n }\r\n\r\n}\r\n", "file_name": "StringSerializer.java", "human_label": "Compute the size of the utf8 string beginning at the specified index with the specified length.", "level": "self_contained", "lineno": "317", "name": "computeUTF8Size", "oracle_context": "{ \"apis\" : \"[charAt]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "io.protostuff", "project": "protostuff-master" }, { "_id": "636766f01a6d9265ec017639", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.io.InputStream;\\nimport java.lang.reflect.Constructor;\\nimport java.lang.reflect.InvocationTargetException;\\nimport java.lang.reflect.Method;\\nimport java.lang.reflect.Modifier;\\nimport java.net.URL;\\nimport java.util.Arrays;\\nimport java.util.Collections;\\nimport java.util.HashMap;\\nimport java.util.List;\\nimport java.util.logging.Logger;\\nLogger logger;\\nint CR;\\nint LF;\\nHashMap> name2Class;\\nHashMap,String> class2Name;\\nHashMap,Method> class2Value;\\nfromName(String name);\\ntoName(Class type);\\nvalueOf(Class type,String value);\\nvalueOf(String type,String value);\\nparseInt(String s,int offset,int length,int base);\\nparseInt(byte[] b,int offset,int length,int base);\\nparseBytes(String s,int base);\\ntoString(byte[] bytes,int base);\\nconvertHexDigit(byte b);\\ntoHex(byte b,Appendable buf);\\ntoHexString(byte b);\\ntoHexString(byte[] b);\\ntoHexString(byte[] b,int offset,int length);\\nfromHexString(String s);\\ndump(Class c);\\ndump(ClassLoader cl);\\nreadLine(InputStream in);\\njarFor(String className);\\ncall(Class oClass,String method,Object obj,Object[] arg);\\n\", \"repo_level\" : \"\" }", "class_name": "TypeUtil", "code": "public static List asList(T[] a){\n if (a == null) return Collections.emptyList();\n return Arrays.asList(a);\n}\n", "docstring": "/** \n * Array to List.

Works like {@link Arrays#asList(Object)}, but handles null arrays.\n * @return a list backed by the array.\n */\n", "end_lineno": "143", "file_content": "// ========================================================================\n// Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd.\n// ------------------------------------------------------------------------\n// All rights reserved. This program and the accompanying materials\n// are made available under the terms of the Eclipse Public License v1.0\n// and Apache License v2.0 which accompanies this distribution.\n// The Eclipse Public License is available at\n// http://www.eclipse.org/legal/epl-v10.html\n// The Apache License v2.0 is available at\n// http://www.opensource.org/licenses/apache2.0.php\n// You may elect to redistribute this code under either of these licenses.\n// ========================================================================\npackage net.hasor.utils.json;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.net.URL;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.logging.Logger;\n/* ------------------------------------------------------------ */\n\n/**\n * TYPE Utilities.\n * Provides various static utiltiy methods for manipulating types and their\n * string representations.\n *\n * @since Jetty 4.1\n */\nclass TypeUtil {\n protected final static Logger logger = Logger.getLogger(TypeUtil.class.getName());\n public static int CR = '\\015';\n public static int LF = '\\012';\n /* ------------------------------------------------------------ */\n private static final HashMap> name2Class = new HashMap>();\n\n static {\n name2Class.put(\"boolean\", Boolean.TYPE);\n name2Class.put(\"byte\", Byte.TYPE);\n name2Class.put(\"char\", Character.TYPE);\n name2Class.put(\"double\", Double.TYPE);\n name2Class.put(\"float\", Float.TYPE);\n name2Class.put(\"int\", Integer.TYPE);\n name2Class.put(\"long\", Long.TYPE);\n name2Class.put(\"short\", Short.TYPE);\n name2Class.put(\"void\", Void.TYPE);\n name2Class.put(\"java.lang.Boolean.TYPE\", Boolean.TYPE);\n name2Class.put(\"java.lang.Byte.TYPE\", Byte.TYPE);\n name2Class.put(\"java.lang.Character.TYPE\", Character.TYPE);\n name2Class.put(\"java.lang.Double.TYPE\", Double.TYPE);\n name2Class.put(\"java.lang.Float.TYPE\", Float.TYPE);\n name2Class.put(\"java.lang.Integer.TYPE\", Integer.TYPE);\n name2Class.put(\"java.lang.Long.TYPE\", Long.TYPE);\n name2Class.put(\"java.lang.Short.TYPE\", Short.TYPE);\n name2Class.put(\"java.lang.Void.TYPE\", Void.TYPE);\n name2Class.put(\"java.lang.Boolean\", Boolean.class);\n name2Class.put(\"java.lang.Byte\", Byte.class);\n name2Class.put(\"java.lang.Character\", Character.class);\n name2Class.put(\"java.lang.Double\", Double.class);\n name2Class.put(\"java.lang.Float\", Float.class);\n name2Class.put(\"java.lang.Integer\", Integer.class);\n name2Class.put(\"java.lang.Long\", Long.class);\n name2Class.put(\"java.lang.Short\", Short.class);\n name2Class.put(\"Boolean\", Boolean.class);\n name2Class.put(\"Byte\", Byte.class);\n name2Class.put(\"Character\", Character.class);\n name2Class.put(\"Double\", Double.class);\n name2Class.put(\"Float\", Float.class);\n name2Class.put(\"Integer\", Integer.class);\n name2Class.put(\"Long\", Long.class);\n name2Class.put(\"Short\", Short.class);\n name2Class.put(null, Void.TYPE);\n name2Class.put(\"string\", String.class);\n name2Class.put(\"String\", String.class);\n name2Class.put(\"java.lang.String\", String.class);\n }\n\n /* ------------------------------------------------------------ */\n private static final HashMap, String> class2Name = new HashMap, String>();\n\n static {\n class2Name.put(Boolean.TYPE, \"boolean\");\n class2Name.put(Byte.TYPE, \"byte\");\n class2Name.put(Character.TYPE, \"char\");\n class2Name.put(Double.TYPE, \"double\");\n class2Name.put(Float.TYPE, \"float\");\n class2Name.put(Integer.TYPE, \"int\");\n class2Name.put(Long.TYPE, \"long\");\n class2Name.put(Short.TYPE, \"short\");\n class2Name.put(Void.TYPE, \"void\");\n class2Name.put(Boolean.class, \"java.lang.Boolean\");\n class2Name.put(Byte.class, \"java.lang.Byte\");\n class2Name.put(Character.class, \"java.lang.Character\");\n class2Name.put(Double.class, \"java.lang.Double\");\n class2Name.put(Float.class, \"java.lang.Float\");\n class2Name.put(Integer.class, \"java.lang.Integer\");\n class2Name.put(Long.class, \"java.lang.Long\");\n class2Name.put(Short.class, \"java.lang.Short\");\n class2Name.put(null, \"void\");\n class2Name.put(String.class, \"java.lang.String\");\n }\n\n /* ------------------------------------------------------------ */\n private static final HashMap, Method> class2Value = new HashMap, Method>();\n\n static {\n try {\n Class[] s = { String.class };\n class2Value.put(Boolean.TYPE, Boolean.class.getMethod(\"valueOf\", s));\n class2Value.put(Byte.TYPE, Byte.class.getMethod(\"valueOf\", s));\n class2Value.put(Double.TYPE, Double.class.getMethod(\"valueOf\", s));\n class2Value.put(Float.TYPE, Float.class.getMethod(\"valueOf\", s));\n class2Value.put(Integer.TYPE, Integer.class.getMethod(\"valueOf\", s));\n class2Value.put(Long.TYPE, Long.class.getMethod(\"valueOf\", s));\n class2Value.put(Short.TYPE, Short.class.getMethod(\"valueOf\", s));\n class2Value.put(Boolean.class, Boolean.class.getMethod(\"valueOf\", s));\n class2Value.put(Byte.class, Byte.class.getMethod(\"valueOf\", s));\n class2Value.put(Double.class, Double.class.getMethod(\"valueOf\", s));\n class2Value.put(Float.class, Float.class.getMethod(\"valueOf\", s));\n class2Value.put(Integer.class, Integer.class.getMethod(\"valueOf\", s));\n class2Value.put(Long.class, Long.class.getMethod(\"valueOf\", s));\n class2Value.put(Short.class, Short.class.getMethod(\"valueOf\", s));\n } catch (Exception e) {\n throw new Error(e);\n }\n }\n /* ------------------------------------------------------------ */\n\n /** Array to List.\n *

\n * Works like {@link Arrays#asList(Object...)}, but handles null arrays.\n * @return a list backed by the array.\n */\n public static List asList(T[] a) {\n if (a == null)\n return Collections.emptyList();\n return Arrays.asList(a);\n }\n /* ------------------------------------------------------------ */\n\n /** Class from a canonical name for a type.\n * @param name A class or type name.\n * @return A class , which may be a primitive TYPE field..\n */\n public static Class fromName(String name) {\n return name2Class.get(name);\n }\n /* ------------------------------------------------------------ */\n\n /** Canonical name for a type.\n * @param type A class , which may be a primitive TYPE field.\n * @return Canonical name.\n */\n public static String toName(Class type) {\n return class2Name.get(type);\n }\n /* ------------------------------------------------------------ */\n\n /** Convert String value to instance.\n * @param type The class of the instance, which may be a primitive TYPE field.\n * @param value The value as a string.\n * @return The value as an Object.\n */\n public static Object valueOf(Class type, String value) {\n try {\n if (type.equals(String.class))\n return value;\n Method m = class2Value.get(type);\n if (m != null)\n return m.invoke(null, value);\n if (type.equals(Character.TYPE) || type.equals(Character.class))\n return new Character(value.charAt(0));\n Constructor c = type.getConstructor(String.class);\n return c.newInstance(value);\n } catch (NoSuchMethodException e) {\n // LogSupport.ignore(log,e);\n } catch (IllegalAccessException e) {\n // LogSupport.ignore(log,e);\n } catch (InstantiationException e) {\n // LogSupport.ignore(log,e);\n } catch (InvocationTargetException e) {\n if (e.getTargetException() instanceof Error)\n throw (Error) (e.getTargetException());\n // LogSupport.ignore(log,e);\n }\n return null;\n }\n /* ------------------------------------------------------------ */\n\n /** Convert String value to instance.\n * @param type classname or type (eg int)\n * @param value The value as a string.\n * @return The value as an Object.\n */\n public static Object valueOf(String type, String value) {\n return valueOf(fromName(type), value);\n }\n /* ------------------------------------------------------------ */\n\n /** Parse an int from a substring.\n * Negative numbers are not handled.\n * @param s String\n * @param offset Offset within string\n * @param length Length of integer or -1 for remainder of string\n * @param base base of the integer\n * @return the parsed integer\n * @throws NumberFormatException if the string cannot be parsed\n */\n public static int parseInt(String s, int offset, int length, int base) throws NumberFormatException {\n int value = 0;\n if (length < 0)\n length = s.length() - offset;\n for (int i = 0; i < length; i++) {\n char c = s.charAt(offset + i);\n int digit = c - '0';\n if (digit < 0 || digit >= base || digit >= 10) {\n digit = 10 + c - 'A';\n if (digit < 10 || digit >= base)\n digit = 10 + c - 'a';\n }\n if (digit < 0 || digit >= base)\n throw new NumberFormatException(s.substring(offset, offset + length));\n value = value * base + digit;\n }\n return value;\n }\n /* ------------------------------------------------------------ */\n\n /** Parse an int from a byte array of ascii characters.\n * Negative numbers are not handled.\n * @param b byte array\n * @param offset Offset within string\n * @param length Length of integer or -1 for remainder of string\n * @param base base of the integer\n * @return the parsed integer\n * @throws NumberFormatException if the array cannot be parsed into an integer\n */\n public static int parseInt(byte[] b, int offset, int length, int base) throws NumberFormatException {\n int value = 0;\n if (length < 0)\n length = b.length - offset;\n for (int i = 0; i < length; i++) {\n char c = (char) (0xff & b[offset + i]);\n int digit = c - '0';\n if (digit < 0 || digit >= base || digit >= 10) {\n digit = 10 + c - 'A';\n if (digit < 10 || digit >= base)\n digit = 10 + c - 'a';\n }\n if (digit < 0 || digit >= base)\n throw new NumberFormatException(new String(b, offset, length));\n value = value * base + digit;\n }\n return value;\n }\n\n /* ------------------------------------------------------------ */\n public static byte[] parseBytes(String s, int base) {\n byte[] bytes = new byte[s.length() / 2];\n for (int i = 0; i < s.length(); i += 2)\n bytes[i / 2] = (byte) TypeUtil.parseInt(s, i, 2, base);\n return bytes;\n }\n\n /* ------------------------------------------------------------ */\n public static String toString(byte[] bytes, int base) {\n StringBuilder buf = new StringBuilder();\n for (byte b : bytes) {\n int bi = 0xff & b;\n int c = '0' + (bi / base) % base;\n if (c > '9')\n c = 'a' + (c - '0' - 10);\n buf.append((char) c);\n c = '0' + bi % base;\n if (c > '9')\n c = 'a' + (c - '0' - 10);\n buf.append((char) c);\n }\n return buf.toString();\n }\n /* ------------------------------------------------------------ */\n\n /**\n * @param b An ASCII encoded character 0-9 a-f A-F\n * @return The byte value of the character 0-16.\n */\n public static byte convertHexDigit(byte b) {\n if ((b >= '0') && (b <= '9'))\n return (byte) (b - '0');\n if ((b >= 'a') && (b <= 'f'))\n return (byte) (b - 'a' + 10);\n if ((b >= 'A') && (b <= 'F'))\n return (byte) (b - 'A' + 10);\n throw new IllegalArgumentException(\"!hex:\" + Integer.toHexString(0xff & b));\n }\n\n /* ------------------------------------------------------------ */\n public static void toHex(byte b, Appendable buf) {\n try {\n int bi = 0xff & b;\n int c = '0' + (bi / 16) % 16;\n if (c > '9')\n c = 'A' + (c - '0' - 10);\n buf.append((char) c);\n c = '0' + bi % 16;\n if (c > '9')\n c = 'A' + (c - '0' - 10);\n buf.append((char) c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /* ------------------------------------------------------------ */\n public static String toHexString(byte b) {\n return toHexString(new byte[] { b }, 0, 1);\n }\n\n /* ------------------------------------------------------------ */\n public static String toHexString(byte[] b) {\n return toHexString(b, 0, b.length);\n }\n\n /* ------------------------------------------------------------ */\n public static String toHexString(byte[] b, int offset, int length) {\n StringBuilder buf = new StringBuilder();\n for (int i = offset; i < offset + length; i++) {\n int bi = 0xff & b[i];\n int c = '0' + (bi / 16) % 16;\n if (c > '9')\n c = 'A' + (c - '0' - 10);\n buf.append((char) c);\n c = '0' + bi % 16;\n if (c > '9')\n c = 'a' + (c - '0' - 10);\n buf.append((char) c);\n }\n return buf.toString();\n }\n\n /* ------------------------------------------------------------ */\n public static byte[] fromHexString(String s) {\n if (s.length() % 2 != 0)\n throw new IllegalArgumentException(s);\n byte[] array = new byte[s.length() / 2];\n for (int i = 0; i < array.length; i++) {\n int b = Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16);\n array[i] = (byte) (0xff & b);\n }\n return array;\n }\n\n public static void dump(Class c) {\n System.err.println(\"Dump: \" + c);\n dump(c.getClassLoader());\n }\n\n public static void dump(ClassLoader cl) {\n System.err.println(\"Dump Loaders:\");\n while (cl != null) {\n System.err.println(\" loader \" + cl);\n cl = cl.getParent();\n }\n }\n\n /* ------------------------------------------------------------ */\n public static byte[] readLine(InputStream in) throws IOException {\n byte[] buf = new byte[256];\n int i = 0;\n int loops = 0;\n int ch = 0;\n while (true) {\n ch = in.read();\n if (ch < 0)\n break;\n loops++;\n // skip a leading LF's\n if (loops == 1 && ch == LF)\n continue;\n if (ch == CR || ch == LF)\n break;\n if (i >= buf.length) {\n byte[] old_buf = buf;\n buf = new byte[old_buf.length + 256];\n System.arraycopy(old_buf, 0, buf, 0, old_buf.length);\n }\n buf[i++] = (byte) ch;\n }\n if (ch == -1 && i == 0)\n return null;\n // skip a trailing LF if it exists\n if (ch == CR && in.available() >= 1 && in.markSupported()) {\n in.mark(1);\n ch = in.read();\n if (ch != LF)\n in.reset();\n }\n byte[] old_buf = buf;\n buf = new byte[i];\n System.arraycopy(old_buf, 0, buf, 0, i);\n return buf;\n }\n\n public static URL jarFor(String className) {\n try {\n className = className.replace('.', '/') + \".class\";\n // hack to discover jstl libraries\n URL url = Loader.getResource(null, className, false);\n String s = url.toString();\n if (s.startsWith(\"jar:file:\"))\n return new URL(s.substring(4, s.indexOf(\"!/\")));\n } catch (Exception e) {\n logger.fine(e.getMessage());\n }\n return null;\n }\n\n public static Object call(Class oClass, String method, Object obj, Object[] arg) throws InvocationTargetException, NoSuchMethodException {\n // Lets just try all methods for now\n Method[] methods = oClass.getMethods();\n for (int c = 0; methods != null && c < methods.length; c++) {\n if (!methods[c].getName().equals(method))\n continue;\n if (methods[c].getParameterTypes().length != arg.length)\n continue;\n if (Modifier.isStatic(methods[c].getModifiers()) != (obj == null))\n continue;\n if ((obj == null) && methods[c].getDeclaringClass() != oClass)\n continue;\n try {\n return methods[c].invoke(obj, arg);\n } catch (IllegalAccessException e) {\n logger.fine(e.getMessage());\n } catch (IllegalArgumentException e) {\n logger.fine(e.getMessage());\n }\n }\n throw new NoSuchMethodException(method);\n }\n}\n", "file_name": "TypeUtil.java", "human_label": "Convert an array to list, return empty list for null array.", "level": "slib_runnable", "lineno": "134", "name": "asList", "oracle_context": "{ \"apis\" : \"[emptyList]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils.json", "project": "hasor-master" }, { "_id": "6367672d1a6d9265ec017c74", "all_context": "{ \"class_level\" : \"HashMap map;\\nArrayList values;\\nRandomizedSet();\\nremove(int val);\\ngetRandom();\\ninsert(int val);\\n\", \"repo_level\" : \"\" }", "class_name": "RandomizedSet", "code": "public boolean remove(int val){\n if (map.containsKey(val)) {\n map.remove(val);\n values.remove(values.indexOf(val));\n return true;\n }\n return false;\n}\n", "docstring": "/** \n * Removes a value from the set. Returns true if the set contained the specified element. \n */\n", "end_lineno": "62", "file_content": "//Design a data structure that supports all following operations in average O(1) time.\n\n//insert(val): Inserts an item val to the set if not already present.\n//remove(val): Removes an item val from the set if present.\n//getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.\n\n//Example:\n// Init an empty set.\n//RandomizedSet randomSet = new RandomizedSet();\n\n// Inserts 1 to the set. Returns true as 1 was inserted successfully.\n//randomSet.insert(1);\n\n// Returns false as 2 does not exist in the set.\n//randomSet.remove(2);\n\n// Inserts 2 to the set, returns true. Set now contains [1,2].\n//randomSet.insert(2);\n\n// getRandom should return either 1 or 2 randomly.\n//randomSet.getRandom();\n\n// Removes 1 from the set, returns true. Set now contains [2].\n//randomSet.remove(1);\n\n// 2 was already in the set, so return false.\n//randomSet.insert(2);\n\n// Since 2 is the only number in the set, getRandom always return 2.\n//randomSet.getRandom();\n\nclass RandomizedSet {\n HashMap map;\n ArrayList values;\n\n /** Initialize your data structure here. */\n public RandomizedSet() {\n map = new HashMap();\n values = new ArrayList();\n }\n \n /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */\n public boolean insert(int val) {\n if(!map.containsKey(val)) {\n map.put(val, val);\n values.add(val);\n return true;\n }\n else {\n return false;\n }\n }\n \n /** Removes a value from the set. Returns true if the set contained the specified element. */\n public boolean remove(int val) {\n if(map.containsKey(val)) {\n map.remove(val);\n values.remove(values.indexOf(val));\n return true;\n }\n return false;\n }\n \n /** Get a random element from the set. */\n public int getRandom() {\n int random = (int)(Math.random() * values.size());\n int valueToReturn = values.get(random);\n return map.get(valueToReturn);\n }\n}\n\n/**\n * Your RandomizedSet object will be instantiated and called as such:\n * RandomizedSet obj = new RandomizedSet();\n * boolean param_1 = obj.insert(val);\n * boolean param_2 = obj.remove(val);\n * int param_3 = obj.getRandom();\n */\n\n", "file_name": "InsertDeleteGetRandomO1.java", "human_label": "Remove a value from the values if the map keys contains the val. Returns true if actually removed, and false otherwise.", "level": "self_contained", "lineno": "54", "name": "remove", "oracle_context": "{ \"apis\" : \"[containsKey, indexOf]\", \"classes\" : \"[]\", \"vars\" : \"[map, values]\" }", "package": "", "project": "interviews-master" }, { "_id": "6367676b1a6d9265ec0181df", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static boolean startsWithIgnoreCase(String str,String prefix){\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr=str.substring(0,prefix.length()).toLowerCase();\n String lcPrefix=prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n}\n", "docstring": "/** \n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n", "end_lineno": "310", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *

\n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
\n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Return true if the given string starts with the specified case-insensitive prefix, false otherwise.", "level": "self_contained", "lineno": "290", "name": "startsWithIgnoreCase", "oracle_context": "{ \"apis\" : \"[startsWith, length, toLowerCase, substring, equals]\", \"classes\" : \"[String]\", \"vars\" : \"[]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "6367674b1a6d9265ec017dc0", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.alg.interfaces.*;\\nimport org.jgrapht.alg.util.*;\\nimport java.util.*;\\nboolean DEFAULT_USE_HEURISTICS;\\nGraph graph;\\nComparator comparator;\\nboolean useHeuristics;\\nint WORK_ARRAY_INITIAL_SIZE;\\ndouble[] a;\\nPathGrowingWeightedMatching(Graph graph);\\nPathGrowingWeightedMatching(Graph graph,boolean useHeuristics);\\nPathGrowingWeightedMatching(Graph graph,boolean useHeuristics,double epsilon);\\ngetMatching();\\nrun();\\nrunWithHeuristics();\\ngetMaximumWeightMatching(Graph g,LinkedList path);\\n\", \"repo_level\" : \"\" }", "class_name": "PathGrowingWeightedMatching", "code": "private Set initVisibleVertices(){\n Set visibleVertex=new HashSet<>();\n for ( E e : graph.edgeSet()) {\n V s=graph.getEdgeSource(e);\n V t=graph.getEdgeTarget(e);\n if (!s.equals(t)) {\n visibleVertex.add(s);\n visibleVertex.add(t);\n }\n }\n return visibleVertex;\n}\n", "docstring": "/** \n * Compute all vertices that have positive degree by iterating over the edges on purpose. This keeps the complexity to $O(m)$ where $m$ is the number of edges.\n * @return set of vertices with positive degree\n */\n", "end_lineno": "156", "file_content": "/*\n * (C) Copyright 2016-2021, by Dimitrios Michail and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.matching;\n\nimport org.jgrapht.*;\nimport org.jgrapht.alg.interfaces.*;\nimport org.jgrapht.alg.util.*;\n\nimport java.util.*;\n\n/**\n * A linear time $\\frac{1}{2}$-approximation algorithm for finding a maximum weight matching in an\n * arbitrary graph. Linear time here means $O(m)$ where m is the cardinality of the edge set, even\n * if the graph contains isolated vertices. $\\frac{1}{2}$-approximation means that for any graph\n * instance, the algorithm computes a matching whose weight is at least half of the weight of a\n * maximum weight matching. The implementation accepts directed and undirected graphs which may\n * contain self-loops and multiple edges. There is no assumption on the edge weights, i.e. they can\n * also be negative or zero.\n * \n *

\n * The algorithm is due to Drake and Hougardy, described in detail in the following paper:\n *

    \n *
  • D.E. Drake, S. Hougardy, A Simple Approximation Algorithm for the Weighted Matching Problem,\n * Information Processing Letters 85, 211-213, 2003.
  • \n *
\n * \n *

\n * This particular implementation uses by default two additional heuristics discussed by the authors\n * which also take linear time but improve the quality of the matchings. These heuristics can be\n * disabled by calling the constructor {@link #PathGrowingWeightedMatching(Graph, boolean)}.\n * Disabling the heuristics has the effect of fewer passes over the edge set of the input graph,\n * probably at the expense of the total weight of the matching.\n * \n *

\n * For a discussion on engineering approximate weighted matching algorithms see the following paper:\n *

    \n *
  • Jens Maue and Peter Sanders. Engineering algorithms for approximate weighted matching.\n * International Workshop on Experimental and Efficient Algorithms, Springer, 2007.
  • \n *
\n *\n * @see GreedyWeightedMatching\n * \n * @param the graph vertex type\n * @param the graph edge type\n *\n * @author Dimitrios Michail\n */\npublic class PathGrowingWeightedMatching\n implements\n MatchingAlgorithm\n{\n /**\n * Default value on whether to use extra heuristics to improve the result.\n */\n public static final boolean DEFAULT_USE_HEURISTICS = true;\n\n private final Graph graph;\n private final Comparator comparator;\n private final boolean useHeuristics;\n\n /**\n * Construct a new instance of the path growing algorithm. Floating point values are compared\n * using {@link #DEFAULT_EPSILON} tolerance. By default two additional linear time heuristics\n * are used in order to improve the quality of the matchings.\n * \n * @param graph the input graph\n */\n public PathGrowingWeightedMatching(Graph graph)\n {\n this(graph, DEFAULT_USE_HEURISTICS, DEFAULT_EPSILON);\n }\n\n /**\n * Construct a new instance of the path growing algorithm. Floating point values are compared\n * using {@link #DEFAULT_EPSILON} tolerance.\n * \n * @param graph the input graph\n * @param useHeuristics if true an improved version with additional heuristics is executed. The\n * running time remains linear but performs a few more passes over the input. While the\n * approximation factor remains $\\frac{1}{2}$, in most cases the heuristics produce\n * matchings of higher quality.\n */\n public PathGrowingWeightedMatching(Graph graph, boolean useHeuristics)\n {\n this(graph, useHeuristics, DEFAULT_EPSILON);\n }\n\n /**\n * Construct a new instance of the path growing algorithm.\n * \n * @param graph the input graph\n * @param useHeuristics if true an improved version with additional heuristics is executed. The\n * running time remains linear but performs a few more passes over the input. While the\n * approximation factor remains $\\frac{1}{2}$, in most cases the heuristics produce\n * matchings of higher quality.\n * @param epsilon tolerance when comparing floating point values\n */\n public PathGrowingWeightedMatching(Graph graph, boolean useHeuristics, double epsilon)\n {\n if (graph == null) {\n throw new IllegalArgumentException(\"Input graph cannot be null\");\n }\n this.graph = graph;\n this.comparator = new ToleranceDoubleComparator(epsilon);\n this.useHeuristics = useHeuristics;\n }\n\n /**\n * Get a matching that is a $\\frac{1}{2}$-approximation of the maximum weighted matching.\n * \n * @return a matching\n */\n @Override\n public Matching getMatching()\n {\n if (useHeuristics) {\n return runWithHeuristics();\n } else {\n return run();\n }\n }\n\n /**\n * Compute all vertices that have positive degree by iterating over the edges on purpose. This\n * keeps the complexity to $O(m)$ where $m$ is the number of edges.\n * \n * @return set of vertices with positive degree\n */\n private Set initVisibleVertices()\n {\n Set visibleVertex = new HashSet<>();\n for (E e : graph.edgeSet()) {\n V s = graph.getEdgeSource(e);\n V t = graph.getEdgeTarget(e);\n if (!s.equals(t)) {\n visibleVertex.add(s);\n visibleVertex.add(t);\n }\n }\n return visibleVertex;\n }\n\n // the algorithm (no heuristics)\n private Matching run()\n {\n // lookup all relevant vertices\n Set visibleVertex = initVisibleVertices();\n\n // run algorithm\n Set m1 = new HashSet<>();\n Set m2 = new HashSet<>();\n double m1Weight = 0d, m2Weight = 0d;\n int i = 1;\n while (!visibleVertex.isEmpty()) {\n // find vertex arbitrarily\n V x = visibleVertex.stream().findAny().get();\n\n // grow path from x\n while (x != null) {\n // first heaviest edge incident to vertex x (among visible neighbors)\n double maxWeight = 0d;\n E maxWeightedEdge = null;\n V maxWeightedNeighbor = null;\n for (E e : graph.edgesOf(x)) {\n V other = Graphs.getOppositeVertex(graph, e, x);\n if (visibleVertex.contains(other) && !other.equals(x)) {\n double curWeight = graph.getEdgeWeight(e);\n if (comparator.compare(curWeight, 0d) > 0 && (maxWeightedEdge == null\n || comparator.compare(curWeight, maxWeight) > 0))\n {\n maxWeight = curWeight;\n maxWeightedEdge = e;\n maxWeightedNeighbor = other;\n }\n }\n }\n\n // add it to either m1 or m2, alternating between them\n if (maxWeightedEdge != null) {\n switch (i) {\n case 1:\n m1.add(maxWeightedEdge);\n m1Weight += maxWeight;\n break;\n case 2:\n m2.add(maxWeightedEdge);\n m2Weight += maxWeight;\n break;\n default:\n throw new RuntimeException(\n \"Failed to figure out matching, seems to be a bug\");\n }\n i = 3 - i;\n }\n\n // remove x and incident edges\n visibleVertex.remove(x);\n\n // go to next vertex\n x = maxWeightedNeighbor;\n }\n }\n\n // return best matching\n if (comparator.compare(m1Weight, m2Weight) > 0) {\n return new MatchingImpl<>(graph, m1, m1Weight);\n } else {\n return new MatchingImpl<>(graph, m2, m2Weight);\n }\n }\n\n // the algorithm (improved with additional heuristics)\n private Matching runWithHeuristics()\n {\n // lookup all relevant vertices\n Set visibleVertex = initVisibleVertices();\n\n // create solver for paths\n DynamicProgrammingPathSolver pathSolver = new DynamicProgrammingPathSolver();\n\n Set matching = new HashSet<>();\n double matchingWeight = 0d;\n Set matchedVertices = new HashSet<>();\n\n // run algorithm\n while (!visibleVertex.isEmpty()) {\n // find vertex arbitrarily\n V x = visibleVertex.stream().findAny().get();\n\n // grow path from x\n LinkedList path = new LinkedList<>();\n while (x != null) {\n // first heaviest edge incident to vertex x (among visible neighbors)\n double maxWeight = 0d;\n E maxWeightedEdge = null;\n V maxWeightedNeighbor = null;\n for (E e : graph.edgesOf(x)) {\n V other = Graphs.getOppositeVertex(graph, e, x);\n if (visibleVertex.contains(other) && !other.equals(x)) {\n double curWeight = graph.getEdgeWeight(e);\n if (comparator.compare(curWeight, 0d) > 0 && (maxWeightedEdge == null\n || comparator.compare(curWeight, maxWeight) > 0))\n {\n maxWeight = curWeight;\n maxWeightedEdge = e;\n maxWeightedNeighbor = other;\n }\n }\n }\n\n // add edge to path and remove x\n if (maxWeightedEdge != null) {\n path.add(maxWeightedEdge);\n }\n visibleVertex.remove(x);\n\n // go to next vertex\n x = maxWeightedNeighbor;\n }\n\n // find maximum weight matching of path using dynamic programming\n Pair> pathMatching = pathSolver.getMaximumWeightMatching(graph, path);\n\n // add it to result while keeping track of matched vertices\n matchingWeight += pathMatching.getFirst();\n for (E e : pathMatching.getSecond()) {\n V s = graph.getEdgeSource(e);\n V t = graph.getEdgeTarget(e);\n if (!matchedVertices.add(s)) {\n throw new RuntimeException(\n \"Set is not a valid matching, please submit a bug report\");\n }\n if (!matchedVertices.add(t)) {\n throw new RuntimeException(\n \"Set is not a valid matching, please submit a bug report\");\n }\n matching.add(e);\n }\n }\n\n // extend matching to maximal cardinality (out of edges with positive weight)\n for (E e : graph.edgeSet()) {\n double edgeWeight = graph.getEdgeWeight(e);\n if (comparator.compare(edgeWeight, 0d) <= 0) {\n // ignore zero or negative weight\n continue;\n }\n V s = graph.getEdgeSource(e);\n if (matchedVertices.contains(s)) {\n // matched vertex, ignore\n continue;\n }\n V t = graph.getEdgeTarget(e);\n if (matchedVertices.contains(t)) {\n // matched vertex, ignore\n continue;\n }\n // add edge to matching\n matching.add(e);\n matchingWeight += edgeWeight;\n }\n\n // return extended matching\n return new MatchingImpl<>(graph, matching, matchingWeight);\n }\n\n /**\n * Helper class for repeatedly solving the maximum weight matching on paths.\n * \n * The work array used in the dynamic programming algorithm is reused between invocations. In\n * case its size is smaller than the path provided, its length is increased. This class is not\n * thread-safe.\n */\n class DynamicProgrammingPathSolver\n {\n private static final int WORK_ARRAY_INITIAL_SIZE = 256;\n\n // work array\n private double[] a = new double[WORK_ARRAY_INITIAL_SIZE];\n\n /**\n * Find the maximum weight matching of a path using dynamic programming.\n * \n * @param path a list of edges. The code assumes that the list of edges is a valid simple\n * path, and that is not a cycle.\n * @return a maximum weight matching of the path\n */\n public Pair> getMaximumWeightMatching(Graph g, LinkedList path)\n {\n int pathLength = path.size();\n\n // special cases\n switch (pathLength) {\n case 0:\n // special case, empty path\n return Pair.of(0d, Collections.emptySet());\n case 1:\n // special case, one edge\n E e = path.getFirst();\n double eWeight = g.getEdgeWeight(e);\n if (comparator.compare(eWeight, 0d) > 0) {\n return Pair.of(eWeight, Collections.singleton(e));\n } else {\n return Pair.of(0d, Collections.emptySet());\n }\n }\n\n // make sure work array has enough space\n if (a.length < pathLength + 1) {\n a = new double[pathLength + 1];\n }\n\n // first pass to find solution\n Iterator it = path.iterator();\n E e = it.next();\n double eWeight = g.getEdgeWeight(e);\n a[0] = 0d;\n a[1] = (comparator.compare(eWeight, 0d) > 0) ? eWeight : 0d;\n for (int i = 2; i <= pathLength; i++) {\n e = it.next();\n eWeight = g.getEdgeWeight(e);\n if (comparator.compare(a[i - 1], a[i - 2] + eWeight) > 0) {\n a[i] = a[i - 1];\n } else {\n a[i] = a[i - 2] + eWeight;\n }\n }\n\n // reverse second pass to build solution\n Set matching = new HashSet<>();\n it = path.descendingIterator();\n int i = pathLength;\n while (i >= 1) {\n e = it.next();\n if (comparator.compare(a[i], a[i - 1]) > 0) {\n matching.add(e);\n // skip next edge\n if (i > 1) {\n e = it.next();\n }\n i--;\n }\n i--;\n }\n\n // return solution\n return Pair.of(a[pathLength], matching);\n }\n\n }\n\n}\n", "file_name": "PathGrowingWeightedMatching.java", "human_label": "Compute all vertices by iterating over the edges of this graph.", "level": "class_runnable", "lineno": "138", "name": "initVisibleVertices", "oracle_context": "{ \"apis\" : \"[edgeSet, getEdgeSource, getEdgeTarget, equals, add]\", \"classes\" : \"[Set, V]\", \"vars\" : \"[graph]\" }", "package": "org.jgrapht.alg.matching", "project": "jgrapht-master" }, { "_id": "636767001a6d9265ec017873", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.List;\\nimport java.util.Locale;\\nString EMPTY;\\nint INDEX_NOT_FOUND;\\nint PAD_LIMIT;\\nchar[] escapes;\\nStringUtils();\\nisNotEmpty(String str);\\nisBlank(String str);\\nisNotBlank(String str);\\ntrim(String str);\\ntrimToNull(String str);\\ntrimToEmpty(String str);\\nstrip(String str);\\nstripToNull(String str);\\nstripToEmpty(String str);\\nstrip(String str,String stripChars);\\nstripStart(String str,String stripChars);\\nstripEnd(String str,String stripChars);\\nstripAll(String[] strs);\\nstripAll(String[] strs,String stripChars);\\nequals(String str1,String str2);\\nequalsIgnoreCase(String str1,String str2);\\nindexOf(String str,char searchChar);\\nindexOf(String str,char searchChar,int startPos);\\nindexOf(String str,String searchStr);\\nordinalIndexOf(String str,String searchStr,int ordinal);\\nordinalIndexOf(String str,String searchStr,int ordinal,boolean lastIndex);\\nindexOf(String str,String searchStr,int startPos);\\nindexOfIgnoreCase(String str,String searchStr);\\nindexOfIgnoreCase(String str,String searchStr,int startPos);\\nlastIndexOf(String str,char searchChar);\\nlastIndexOf(String str,char searchChar,int startPos);\\nlastIndexOf(String str,String searchStr);\\nlastOrdinalIndexOf(String str,String searchStr,int ordinal);\\nlastIndexOf(String str,String searchStr,int startPos);\\nlastIndexOfIgnoreCase(String str,String searchStr);\\nlastIndexOfIgnoreCase(String str,String searchStr,int startPos);\\ncontains(String str,char searchChar);\\ncontains(String str,String searchStr);\\ncontainsIgnoreCase(String str,String searchStr);\\nindexOfAny(String str,char[] searchChars);\\nindexOfAny(String str,String searchChars);\\ncontainsAny(String str,char[] searchChars);\\ncontainsAny(String str,String searchChars);\\nindexOfAnyBut(String str,char[] searchChars);\\nindexOfAnyBut(String str,String searchChars);\\ncontainsOnly(String str,char[] valid);\\ncontainsOnly(String str,String validChars);\\ncontainsNone(String str,char[] searchChars);\\ncontainsNone(String str,String invalidChars);\\nindexOfAny(String str,String[] searchStrs);\\nlastIndexOfAny(String str,String[] searchStrs);\\nsubstring(String str,int start);\\nsubstring(String str,int start,int end);\\nleft(String str,int len);\\nright(String str,int len);\\nmid(String str,int pos,int len);\\nsubstringBefore(String str,String separator);\\nsubstringAfter(String str,String separator);\\nsubstringBeforeLast(String str,String separator);\\nsubstringAfterLast(String str,String separator);\\nsubstringBetween(String str,String tag);\\nsubstringBetween(String str,String open,String close);\\nsubstringsBetween(String str,String open,String close);\\nsplitKeep(String str,char separatorChar);\\nsplitKeep(String str,String separatorStr);\\nsplit(String str);\\nsplit(String str,char separatorChar);\\nsplit(String str,String separatorChars);\\nsplit(String str,String separatorChars,int max);\\nsplitByWholeSeparator(String str,String separator);\\nsplitByWholeSeparator(String str,String separator,int max);\\nsplitByWholeSeparatorPreserveAllTokens(String str,String separator);\\nsplitByWholeSeparatorPreserveAllTokens(String str,String separator,int max);\\nsplitByWholeSeparatorWorker(String str,String separator,int max,boolean preserveAllTokens);\\nsplitPreserveAllTokens(String str);\\nsplitPreserveAllTokens(String str,char separatorChar);\\nsplitWorker(String str,char separatorChar,boolean preserveAllTokens);\\nsplitPreserveAllTokens(String str,String separatorChars);\\nsplitPreserveAllTokens(String str,String separatorChars,int max);\\nsplitWorker(String str,String separatorChars,int max,boolean preserveAllTokens);\\nsplitByCharacterType(String str);\\nsplitByCharacterTypeCamelCase(String str);\\nsplitByCharacterType(String str,boolean camelCase);\\njoin(Object[] array);\\njoin(Object[] array,char separator);\\njoin(Object[] array,char separator,int startIndex,int endIndex);\\njoin(Object[] array,String separator);\\njoin(Object[] array,String separator,int startIndex,int endIndex);\\ndeleteWhitespace(String str);\\nremoveStart(String str,String remove);\\nremoveStartIgnoreCase(String str,String remove);\\nremoveEnd(String str,String remove);\\nremoveEndIgnoreCase(String str,String remove);\\nremove(String str,String remove);\\nremove(String str,char remove);\\nreplaceOnce(String text,String searchString,String replacement);\\nreplace(String text,String searchString,String replacement);\\nreplace(String text,String searchString,String replacement,int max);\\nreplaceEach(String text,String[] searchList,String[] replacementList);\\nreplaceEachRepeatedly(String text,String[] searchList,String[] replacementList);\\nreplaceEach(String text,String[] searchList,String[] replacementList,boolean repeat,int timeToLive);\\nreplaceChars(String str,char searchChar,char replaceChar);\\nreplaceChars(String str,String searchChars,String replaceChars);\\noverlay(String str,String overlay,int start,int end);\\nchomp(String str);\\nchomp(String str,String separator);\\nchop(String str);\\nrepeat(char character,int repeat);\\nrepeat(String str,int repeat);\\nrepeat(String str,String separator,int repeat);\\npadding(int repeat,char padChar);\\nrightPad(String str,int size);\\nrightPad(String str,int size,char padChar);\\nrightPad(String str,int size,String padStr);\\nleftPad(String str,int size);\\nleftPad(String str,int size,char padChar);\\nleftPad(String str,int size,String padStr);\\nlength(String str);\\ncenter(String str,int size);\\ncenter(String str,int size,char padChar);\\ncenter(String str,int size,String padStr);\\nupperCase(String str);\\nupperCase(String str,Locale locale);\\nlowerCase(String str);\\nlowerCase(String str,Locale locale);\\ncapitalize(String str);\\nuncapitalize(String str);\\nswapCase(String str);\\ncountMatches(String str,String sub);\\nisAlpha(String str);\\nisAlphaSpace(String str);\\nisAlphanumeric(String str);\\nisAlphanumericSpace(String str);\\nisAsciiPrintable(String str);\\nisNumeric(String str);\\nisNumericSpace(String str);\\nisWhitespace(String str);\\nisAllLowerCase(String str);\\nisAllUpperCase(String str);\\ndefaultString(String str);\\ndefaultString(String str,String defaultStr);\\ndefaultIfBlank(String str,String defaultStr);\\ndefaultIfEmpty(String str,String defaultStr);\\nreverse(String str);\\nreverseDelimited(String str,char separatorChar);\\nabbreviate(String str,int maxWidth);\\nabbreviate(String str,int offset,int maxWidth);\\nabbreviateMiddle(String str,String middle,int length);\\ndifference(String str1,String str2);\\nindexOfDifference(String str1,String str2);\\nindexOfDifference(String[] strs);\\ngetCommonPrefix(String[] strs);\\ngetLevenshteinDistance(String s,String t);\\nstartsWith(String str,String prefix);\\nstartsWithIgnoreCase(String str,String prefix);\\nstartsWith(String str,String prefix,boolean ignoreCase);\\nstartsWithAny(String string,String[] searchStrings);\\nendsWith(String str,String suffix);\\nendsWithIgnoreCase(String str,String suffix);\\nendsWith(String str,String suffix,boolean ignoreCase);\\nnormalizeSpace(String str);\\nendsWithAny(String string,String[] searchStrings);\\nfirstCharToUpperCase(String value);\\nfirstCharToLowerCase(String value);\\nequalsBlankIgnoreCase(String str1,String str2);\\nquote(String input);\\nquote(Appendable buffer,String input);\\ntoString(Object object);\\nisEmpty(String str);\\n\", \"repo_level\" : \"\" }", "class_name": "StringUtils", "code": "public static String reverse(final String str){\n if (str == null) {\n return null;\n }\n return new StringBuilder(str).reverse().toString();\n}\n", "docstring": "/** \n *

Reverses a String as per {@link StringBuilder#reverse()}.

A null String returns null.

 StringUtils.reverse(null)  = null StringUtils.reverse(\"\")    = \"\" StringUtils.reverse(\"bat\") = \"tab\" 
\n * @param str the String to reverse, may be null\n * @return the reversed String, null if null String input\n */\n", "end_lineno": "5272", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Locale;\n\n/**\n *

Operations on {@link String} that are\n * null safe.

\n *\n *
    \n *
  • IsEmpty/IsBlank\n * - checks if a String contains text
  • \n *
  • Trim/Strip\n * - removes leading and trailing whitespace
  • \n *
  • Equals\n * - compares two strings null-safe
  • \n *
  • startsWith\n * - check if a String starts with a prefix null-safe
  • \n *
  • endsWith\n * - check if a String ends with a suffix null-safe
  • \n *
  • IndexOf/LastIndexOf/Contains\n * - null-safe index-of checks\n *
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut\n * - index-of any of a set of Strings
  • \n *
  • ContainsOnly/ContainsNone/ContainsAny\n * - does String contains only/none/any of these characters
  • \n *
  • Substring/Left/Right/Mid\n * - null-safe substring extractions
  • \n *
  • SubstringBefore/SubstringAfter/SubstringBetween\n * - substring extraction relative to other strings
  • \n *
  • Split/Join\n * - splits a String into an array of substrings and vice versa
  • \n *
  • Remove/Delete\n * - removes part of a String
  • \n *
  • Replace/Overlay\n * - Searches a String and replaces one String with another
  • \n *
  • Chomp/Chop\n * - removes the last part of a String
  • \n *
  • LeftPad/RightPad/Center/Repeat\n * - pads a String
  • \n *
  • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize\n * - changes the case of a String
  • \n *
  • CountMatches\n * - counts the number of occurrences of one String in another
  • \n *
  • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable\n * - checks the characters in a String
  • \n *
  • DefaultString\n * - protects against a null input String
  • \n *
  • Reverse/ReverseDelimited\n * - reverses a String
  • \n *
  • Abbreviate\n * - abbreviates a string using ellipsis
  • \n *
  • Difference\n * - compares Strings and reports on their differences
  • \n *
  • LevensteinDistance\n * - the number of changes needed to change one String into another
  • \n *
\n *\n *

The StringUtils class defines certain words related to\n * String handling.

\n *\n *
    \n *
  • null - null
  • \n *
  • empty - a zero-length string (\"\")
  • \n *
  • space - the space character (' ', char 32)
  • \n *
  • whitespace - the characters defined by {@link Character#isWhitespace(char)}
  • \n *
  • trim - the characters <= 32 as in {@link String#trim()}
  • \n *
\n *\n *

StringUtils handles null input Strings quietly.\n * That is to say that a null input will return null.\n * Where a boolean or int is being returned\n * details vary by method.

\n *\n *

A side effect of the null handling is that a\n * NullPointerException should be considered a bug in\n * StringUtils (except for deprecated methods).

\n *\n *

Methods in this class give sample code to explain their operation.\n * The symbol * is used to indicate any input including null.

\n *\n *

#ThreadSafe#

\n * @see String\n * @author Apache Software Foundation\n * @author Apache Jakarta Turbine\n * @author Jon S. Stevens\n * @author Daniel L. Rall\n * @author Greg Coladonato\n * @author Ed Korthof\n * @author Rand McNeely\n * @author Fredrik Westermarck\n * @author Holger Krauth\n * @author Alexander Day Chaffee\n * @author Henning P. Schmiedehausen\n * @author Arun Mammen Thomas\n * @author Gary Gregory\n * @author Phil Steitz\n * @author Al Chou\n * @author Michael Davey\n * @author Reuben Sivan\n * @author Chris Hyzer\n * @author Scott Johnson\n * @since 1.0\n * @version $Id: StringUtils.java 1058365 2011-01-13 00:04:49Z niallp $\n */\n//@Immutable\npublic class StringUtils {\n // Performance testing notes (JDK 1.4, Jul03, scolebourne)\n // Whitespace:\n // Character.isWhitespace() is faster than WHITESPACE.indexOf()\n // where WHITESPACE is a string of all whitespace characters\n //\n // Character access:\n // String.charAt(n) versus toCharArray(), then array[n]\n // String.charAt(n) is about 15% worse for a 10K string\n // They are about equal for a length 50 string\n // String.charAt(n) is about 4 times better for a length 3 string\n // String.charAt(n) is best bet overall\n //\n // Append:\n // String.concat about twice as fast as StringBuffer.append\n // (not sure who tested this)\n /**\n * The empty String \"\".\n * @since 2.0\n */\n public static final String EMPTY = \"\";\n /**\n * Represents a failed index search.\n * @since 2.1\n */\n public static final int INDEX_NOT_FOUND = -1;\n /**\n *

The maximum size to which the padding constant(s) can expand.

\n */\n private static final int PAD_LIMIT = 8192;\n\n /**\n *

StringUtils instances should NOT be constructed in\n * standard programming. Instead, the class should be used as\n * StringUtils.trim(\" foo \");.

\n *\n *

This constructor is public to permit tools that require a JavaBean\n * instance to operate.

\n */\n public StringUtils() {\n super();\n }\n // Empty checks\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if a String is empty (\"\") or null.

\n *\n *
\n     * StringUtils.isEmpty(null)      = true\n     * StringUtils.isEmpty(\"\")        = true\n     * StringUtils.isEmpty(\" \")       = false\n     * StringUtils.isEmpty(\"bob\")     = false\n     * StringUtils.isEmpty(\"  bob  \") = false\n     * 
\n *\n *

NOTE: This method changed in Lang version 2.0.\n * It no longer trims the String.\n * That functionality is available in isBlank().

\n *\n * @param str the String to check, may be null\n * @return true if the String is empty or null\n */\n public static boolean isEmpty(final String str) {\n return str == null || str.length() == 0;\n }\n\n /**\n *

Checks if a String is not empty (\"\") and not null.

\n *\n *
\n     * StringUtils.isNotEmpty(null)      = false\n     * StringUtils.isNotEmpty(\"\")        = false\n     * StringUtils.isNotEmpty(\" \")       = true\n     * StringUtils.isNotEmpty(\"bob\")     = true\n     * StringUtils.isNotEmpty(\"  bob  \") = true\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if the String is not empty and not null\n */\n public static boolean isNotEmpty(final String str) {\n return !StringUtils.isEmpty(str);\n }\n\n /**\n *

Checks if a String is whitespace, empty (\"\") or null.

\n *\n *
\n     * StringUtils.isBlank(null)      = true\n     * StringUtils.isBlank(\"\")        = true\n     * StringUtils.isBlank(\" \")       = true\n     * StringUtils.isBlank(\"bob\")     = false\n     * StringUtils.isBlank(\"  bob  \") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if the String is null, empty or whitespace\n * @since 2.0\n */\n public static boolean isBlank(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return true;\n }\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i)) == false) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if a String is not empty (\"\"), not null and not whitespace only.

\n *\n *
\n     * StringUtils.isNotBlank(null)      = false\n     * StringUtils.isNotBlank(\"\")        = false\n     * StringUtils.isNotBlank(\" \")       = false\n     * StringUtils.isNotBlank(\"bob\")     = true\n     * StringUtils.isNotBlank(\"  bob  \") = true\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if the String is\n * not empty and not null and not whitespace\n * @since 2.0\n */\n public static boolean isNotBlank(final String str) {\n return !StringUtils.isBlank(str);\n }\n // Trim\n //-----------------------------------------------------------------------\n\n /**\n *

Removes control characters (char <= 32) from both\n * ends of this String, handling null by returning\n * null.

\n *\n *

The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #strip(String)}.

\n *\n *

To trim your choice of characters, use the\n * {@link #strip(String, String)} methods.

\n *\n *
\n     * StringUtils.trim(null)          = null\n     * StringUtils.trim(\"\")            = \"\"\n     * StringUtils.trim(\"     \")       = \"\"\n     * StringUtils.trim(\"abc\")         = \"abc\"\n     * StringUtils.trim(\"    abc    \") = \"abc\"\n     * 
\n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed string, null if null String input\n */\n public static String trim(final String str) {\n return str == null ? null : str.trim();\n }\n\n /**\n *

Removes control characters (char <= 32) from both\n * ends of this String returning null if the String is\n * empty (\"\") after the trim or if it is null.\n *\n *

The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #stripToNull(String)}.

\n *\n *
\n     * StringUtils.trimToNull(null)          = null\n     * StringUtils.trimToNull(\"\")            = null\n     * StringUtils.trimToNull(\"     \")       = null\n     * StringUtils.trimToNull(\"abc\")         = \"abc\"\n     * StringUtils.trimToNull(\"    abc    \") = \"abc\"\n     * 
\n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed String,\n * null if only chars <= 32, empty or null String input\n * @since 2.0\n */\n public static String trimToNull(final String str) {\n String ts = StringUtils.trim(str);\n return StringUtils.isEmpty(ts) ? null : ts;\n }\n\n /**\n *

Removes control characters (char <= 32) from both\n * ends of this String returning an empty String (\"\") if the String\n * is empty (\"\") after the trim or if it is null.\n *\n *

The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #stripToEmpty(String)}.

\n *\n *
\n     * StringUtils.trimToEmpty(null)          = \"\"\n     * StringUtils.trimToEmpty(\"\")            = \"\"\n     * StringUtils.trimToEmpty(\"     \")       = \"\"\n     * StringUtils.trimToEmpty(\"abc\")         = \"abc\"\n     * StringUtils.trimToEmpty(\"    abc    \") = \"abc\"\n     * 
\n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed String, or an empty String if null input\n * @since 2.0\n */\n public static String trimToEmpty(final String str) {\n return str == null ? StringUtils.EMPTY : str.trim();\n }\n // Stripping\n //-----------------------------------------------------------------------\n\n /**\n *

Strips whitespace from the start and end of a String.

\n *\n *

This is similar to {@link #trim(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.strip(null)     = null\n     * StringUtils.strip(\"\")       = \"\"\n     * StringUtils.strip(\"   \")    = \"\"\n     * StringUtils.strip(\"abc\")    = \"abc\"\n     * StringUtils.strip(\"  abc\")  = \"abc\"\n     * StringUtils.strip(\"abc  \")  = \"abc\"\n     * StringUtils.strip(\" abc \")  = \"abc\"\n     * StringUtils.strip(\" ab c \") = \"ab c\"\n     * 
\n *\n * @param str the String to remove whitespace from, may be null\n * @return the stripped String, null if null String input\n */\n public static String strip(final String str) {\n return StringUtils.strip(str, null);\n }\n\n /**\n *

Strips whitespace from the start and end of a String returning\n * null if the String is empty (\"\") after the strip.

\n *\n *

This is similar to {@link #trimToNull(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripToNull(null)     = null\n     * StringUtils.stripToNull(\"\")       = null\n     * StringUtils.stripToNull(\"   \")    = null\n     * StringUtils.stripToNull(\"abc\")    = \"abc\"\n     * StringUtils.stripToNull(\"  abc\")  = \"abc\"\n     * StringUtils.stripToNull(\"abc  \")  = \"abc\"\n     * StringUtils.stripToNull(\" abc \")  = \"abc\"\n     * StringUtils.stripToNull(\" ab c \") = \"ab c\"\n     * 
\n *\n * @param str the String to be stripped, may be null\n * @return the stripped String,\n * null if whitespace, empty or null String input\n * @since 2.0\n */\n public static String stripToNull(String str) {\n if (str == null) {\n return null;\n }\n str = StringUtils.strip(str, null);\n return str.length() == 0 ? null : str;\n }\n\n /**\n *

Strips whitespace from the start and end of a String returning\n * an empty String if null input.

\n *\n *

This is similar to {@link #trimToEmpty(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripToEmpty(null)     = \"\"\n     * StringUtils.stripToEmpty(\"\")       = \"\"\n     * StringUtils.stripToEmpty(\"   \")    = \"\"\n     * StringUtils.stripToEmpty(\"abc\")    = \"abc\"\n     * StringUtils.stripToEmpty(\"  abc\")  = \"abc\"\n     * StringUtils.stripToEmpty(\"abc  \")  = \"abc\"\n     * StringUtils.stripToEmpty(\" abc \")  = \"abc\"\n     * StringUtils.stripToEmpty(\" ab c \") = \"ab c\"\n     * 
\n *\n * @param str the String to be stripped, may be null\n * @return the trimmed String, or an empty String if null input\n * @since 2.0\n */\n public static String stripToEmpty(final String str) {\n return str == null ? StringUtils.EMPTY : StringUtils.strip(str, null);\n }\n\n /**\n *

Strips any of a set of characters from the start and end of a String.\n * This is similar to {@link String#trim()} but allows the characters\n * to be stripped to be controlled.

\n *\n *

A null input String returns null.\n * An empty string (\"\") input returns the empty string.

\n *\n *

If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.\n * Alternatively use {@link #strip(String)}.

\n *\n *
\n     * StringUtils.strip(null, *)          = null\n     * StringUtils.strip(\"\", *)            = \"\"\n     * StringUtils.strip(\"abc\", null)      = \"abc\"\n     * StringUtils.strip(\"  abc\", null)    = \"abc\"\n     * StringUtils.strip(\"abc  \", null)    = \"abc\"\n     * StringUtils.strip(\" abc \", null)    = \"abc\"\n     * StringUtils.strip(\"  abcyx\", \"xyz\") = \"  abc\"\n     * 
\n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String strip(String str, final String stripChars) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n str = StringUtils.stripStart(str, stripChars);\n return StringUtils.stripEnd(str, stripChars);\n }\n\n /**\n *

Strips any of a set of characters from the start of a String.

\n *\n *

A null input String returns null.\n * An empty string (\"\") input returns the empty string.

\n *\n *

If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripStart(null, *)          = null\n     * StringUtils.stripStart(\"\", *)            = \"\"\n     * StringUtils.stripStart(\"abc\", \"\")        = \"abc\"\n     * StringUtils.stripStart(\"abc\", null)      = \"abc\"\n     * StringUtils.stripStart(\"  abc\", null)    = \"abc\"\n     * StringUtils.stripStart(\"abc  \", null)    = \"abc  \"\n     * StringUtils.stripStart(\" abc \", null)    = \"abc \"\n     * StringUtils.stripStart(\"yxabc  \", \"xyz\") = \"abc  \"\n     * 
\n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String stripStart(final String str, final String stripChars) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n int start = 0;\n if (stripChars == null) {\n while (start != strLen && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n } else if (stripChars.length() == 0) {\n return str;\n } else {\n while (start != strLen && stripChars.indexOf(str.charAt(start)) != StringUtils.INDEX_NOT_FOUND) {\n start++;\n }\n }\n return str.substring(start);\n }\n\n /**\n *

Strips any of a set of characters from the end of a String.

\n *\n *

A null input String returns null.\n * An empty string (\"\") input returns the empty string.

\n *\n *

If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripEnd(null, *)          = null\n     * StringUtils.stripEnd(\"\", *)            = \"\"\n     * StringUtils.stripEnd(\"abc\", \"\")        = \"abc\"\n     * StringUtils.stripEnd(\"abc\", null)      = \"abc\"\n     * StringUtils.stripEnd(\"  abc\", null)    = \"  abc\"\n     * StringUtils.stripEnd(\"abc  \", null)    = \"abc\"\n     * StringUtils.stripEnd(\" abc \", null)    = \" abc\"\n     * StringUtils.stripEnd(\"  abcyx\", \"xyz\") = \"  abc\"\n     * StringUtils.stripEnd(\"120.00\", \".0\")   = \"12\"\n     * 
\n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the set of characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String stripEnd(final String str, final String stripChars) {\n int end;\n if (str == null || (end = str.length()) == 0) {\n return str;\n }\n if (stripChars == null) {\n while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n } else if (stripChars.length() == 0) {\n return str;\n } else {\n while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != StringUtils.INDEX_NOT_FOUND) {\n end--;\n }\n }\n return str.substring(0, end);\n }\n // StripAll\n //-----------------------------------------------------------------------\n\n /**\n *

Strips whitespace from the start and end of every String in an array.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

A new array is returned each time, except for length zero.\n * A null array will return null.\n * An empty array will return itself.\n * A null array entry will be ignored.

\n *\n *
\n     * StringUtils.stripAll(null)             = null\n     * StringUtils.stripAll([])               = []\n     * StringUtils.stripAll([\"abc\", \"  abc\"]) = [\"abc\", \"abc\"]\n     * StringUtils.stripAll([\"abc  \", null])  = [\"abc\", null]\n     * 
\n *\n * @param strs the array to remove whitespace from, may be null\n * @return the stripped Strings, null if null array input\n */\n public static String[] stripAll(final String[] strs) {\n return StringUtils.stripAll(strs, null);\n }\n\n /**\n *

Strips any of a set of characters from the start and end of every\n * String in an array.

\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

A new array is returned each time, except for length zero.\n * A null array will return null.\n * An empty array will return itself.\n * A null array entry will be ignored.\n * A null stripChars will strip whitespace as defined by\n * {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripAll(null, *)                = null\n     * StringUtils.stripAll([], *)                  = []\n     * StringUtils.stripAll([\"abc\", \"  abc\"], null) = [\"abc\", \"abc\"]\n     * StringUtils.stripAll([\"abc  \", null], null)  = [\"abc\", null]\n     * StringUtils.stripAll([\"abc  \", null], \"yz\")  = [\"abc  \", null]\n     * StringUtils.stripAll([\"yabcz\", null], \"yz\")  = [\"abc\", null]\n     * 
\n *\n * @param strs the array to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped Strings, null if null array input\n */\n public static String[] stripAll(final String[] strs, final String stripChars) {\n int strsLen;\n if (strs == null || (strsLen = strs.length) == 0) {\n return strs;\n }\n String[] newArr = new String[strsLen];\n for (int i = 0; i < strsLen; i++) {\n newArr[i] = StringUtils.strip(strs[i], stripChars);\n }\n return newArr;\n }\n // Equals\n //-----------------------------------------------------------------------\n\n /**\n *

Compares two Strings, returning true if they are equal.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

\n *\n *
\n     * StringUtils.equals(null, null)   = true\n     * StringUtils.equals(null, \"abc\")  = false\n     * StringUtils.equals(\"abc\", null)  = false\n     * StringUtils.equals(\"abc\", \"abc\") = true\n     * StringUtils.equals(\"abc\", \"ABC\") = false\n     * 
\n *\n * @see String#equals(Object)\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return true if the Strings are equal, case sensitive, or\n * both null\n */\n public static boolean equals(final String str1, final String str2) {\n return str1 == null ? str2 == null : str1.equals(str2);\n }\n\n /**\n *

Compares two Strings, returning true if they are equal ignoring\n * the case.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered equal. Comparison is case insensitive.

\n *\n *
\n     * StringUtils.equalsIgnoreCase(null, null)   = true\n     * StringUtils.equalsIgnoreCase(null, \"abc\")  = false\n     * StringUtils.equalsIgnoreCase(\"abc\", null)  = false\n     * StringUtils.equalsIgnoreCase(\"abc\", \"abc\") = true\n     * StringUtils.equalsIgnoreCase(\"abc\", \"ABC\") = true\n     * 
\n *\n * @see String#equalsIgnoreCase(String)\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return true if the Strings are equal, case insensitive, or\n * both null\n */\n public static boolean equalsIgnoreCase(final String str1, final String str2) {\n return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);\n }\n // IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(int)}.

\n *\n *

A null or empty (\"\") String will return INDEX_NOT_FOUND (-1).

\n *\n *
\n     * StringUtils.indexOf(null, *)         = -1\n     * StringUtils.indexOf(\"\", *)           = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'a') = 0\n     * StringUtils.indexOf(\"aabaabaa\", 'b') = 2\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return the first index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchChar);\n }\n\n /**\n *

Finds the first index within a String from a start position,\n * handling null.\n * This method uses {@link String#indexOf(int, int)}.

\n *\n *

A null or empty (\"\") String will return (INDEX_NOT_FOUND) -1.\n * A negative start position is treated as zero.\n * A start position greater than the string length returns -1.

\n *\n *
\n     * StringUtils.indexOf(null, *, *)          = -1\n     * StringUtils.indexOf(\"\", *, *)            = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 0)  = 2\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 3)  = 5\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 9)  = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'b', -1) = 2\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final char searchChar, final int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchChar, startPos);\n }\n\n /**\n *

Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n *
\n     * StringUtils.indexOf(null, *)          = -1\n     * StringUtils.indexOf(*, null)          = -1\n     * StringUtils.indexOf(\"\", \"\")           = 0\n     * StringUtils.indexOf(\"\", *)            = -1 (except when * = \"\")\n     * StringUtils.indexOf(\"aabaabaa\", \"a\")  = 0\n     * StringUtils.indexOf(\"aabaabaa\", \"b\")  = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"ab\") = 1\n     * StringUtils.indexOf(\"aabaabaa\", \"\")   = 0\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr);\n }\n\n /**\n *

Finds the n-th index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n *
\n     * StringUtils.ordinalIndexOf(null, *, *)          = -1\n     * StringUtils.ordinalIndexOf(*, null, *)          = -1\n     * StringUtils.ordinalIndexOf(\"\", \"\", *)           = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"a\", 1)  = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"a\", 2)  = 1\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"b\", 1)  = 2\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"b\", 2)  = 5\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"ab\", 1) = 1\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"ab\", 2) = 4\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"\", 1)   = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"\", 2)   = 0\n     * 
\n *\n *

Note that 'head(String str, int n)' may be implemented as:

\n *\n *
\n     *   str.substring(0, lastOrdinalIndexOf(str, \"\\n\", n))\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th searchStr to find\n * @return the n-th index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n * @since 2.1\n */\n public static int ordinalIndexOf(final String str, final String searchStr, final int ordinal) {\n return StringUtils.ordinalIndexOf(str, searchStr, ordinal, false);\n }\n\n /**\n *

Finds the n-th index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th searchStr to find\n * @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf()\n * @return the n-th index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n */\n // Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int)\n private static int ordinalIndexOf(final String str, final String searchStr, final int ordinal, final boolean lastIndex) {\n if (str == null || searchStr == null || ordinal <= 0) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return lastIndex ? str.length() : 0;\n }\n int found = 0;\n int index = lastIndex ? str.length() : StringUtils.INDEX_NOT_FOUND;\n do {\n if (lastIndex) {\n index = str.lastIndexOf(searchStr, index - 1);\n } else {\n index = str.indexOf(searchStr, index + 1);\n }\n if (index < 0) {\n return index;\n }\n found++;\n } while (found < ordinal);\n return index;\n }\n\n /**\n *

Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(String, int)}.

\n *\n *

A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

\n *\n *
\n     * StringUtils.indexOf(null, *, *)          = -1\n     * StringUtils.indexOf(*, null, *)          = -1\n     * StringUtils.indexOf(\"\", \"\", 0)           = 0\n     * StringUtils.indexOf(\"\", *, 0)            = -1 (except when * = \"\")\n     * StringUtils.indexOf(\"aabaabaa\", \"a\", 0)  = 0\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 0)  = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"ab\", 0) = 1\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 3)  = 5\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 9)  = -1\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", -1) = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"\", 2)   = 2\n     * StringUtils.indexOf(\"abc\", \"\", 9)        = 3\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final String searchStr, final int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n // JDK1.2/JDK1.3 have a bug, when startPos > str.length for \"\", hence\n if (searchStr.length() == 0 && startPos >= str.length()) {\n return str.length();\n }\n return str.indexOf(searchStr, startPos);\n }\n\n /**\n *

Case in-sensitive find of the first index within a String.

\n *\n *

A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

\n *\n *
\n     * StringUtils.indexOfIgnoreCase(null, *)          = -1\n     * StringUtils.indexOfIgnoreCase(*, null)          = -1\n     * StringUtils.indexOfIgnoreCase(\"\", \"\")           = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"a\")  = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"b\")  = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"ab\") = 1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int indexOfIgnoreCase(final String str, final String searchStr) {\n return StringUtils.indexOfIgnoreCase(str, searchStr, 0);\n }\n\n /**\n *

Case in-sensitive find of the first index within a String\n * from the specified position.

\n *\n *

A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

\n *\n *
\n     * StringUtils.indexOfIgnoreCase(null, *, *)          = -1\n     * StringUtils.indexOfIgnoreCase(*, null, *)          = -1\n     * StringUtils.indexOfIgnoreCase(\"\", \"\", 0)           = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"A\", 0)  = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 0)  = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"AB\", 0) = 1\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 3)  = 5\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 9)  = -1\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", -1) = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"\", 2)   = 2\n     * StringUtils.indexOfIgnoreCase(\"abc\", \"\", 9)        = 3\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int indexOfIgnoreCase(final String str, final String searchStr, int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (startPos < 0) {\n startPos = 0;\n }\n int endLimit = str.length() - searchStr.length() + 1;\n if (startPos > endLimit) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return startPos;\n }\n for (int i = startPos; i < endLimit; i++) {\n if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {\n return i;\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // LastIndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(int)}.

\n *\n *

A null or empty (\"\") String will return -1.

\n *\n *
\n     * StringUtils.lastIndexOf(null, *)         = -1\n     * StringUtils.lastIndexOf(\"\", *)           = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'a') = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b') = 5\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return the last index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar);\n }\n\n /**\n *

Finds the last index within a String from a start position,\n * handling null.\n * This method uses {@link String#lastIndexOf(int, int)}.

\n *\n *

A null or empty (\"\") String will return -1.\n * A negative start position returns -1.\n * A start position greater than the string length searches the whole string.

\n *\n *
\n     * StringUtils.lastIndexOf(null, *, *)          = -1\n     * StringUtils.lastIndexOf(\"\", *,  *)           = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 8)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 4)  = 2\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 0)  = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 9)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', -1) = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'a', 0)  = 0\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @param startPos the start position\n * @return the last index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final char searchChar, final int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar, startPos);\n }\n\n /**\n *

Finds the last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n *
\n     * StringUtils.lastIndexOf(null, *)          = -1\n     * StringUtils.lastIndexOf(*, null)          = -1\n     * StringUtils.lastIndexOf(\"\", \"\")           = 0\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\")  = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\")  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"ab\") = 4\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"\")   = 8\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the last index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr);\n }\n\n /**\n *

Finds the n-th last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n *
\n     * StringUtils.lastOrdinalIndexOf(null, *, *)          = -1\n     * StringUtils.lastOrdinalIndexOf(*, null, *)          = -1\n     * StringUtils.lastOrdinalIndexOf(\"\", \"\", *)           = 0\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"a\", 1)  = 7\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"a\", 2)  = 6\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"b\", 1)  = 5\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"b\", 2)  = 2\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"ab\", 1) = 4\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"ab\", 2) = 1\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"\", 1)   = 8\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"\", 2)   = 8\n     * 
\n *\n *

Note that 'tail(String str, int n)' may be implemented as:

\n *\n *
\n     *   str.substring(lastOrdinalIndexOf(str, \"\\n\", n) + 1)\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th last searchStr to find\n * @return the n-th last index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n * @since 2.5\n */\n public static int lastOrdinalIndexOf(final String str, final String searchStr, final int ordinal) {\n return StringUtils.ordinalIndexOf(str, searchStr, ordinal, true);\n }\n\n /**\n *

Finds the first index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String, int)}.

\n *\n *

A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

\n *\n *
\n     * StringUtils.lastIndexOf(null, *, *)          = -1\n     * StringUtils.lastIndexOf(*, null, *)          = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\", 8)  = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 8)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"ab\", 8) = 4\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 9)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", -1) = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\", 0)  = 0\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 0)  = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final String searchStr, final int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr, startPos);\n }\n\n /**\n *

Case in-sensitive find of the last index within a String.

\n *\n *

A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

\n *\n *
\n     * StringUtils.lastIndexOfIgnoreCase(null, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(*, null)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\")  = 7\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\")  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"AB\") = 4\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int lastIndexOfIgnoreCase(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return StringUtils.lastIndexOfIgnoreCase(str, searchStr, str.length());\n }\n\n /**\n *

Case in-sensitive find of the last index within a String\n * from the specified position.

\n *\n *

A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

\n *\n *
\n     * StringUtils.lastIndexOfIgnoreCase(null, *, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(*, null, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\", 8)  = 7\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 8)  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"AB\", 8) = 4\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 9)  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", -1) = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\", 0)  = 0\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 0)  = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int lastIndexOfIgnoreCase(final String str, final String searchStr, int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (startPos > str.length() - searchStr.length()) {\n startPos = str.length() - searchStr.length();\n }\n if (startPos < 0) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return startPos;\n }\n for (int i = startPos; i >= 0; i--) {\n if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {\n return i;\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // Contains\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if String contains a search character, handling null.\n * This method uses {@link String#indexOf(int)}.

\n *\n *

A null or empty (\"\") String will return false.

\n *\n *
\n     * StringUtils.contains(null, *)    = false\n     * StringUtils.contains(\"\", *)      = false\n     * StringUtils.contains(\"abc\", 'a') = true\n     * StringUtils.contains(\"abc\", 'z') = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return true if the String contains the search character,\n * false if not or null string input\n * @since 2.0\n */\n public static boolean contains(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return false;\n }\n return str.indexOf(searchChar) >= 0;\n }\n\n /**\n *

Checks if String contains a search String, handling null.\n * This method uses {@link String#indexOf(String)}.

\n *\n *

A null String will return false.

\n *\n *
\n     * StringUtils.contains(null, *)     = false\n     * StringUtils.contains(*, null)     = false\n     * StringUtils.contains(\"\", \"\")      = true\n     * StringUtils.contains(\"abc\", \"\")   = true\n     * StringUtils.contains(\"abc\", \"a\")  = true\n     * StringUtils.contains(\"abc\", \"z\")  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return true if the String contains the search String,\n * false if not or null string input\n * @since 2.0\n */\n public static boolean contains(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n return str.contains(searchStr);\n }\n\n /**\n *

Checks if String contains a search String irrespective of case,\n * handling null. Case-insensitivity is defined as by\n * {@link String#equalsIgnoreCase(String)}.\n *\n *

A null String will return false.

\n *\n *
\n     * StringUtils.contains(null, *) = false\n     * StringUtils.contains(*, null) = false\n     * StringUtils.contains(\"\", \"\") = true\n     * StringUtils.contains(\"abc\", \"\") = true\n     * StringUtils.contains(\"abc\", \"a\") = true\n     * StringUtils.contains(\"abc\", \"z\") = false\n     * StringUtils.contains(\"abc\", \"A\") = true\n     * StringUtils.contains(\"abc\", \"Z\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return true if the String contains the search String irrespective of\n * case or false if not or null string input\n */\n public static boolean containsIgnoreCase(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n int len = searchStr.length();\n int max = str.length() - len;\n for (int i = 0; i <= max; i++) {\n if (str.regionMatches(true, i, searchStr, 0, len)) {\n return true;\n }\n }\n return false;\n }\n // IndexOfAny chars\n //-----------------------------------------------------------------------\n\n /**\n *

Search a String to find the first index of any\n * character in the given set of characters.

\n *\n *

A null String will return -1.\n * A null or zero length search array will return -1.

\n *\n *
\n     * StringUtils.indexOfAny(null, *)                = -1\n     * StringUtils.indexOfAny(\"\", *)                  = -1\n     * StringUtils.indexOfAny(*, null)                = -1\n     * StringUtils.indexOfAny(*, [])                  = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\",['z','a']) = 0\n     * StringUtils.indexOfAny(\"zzabyycdxx\",['b','y']) = 3\n     * StringUtils.indexOfAny(\"aba\", ['z'])           = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAny(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) {\n // ch is a supplementary character\n if (searchChars[j + 1] == str.charAt(i + 1)) {\n return i;\n }\n } else {\n return i;\n }\n }\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Search a String to find the first index of any\n * character in the given set of characters.

\n *\n *

A null String will return -1.\n * A null search string will return -1.

\n *\n *
\n     * StringUtils.indexOfAny(null, *)            = -1\n     * StringUtils.indexOfAny(\"\", *)              = -1\n     * StringUtils.indexOfAny(*, null)            = -1\n     * StringUtils.indexOfAny(*, \"\")              = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", \"za\") = 0\n     * StringUtils.indexOfAny(\"zzabyycdxx\", \"by\") = 3\n     * StringUtils.indexOfAny(\"aba\",\"z\")          = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAny(final String str, final String searchChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return StringUtils.indexOfAny(str, searchChars.toCharArray());\n }\n // ContainsAny\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if the String contains any character in the given\n * set of characters.

\n *\n *

A null String will return false.\n * A null or zero length search array will return false.

\n *\n *
\n     * StringUtils.containsAny(null, *)                = false\n     * StringUtils.containsAny(\"\", *)                  = false\n     * StringUtils.containsAny(*, null)                = false\n     * StringUtils.containsAny(*, [])                  = false\n     * StringUtils.containsAny(\"zzabyycdxx\",['z','a']) = true\n     * StringUtils.containsAny(\"zzabyycdxx\",['b','y']) = true\n     * StringUtils.containsAny(\"aba\", ['z'])           = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the true if any of the chars are found,\n * false if no match or null input\n * @since 2.4\n */\n public static boolean containsAny(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return false;\n }\n int csLength = str.length();\n int searchLength = searchChars.length;\n int csLast = csLength - 1;\n int searchLast = searchLength - 1;\n for (int i = 0; i < csLength; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLength; j++) {\n if (searchChars[j] == ch) {\n if (CharUtils.isHighSurrogate(ch)) {\n if (j == searchLast) {\n // missing low surrogate, fine, like String.indexOf(String)\n return true;\n }\n if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) {\n return true;\n }\n } else {\n // ch is in the Basic Multilingual Plane\n return true;\n }\n }\n }\n }\n return false;\n }\n\n /**\n *

\n * Checks if the String contains any character in the given set of characters.\n *

\n *\n *

\n * A null String will return false. A null search string will return\n * false.\n *

\n *\n *
\n     * StringUtils.containsAny(null, *)            = false\n     * StringUtils.containsAny(\"\", *)              = false\n     * StringUtils.containsAny(*, null)            = false\n     * StringUtils.containsAny(*, \"\")              = false\n     * StringUtils.containsAny(\"zzabyycdxx\", \"za\") = true\n     * StringUtils.containsAny(\"zzabyycdxx\", \"by\") = true\n     * StringUtils.containsAny(\"aba\",\"z\")          = false\n     * 
\n *\n * @param str\n * the String to check, may be null\n * @param searchChars\n * the chars to search for, may be null\n * @return the true if any of the chars are found, false if no match or null input\n * @since 2.4\n */\n public static boolean containsAny(final String str, final String searchChars) {\n if (searchChars == null) {\n return false;\n }\n return StringUtils.containsAny(str, searchChars.toCharArray());\n }\n // IndexOfAnyBut chars\n //-----------------------------------------------------------------------\n\n /**\n *

Search a String to find the first index of any\n * character not in the given set of characters.

\n *\n *

A null String will return -1.\n * A null or zero length search array will return -1.

\n *\n *
\n     * StringUtils.indexOfAnyBut(null, *)                              = -1\n     * StringUtils.indexOfAnyBut(\"\", *)                                = -1\n     * StringUtils.indexOfAnyBut(*, null)                              = -1\n     * StringUtils.indexOfAnyBut(*, [])                                = -1\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", new char[] {'z', 'a'} ) = 3\n     * StringUtils.indexOfAnyBut(\"aba\", new char[] {'z'} )             = 0\n     * StringUtils.indexOfAnyBut(\"aba\", new char[] {'a', 'b'} )        = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAnyBut(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n outer:\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) {\n if (searchChars[j + 1] == str.charAt(i + 1)) {\n continue outer;\n }\n } else {\n continue outer;\n }\n }\n }\n return i;\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Search a String to find the first index of any\n * character not in the given set of characters.

\n *\n *

A null String will return -1.\n * A null or empty search string will return -1.

\n *\n *
\n     * StringUtils.indexOfAnyBut(null, *)            = -1\n     * StringUtils.indexOfAnyBut(\"\", *)              = -1\n     * StringUtils.indexOfAnyBut(*, null)            = -1\n     * StringUtils.indexOfAnyBut(*, \"\")              = -1\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", \"za\") = 3\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", \"\")   = -1\n     * StringUtils.indexOfAnyBut(\"aba\",\"ab\")         = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAnyBut(final String str, final String searchChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n char ch = str.charAt(i);\n boolean chFound = searchChars.indexOf(ch) >= 0;\n if (i + 1 < strLen && CharUtils.isHighSurrogate(ch)) {\n char ch2 = str.charAt(i + 1);\n if (chFound && searchChars.indexOf(ch2) < 0) {\n return i;\n }\n } else {\n if (!chFound) {\n return i;\n }\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // ContainsOnly\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if the String contains only certain characters.

\n *\n *

A null String will return false.\n * A null valid character array will return false.\n * An empty String (length()=0) always returns true.

\n *\n *
\n     * StringUtils.containsOnly(null, *)       = false\n     * StringUtils.containsOnly(*, null)       = false\n     * StringUtils.containsOnly(\"\", *)         = true\n     * StringUtils.containsOnly(\"ab\", '')      = false\n     * StringUtils.containsOnly(\"abab\", 'abc') = true\n     * StringUtils.containsOnly(\"ab1\", 'abc')  = false\n     * StringUtils.containsOnly(\"abz\", 'abc')  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param valid an array of valid chars, may be null\n * @return true if it only contains valid chars and is non-null\n */\n public static boolean containsOnly(final String str, final char[] valid) {\n // All these pre-checks are to maintain API with an older version\n if (valid == null || str == null) {\n return false;\n }\n if (str.length() == 0) {\n return true;\n }\n if (valid.length == 0) {\n return false;\n }\n return StringUtils.indexOfAnyBut(str, valid) == StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the String contains only certain characters.

\n *\n *

A null String will return false.\n * A null valid character String will return false.\n * An empty String (length()=0) always returns true.

\n *\n *
\n     * StringUtils.containsOnly(null, *)       = false\n     * StringUtils.containsOnly(*, null)       = false\n     * StringUtils.containsOnly(\"\", *)         = true\n     * StringUtils.containsOnly(\"ab\", \"\")      = false\n     * StringUtils.containsOnly(\"abab\", \"abc\") = true\n     * StringUtils.containsOnly(\"ab1\", \"abc\")  = false\n     * StringUtils.containsOnly(\"abz\", \"abc\")  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param validChars a String of valid chars, may be null\n * @return true if it only contains valid chars and is non-null\n * @since 2.0\n */\n public static boolean containsOnly(final String str, final String validChars) {\n if (str == null || validChars == null) {\n return false;\n }\n return StringUtils.containsOnly(str, validChars.toCharArray());\n }\n // ContainsNone\n //-----------------------------------------------------------------------\n\n /**\n *

Checks that the String does not contain certain characters.

\n *\n *

A null String will return true.\n * A null invalid character array will return true.\n * An empty String (length()=0) always returns true.

\n *\n *
\n     * StringUtils.containsNone(null, *)       = true\n     * StringUtils.containsNone(*, null)       = true\n     * StringUtils.containsNone(\"\", *)         = true\n     * StringUtils.containsNone(\"ab\", '')      = true\n     * StringUtils.containsNone(\"abab\", 'xyz') = true\n     * StringUtils.containsNone(\"ab1\", 'xyz')  = true\n     * StringUtils.containsNone(\"abz\", 'xyz')  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars an array of invalid chars, may be null\n * @return true if it contains none of the invalid chars, or is null\n * @since 2.0\n */\n public static boolean containsNone(final String str, final char[] searchChars) {\n if (str == null || searchChars == null) {\n return true;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (CharUtils.isHighSurrogate(ch)) {\n if (j == searchLast) {\n // missing low surrogate, fine, like String.indexOf(String)\n return false;\n }\n if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) {\n return false;\n }\n } else {\n // ch is in the Basic Multilingual Plane\n return false;\n }\n }\n }\n }\n return true;\n }\n\n /**\n *

Checks that the String does not contain certain characters.

\n *\n *

A null String will return true.\n * A null invalid character array will return true.\n * An empty String (\"\") always returns true.

\n *\n *
\n     * StringUtils.containsNone(null, *)       = true\n     * StringUtils.containsNone(*, null)       = true\n     * StringUtils.containsNone(\"\", *)         = true\n     * StringUtils.containsNone(\"ab\", \"\")      = true\n     * StringUtils.containsNone(\"abab\", \"xyz\") = true\n     * StringUtils.containsNone(\"ab1\", \"xyz\")  = true\n     * StringUtils.containsNone(\"abz\", \"xyz\")  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param invalidChars a String of invalid chars, may be null\n * @return true if it contains none of the invalid chars, or is null\n * @since 2.0\n */\n public static boolean containsNone(final String str, final String invalidChars) {\n if (str == null || invalidChars == null) {\n return true;\n }\n return StringUtils.containsNone(str, invalidChars.toCharArray());\n }\n // IndexOfAny strings\n //-----------------------------------------------------------------------\n\n /**\n *

Find the first index of any of a set of potential substrings.

\n *\n *

A null String will return -1.\n * A null or zero length search array will return -1.\n * A null search array entry will be ignored, but a search\n * array containing \"\" will return 0 if str is not\n * null. This method uses {@link String#indexOf(String)}.

\n *\n *
\n     * StringUtils.indexOfAny(null, *)                     = -1\n     * StringUtils.indexOfAny(*, null)                     = -1\n     * StringUtils.indexOfAny(*, [])                       = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"ab\",\"cd\"])   = 2\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"cd\",\"ab\"])   = 2\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"])   = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"zab\",\"aby\"]) = 1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"\"])          = 0\n     * StringUtils.indexOfAny(\"\", [\"\"])                    = 0\n     * StringUtils.indexOfAny(\"\", [\"a\"])                   = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStrs the Strings to search for, may be null\n * @return the first index of any of the searchStrs in str, -1 if no match\n */\n public static int indexOfAny(final String str, final String[] searchStrs) {\n if (str == null || searchStrs == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int sz = searchStrs.length;\n // String's can't have a MAX_VALUEth index.\n int ret = Integer.MAX_VALUE;\n int tmp = 0;\n for (int i = 0; i < sz; i++) {\n String search = searchStrs[i];\n if (search == null) {\n continue;\n }\n tmp = str.indexOf(search);\n if (tmp == StringUtils.INDEX_NOT_FOUND) {\n continue;\n }\n if (tmp < ret) {\n ret = tmp;\n }\n }\n return ret == Integer.MAX_VALUE ? StringUtils.INDEX_NOT_FOUND : ret;\n }\n\n /**\n *

Find the latest index of any of a set of potential substrings.

\n *\n *

A null String will return -1.\n * A null search array will return -1.\n * A null or zero length search array entry will be ignored,\n * but a search array containing \"\" will return the length of str\n * if str is not null. This method uses {@link String#indexOf(String)}

\n *\n *
\n     * StringUtils.lastIndexOfAny(null, *)                   = -1\n     * StringUtils.lastIndexOfAny(*, null)                   = -1\n     * StringUtils.lastIndexOfAny(*, [])                     = -1\n     * StringUtils.lastIndexOfAny(*, [null])                 = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"ab\",\"cd\"]) = 6\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"cd\",\"ab\"]) = 6\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"]) = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"]) = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"\"])   = 10\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStrs the Strings to search for, may be null\n * @return the last index of any of the Strings, -1 if no match\n */\n public static int lastIndexOfAny(final String str, final String[] searchStrs) {\n if (str == null || searchStrs == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int sz = searchStrs.length;\n int ret = StringUtils.INDEX_NOT_FOUND;\n int tmp = 0;\n for (int i = 0; i < sz; i++) {\n String search = searchStrs[i];\n if (search == null) {\n continue;\n }\n tmp = str.lastIndexOf(search);\n if (tmp > ret) {\n ret = tmp;\n }\n }\n return ret;\n }\n // Substring\n //-----------------------------------------------------------------------\n\n /**\n *

Gets a substring from the specified String avoiding exceptions.

\n *\n *

A negative start position can be used to start n\n * characters from the end of the String.

\n *\n *

A null String will return null.\n * An empty (\"\") String will return \"\".

\n *\n *
\n     * StringUtils.substring(null, *)   = null\n     * StringUtils.substring(\"\", *)     = \"\"\n     * StringUtils.substring(\"abc\", 0)  = \"abc\"\n     * StringUtils.substring(\"abc\", 2)  = \"c\"\n     * StringUtils.substring(\"abc\", 4)  = \"\"\n     * StringUtils.substring(\"abc\", -2) = \"bc\"\n     * StringUtils.substring(\"abc\", -4) = \"abc\"\n     * 
\n *\n * @param str the String to get the substring from, may be null\n * @param start the position to start from, negative means\n * count back from the end of the String by this many characters\n * @return substring from start position, null if null String input\n */\n public static String substring(final String str, int start) {\n if (str == null) {\n return null;\n }\n // handle negatives, which means last n characters\n if (start < 0) {\n start = str.length() + start; // remember start is negative\n }\n if (start < 0) {\n start = 0;\n }\n if (start > str.length()) {\n return StringUtils.EMPTY;\n }\n return str.substring(start);\n }\n\n /**\n *

Gets a substring from the specified String avoiding exceptions.

\n *\n *

A negative start position can be used to start/end n\n * characters from the end of the String.

\n *\n *

The returned substring starts with the character in the start\n * position and ends before the end position. All position counting is\n * zero-based -- i.e., to start at the beginning of the string use\n * start = 0. Negative start and end positions can be used to\n * specify offsets relative to the end of the String.

\n *\n *

If start is not strictly to the left of end, \"\"\n * is returned.

\n *\n *
\n     * StringUtils.substring(null, *, *)    = null\n     * StringUtils.substring(\"\", * ,  *)    = \"\";\n     * StringUtils.substring(\"abc\", 0, 2)   = \"ab\"\n     * StringUtils.substring(\"abc\", 2, 0)   = \"\"\n     * StringUtils.substring(\"abc\", 2, 4)   = \"c\"\n     * StringUtils.substring(\"abc\", 4, 6)   = \"\"\n     * StringUtils.substring(\"abc\", 2, 2)   = \"\"\n     * StringUtils.substring(\"abc\", -2, -1) = \"b\"\n     * StringUtils.substring(\"abc\", -4, 2)  = \"ab\"\n     * 
\n *\n * @param str the String to get the substring from, may be null\n * @param start the position to start from, negative means\n * count back from the end of the String by this many characters\n * @param end the position to end at (exclusive), negative means\n * count back from the end of the String by this many characters\n * @return substring from start position to end positon,\n * null if null String input\n */\n public static String substring(final String str, int start, int end) {\n if (str == null) {\n return null;\n }\n // handle negatives\n if (end < 0) {\n end = str.length() + end; // remember end is negative\n }\n if (start < 0) {\n start = str.length() + start; // remember start is negative\n }\n // check length next\n if (end > str.length()) {\n end = str.length();\n }\n // if start is greater than end, return \"\"\n if (start > end) {\n return StringUtils.EMPTY;\n }\n if (start < 0) {\n start = 0;\n }\n if (end < 0) {\n end = 0;\n }\n return str.substring(start, end);\n }\n // Left/Right/Mid\n //-----------------------------------------------------------------------\n\n /**\n *

Gets the leftmost len characters of a String.

\n *\n *

If len characters are not available, or the\n * String is null, the String will be returned without\n * an exception. An empty String is returned if len is negative.

\n *\n *
\n     * StringUtils.left(null, *)    = null\n     * StringUtils.left(*, -ve)     = \"\"\n     * StringUtils.left(\"\", *)      = \"\"\n     * StringUtils.left(\"abc\", 0)   = \"\"\n     * StringUtils.left(\"abc\", 2)   = \"ab\"\n     * StringUtils.left(\"abc\", 4)   = \"abc\"\n     * 
\n *\n * @param str the String to get the leftmost characters from, may be null\n * @param len the length of the required String\n * @return the leftmost characters, null if null String input\n */\n public static String left(final String str, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0) {\n return StringUtils.EMPTY;\n }\n if (str.length() <= len) {\n return str;\n }\n return str.substring(0, len);\n }\n\n /**\n *

Gets the rightmost len characters of a String.

\n *\n *

If len characters are not available, or the String\n * is null, the String will be returned without an\n * an exception. An empty String is returned if len is negative.

\n *\n *
\n     * StringUtils.right(null, *)    = null\n     * StringUtils.right(*, -ve)     = \"\"\n     * StringUtils.right(\"\", *)      = \"\"\n     * StringUtils.right(\"abc\", 0)   = \"\"\n     * StringUtils.right(\"abc\", 2)   = \"bc\"\n     * StringUtils.right(\"abc\", 4)   = \"abc\"\n     * 
\n *\n * @param str the String to get the rightmost characters from, may be null\n * @param len the length of the required String\n * @return the rightmost characters, null if null String input\n */\n public static String right(final String str, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0) {\n return StringUtils.EMPTY;\n }\n if (str.length() <= len) {\n return str;\n }\n return str.substring(str.length() - len);\n }\n\n /**\n *

Gets len characters from the middle of a String.

\n *\n *

If len characters are not available, the remainder\n * of the String will be returned without an exception. If the\n * String is null, null will be returned.\n * An empty String is returned if len is negative or exceeds the\n * length of str.

\n *\n *
\n     * StringUtils.mid(null, *, *)    = null\n     * StringUtils.mid(*, *, -ve)     = \"\"\n     * StringUtils.mid(\"\", 0, *)      = \"\"\n     * StringUtils.mid(\"abc\", 0, 2)   = \"ab\"\n     * StringUtils.mid(\"abc\", 0, 4)   = \"abc\"\n     * StringUtils.mid(\"abc\", 2, 4)   = \"c\"\n     * StringUtils.mid(\"abc\", 4, 2)   = \"\"\n     * StringUtils.mid(\"abc\", -2, 2)  = \"ab\"\n     * 
\n *\n * @param str the String to get the characters from, may be null\n * @param pos the position to start from, negative treated as zero\n * @param len the length of the required String\n * @return the middle characters, null if null String input\n */\n public static String mid(final String str, int pos, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0 || pos > str.length()) {\n return StringUtils.EMPTY;\n }\n if (pos < 0) {\n pos = 0;\n }\n if (str.length() <= pos + len) {\n return str.substring(pos);\n }\n return str.substring(pos, pos + len);\n }\n // SubStringAfter/SubStringBefore\n //-----------------------------------------------------------------------\n\n /**\n *

Gets the substring before the first occurrence of a separator.\n * The separator is not returned.

\n *\n *

A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * A null separator will return the input string.

\n *\n *

If nothing is found, the string input is returned.

\n *\n *
\n     * StringUtils.substringBefore(null, *)      = null\n     * StringUtils.substringBefore(\"\", *)        = \"\"\n     * StringUtils.substringBefore(\"abc\", \"a\")   = \"\"\n     * StringUtils.substringBefore(\"abcba\", \"b\") = \"a\"\n     * StringUtils.substringBefore(\"abc\", \"c\")   = \"ab\"\n     * StringUtils.substringBefore(\"abc\", \"d\")   = \"abc\"\n     * StringUtils.substringBefore(\"abc\", \"\")    = \"\"\n     * StringUtils.substringBefore(\"abc\", null)  = \"abc\"\n     * 
\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring before the first occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringBefore(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || separator == null) {\n return str;\n }\n if (separator.length() == 0) {\n return StringUtils.EMPTY;\n }\n int pos = str.indexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n return str.substring(0, pos);\n }\n\n /**\n *

Gets the substring after the first occurrence of a separator.\n * The separator is not returned.

\n *\n *

A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * A null separator will return the empty string if the\n * input string is not null.

\n *\n *

If nothing is found, the empty string is returned.

\n *\n *
\n     * StringUtils.substringAfter(null, *)      = null\n     * StringUtils.substringAfter(\"\", *)        = \"\"\n     * StringUtils.substringAfter(*, null)      = \"\"\n     * StringUtils.substringAfter(\"abc\", \"a\")   = \"bc\"\n     * StringUtils.substringAfter(\"abcba\", \"b\") = \"cba\"\n     * StringUtils.substringAfter(\"abc\", \"c\")   = \"\"\n     * StringUtils.substringAfter(\"abc\", \"d\")   = \"\"\n     * StringUtils.substringAfter(\"abc\", \"\")    = \"abc\"\n     * 
\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring after the first occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringAfter(final String str, final String separator) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (separator == null) {\n return StringUtils.EMPTY;\n }\n int pos = str.indexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return StringUtils.EMPTY;\n }\n return str.substring(pos + separator.length());\n }\n\n /**\n *

Gets the substring before the last occurrence of a separator.\n * The separator is not returned.

\n *\n *

A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * An empty or null separator will return the input string.

\n *\n *

If nothing is found, the string input is returned.

\n *\n *
\n     * StringUtils.substringBeforeLast(null, *)      = null\n     * StringUtils.substringBeforeLast(\"\", *)        = \"\"\n     * StringUtils.substringBeforeLast(\"abcba\", \"b\") = \"abc\"\n     * StringUtils.substringBeforeLast(\"abc\", \"c\")   = \"ab\"\n     * StringUtils.substringBeforeLast(\"a\", \"a\")     = \"\"\n     * StringUtils.substringBeforeLast(\"a\", \"z\")     = \"a\"\n     * StringUtils.substringBeforeLast(\"a\", null)    = \"a\"\n     * StringUtils.substringBeforeLast(\"a\", \"\")      = \"a\"\n     * 
\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring before the last occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringBeforeLast(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(separator)) {\n return str;\n }\n int pos = str.lastIndexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n return str.substring(0, pos);\n }\n\n /**\n *

Gets the substring after the last occurrence of a separator.\n * The separator is not returned.

\n *\n *

A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * An empty or null separator will return the empty string if\n * the input string is not null.

\n *\n *

If nothing is found, the empty string is returned.

\n *\n *
\n     * StringUtils.substringAfterLast(null, *)      = null\n     * StringUtils.substringAfterLast(\"\", *)        = \"\"\n     * StringUtils.substringAfterLast(*, \"\")        = \"\"\n     * StringUtils.substringAfterLast(*, null)      = \"\"\n     * StringUtils.substringAfterLast(\"abc\", \"a\")   = \"bc\"\n     * StringUtils.substringAfterLast(\"abcba\", \"b\") = \"a\"\n     * StringUtils.substringAfterLast(\"abc\", \"c\")   = \"\"\n     * StringUtils.substringAfterLast(\"a\", \"a\")     = \"\"\n     * StringUtils.substringAfterLast(\"a\", \"z\")     = \"\"\n     * 
\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring after the last occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringAfterLast(final String str, final String separator) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (StringUtils.isEmpty(separator)) {\n return StringUtils.EMPTY;\n }\n int pos = str.lastIndexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND || pos == str.length() - separator.length()) {\n return StringUtils.EMPTY;\n }\n return str.substring(pos + separator.length());\n }\n // Substring between\n //-----------------------------------------------------------------------\n\n /**\n *

Gets the String that is nested in between two instances of the\n * same String.

\n *\n *

A null input String returns null.\n * A null tag returns null.

\n *\n *
\n     * StringUtils.substringBetween(null, *)            = null\n     * StringUtils.substringBetween(\"\", \"\")             = \"\"\n     * StringUtils.substringBetween(\"\", \"tag\")          = null\n     * StringUtils.substringBetween(\"tagabctag\", null)  = null\n     * StringUtils.substringBetween(\"tagabctag\", \"\")    = \"\"\n     * StringUtils.substringBetween(\"tagabctag\", \"tag\") = \"abc\"\n     * 
\n *\n * @param str the String containing the substring, may be null\n * @param tag the String before and after the substring, may be null\n * @return the substring, null if no match\n * @since 2.0\n */\n public static String substringBetween(final String str, final String tag) {\n return StringUtils.substringBetween(str, tag, tag);\n }\n\n /**\n *

Gets the String that is nested in between two Strings.\n * Only the first match is returned.

\n *\n *

A null input String returns null.\n * A null open/close returns null (no match).\n * An empty (\"\") open and close returns an empty string.

\n *\n *
\n     * StringUtils.substringBetween(\"wx[b]yz\", \"[\", \"]\") = \"b\"\n     * StringUtils.substringBetween(null, *, *)          = null\n     * StringUtils.substringBetween(*, null, *)          = null\n     * StringUtils.substringBetween(*, *, null)          = null\n     * StringUtils.substringBetween(\"\", \"\", \"\")          = \"\"\n     * StringUtils.substringBetween(\"\", \"\", \"]\")         = null\n     * StringUtils.substringBetween(\"\", \"[\", \"]\")        = null\n     * StringUtils.substringBetween(\"yabcz\", \"\", \"\")     = \"\"\n     * StringUtils.substringBetween(\"yabcz\", \"y\", \"z\")   = \"abc\"\n     * StringUtils.substringBetween(\"yabczyabcz\", \"y\", \"z\")   = \"abc\"\n     * 
\n *\n * @param str the String containing the substring, may be null\n * @param open the String before the substring, may be null\n * @param close the String after the substring, may be null\n * @return the substring, null if no match\n * @since 2.0\n */\n public static String substringBetween(final String str, final String open, final String close) {\n if (str == null || open == null || close == null) {\n return null;\n }\n int start = str.indexOf(open);\n if (start != StringUtils.INDEX_NOT_FOUND) {\n int end = str.indexOf(close, start + open.length());\n if (end != StringUtils.INDEX_NOT_FOUND) {\n return str.substring(start + open.length(), end);\n }\n }\n return null;\n }\n\n /**\n *

Searches a String for substrings delimited by a start and end tag,\n * returning all matching substrings in an array.

\n *\n *

A null input String returns null.\n * A null open/close returns null (no match).\n * An empty (\"\") open/close returns null (no match).

\n *\n *
\n     * StringUtils.substringsBetween(\"[a][b][c]\", \"[\", \"]\") = [\"a\",\"b\",\"c\"]\n     * StringUtils.substringsBetween(null, *, *)            = null\n     * StringUtils.substringsBetween(*, null, *)            = null\n     * StringUtils.substringsBetween(*, *, null)            = null\n     * StringUtils.substringsBetween(\"\", \"[\", \"]\")          = []\n     * 
\n *\n * @param str the String containing the substrings, null returns null, empty returns empty\n * @param open the String identifying the start of the substring, empty returns null\n * @param close the String identifying the end of the substring, empty returns null\n * @return a String Array of substrings, or null if no match\n * @since 2.3\n */\n public static String[] substringsBetween(final String str, final String open, final String close) {\n if (str == null || StringUtils.isEmpty(open) || StringUtils.isEmpty(close)) {\n return null;\n }\n int strLen = str.length();\n if (strLen == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n int closeLen = close.length();\n int openLen = open.length();\n List list = new ArrayList();\n int pos = 0;\n while (pos < strLen - closeLen) {\n int start = str.indexOf(open, pos);\n if (start < 0) {\n break;\n }\n start += openLen;\n int end = str.indexOf(close, start);\n if (end < 0) {\n break;\n }\n list.add(str.substring(start, end));\n pos = end + closeLen;\n }\n if (list.isEmpty()) {\n return null;\n }\n return list.toArray(new String[list.size()]);\n }\n // Splitting\n //-----------------------------------------------------------------------\n\n /**\n *

Splits the provided text into an array, using whitespace as the separator. but keep separator.

\n *\n *
\n     * StringUtils.splitKeep(null)          = null\n     * StringUtils.splitKeep(\"\")            = []\n     * StringUtils.splitKeep(\"a b c\", \" \")  = [\"a\", \" \", \"b\", \" \", \"c\"]\n     * StringUtils.splitKeep(\"abc def\", \" \")= [\"abc\", \" \", \"def\"]\n     * StringUtils.splitKeep(\" abc \", \" \")  = [\" \", \"abc\", \" \"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] splitKeep(String str, char separatorChar) {\n return splitKeep(str, String.valueOf(separatorChar));\n }\n\n /**\n *

Splits the provided text into an array, using whitespace as the separator. but keep separator.

\n *\n *
\n     * StringUtils.splitKeep(null)          = null\n     * StringUtils.splitKeep(\"\")            = []\n     * StringUtils.splitKeep(\"a b c\", \" \")  = [\"a\", \" \", \"b\", \" \", \"c\"]\n     * StringUtils.splitKeep(\"abc def\", \" \")= [\"abc\", \" \", \"def\"]\n     * StringUtils.splitKeep(\" abc \", \" \")  = [\" \", \"abc\", \" \"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] splitKeep(String str, String separatorStr) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n int CHARS = separatorStr.length();\n if (CHARS == 0) {\n throw new IllegalArgumentException(\"chars must be > 0\");\n }\n int lastIndex = 0;\n ArrayList dat = new ArrayList<>();\n while (true) {\n int lookIndex = str.indexOf(separatorStr, lastIndex);\n if (lookIndex == -1) {\n String substring = str.substring(lastIndex);\n if (substring.length() > 0) {\n dat.add(substring);\n }\n break;\n } else {\n if (lastIndex != lookIndex) {\n String term = str.substring(lastIndex, lookIndex);\n dat.add(term);\n }\n dat.add(separatorStr);\n lastIndex = lookIndex + CHARS;\n }\n }\n return dat.toArray(new String[0]);\n }\n\n /**\n *

Splits the provided text into an array, using whitespace as the\n * separator.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.split(null)       = null\n     * StringUtils.split(\"\")         = []\n     * StringUtils.split(\"abc def\")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\") = [\"abc\", \"def\"]\n     * StringUtils.split(\" abc \")    = [\"abc\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str) {\n return StringUtils.split(str, null, -1);\n }\n\n /**\n *

Splits the provided text into an array, separator specified.\n * This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"a.b.c\", '.')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.split(\"a..b.c\", '.')   = [\"a\", \"b\", \"c\"]\n     * StringUtils.split(\"a:b:c\", '.')    = [\"a:b:c\"]\n     * StringUtils.split(\"a b c\", ' ')    = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChar the character used as the delimiter\n * @return an array of parsed Strings, null if null String input\n * @since 2.0\n */\n public static String[] split(final String str, final char separatorChar) {\n return StringUtils.splitWorker(str, separatorChar, false);\n }\n\n /**\n *

Splits the provided text into an array, separators specified.\n * This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *
\n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"abc def\", null) = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc def\", \" \")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\", \" \") = [\"abc\", \"def\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\") = [\"ab\", \"cd\", \"ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str, final String separatorChars) {\n return StringUtils.splitWorker(str, separatorChars, -1, false);\n }\n\n /**\n *

Splits the provided text into an array with a maximum length,\n * separators specified.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *

If more than max delimited substrings are found, the last\n * returned string includes all characters after the first max - 1\n * returned strings (including separator characters).

\n *\n *
\n     * StringUtils.split(null, *, *)            = null\n     * StringUtils.split(\"\", *, *)              = []\n     * StringUtils.split(\"ab de fg\", null, 0)   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab   de fg\", null, 0) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\", 0)    = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\", 2)    = [\"ab\", \"cd:ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str, final String separatorChars, final int max) {\n return StringUtils.splitWorker(str, separatorChars, max, false);\n }\n\n /**\n *

Splits the provided text into an array, separator string specified.

\n *\n *

The separator(s) will not be included in the returned String array.\n * Adjacent separators are treated as one separator.

\n *\n *

A null input String returns null.\n * A null separator splits on whitespace.

\n *\n *
\n     * StringUtils.splitByWholeSeparator(null, *)               = null\n     * StringUtils.splitByWholeSeparator(\"\", *)                 = []\n     * StringUtils.splitByWholeSeparator(\"ab de fg\", null)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab   de fg\", null)    = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab:cd:ef\", \":\")       = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\") = [\"ab\", \"cd\", \"ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String was input\n */\n public static String[] splitByWholeSeparator(final String str, final String separator) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, -1, false);\n }\n\n /**\n *

Splits the provided text into an array, separator string specified.\n * Returns a maximum of max substrings.

\n *\n *

The separator(s) will not be included in the returned String array.\n * Adjacent separators are treated as one separator.

\n *\n *

A null input String returns null.\n * A null separator splits on whitespace.

\n *\n *
\n     * StringUtils.splitByWholeSeparator(null, *, *)               = null\n     * StringUtils.splitByWholeSeparator(\"\", *, *)                 = []\n     * StringUtils.splitByWholeSeparator(\"ab de fg\", null, 0)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab   de fg\", null, 0)    = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab:cd:ef\", \":\", 2)       = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\", 5) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\", 2) = [\"ab\", \"cd-!-ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @return an array of parsed Strings, null if null String was input\n */\n public static String[] splitByWholeSeparator(final String str, final String separator, final int max) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, max, false);\n }\n\n /**\n *

Splits the provided text into an array, separator string specified.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separator splits on whitespace.

\n *\n *
\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *)               = null\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"\", *)                 = []\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab de fg\", null)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab   de fg\", null)    = [\"ab\", \"\", \"\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab:cd:ef\", \":\")       = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\") = [\"ab\", \"cd\", \"ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String was input\n * @since 2.4\n */\n public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, -1, true);\n }\n\n /**\n *

Splits the provided text into an array, separator string specified.\n * Returns a maximum of max substrings.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separator splits on whitespace.

\n *\n *
\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *)               = null\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"\", *, *)                 = []\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab de fg\", null, 0)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab   de fg\", null, 0)    = [\"ab\", \"\", \"\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab:cd:ef\", \":\", 2)       = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\", 5) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\", 2) = [\"ab\", \"cd-!-ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @return an array of parsed Strings, null if null String was input\n * @since 2.4\n */\n public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator, final int max) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, max, true);\n }\n\n /**\n * Performs the logic for the splitByWholeSeparatorPreserveAllTokens methods.\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n private static String[] splitByWholeSeparatorWorker(final String str, final String separator, final int max, final boolean preserveAllTokens) {\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n if (separator == null || StringUtils.EMPTY.equals(separator)) {\n // Split on whitespace.\n return StringUtils.splitWorker(str, null, max, preserveAllTokens);\n }\n int separatorLength = separator.length();\n ArrayList substrings = new ArrayList<>();\n int numberOfSubstrings = 0;\n int beg = 0;\n int end = 0;\n while (end < len) {\n end = str.indexOf(separator, beg);\n if (end > -1) {\n if (end > beg) {\n numberOfSubstrings += 1;\n if (numberOfSubstrings == max) {\n end = len;\n substrings.add(str.substring(beg));\n } else {\n // The following is OK, because String.substring( beg, end ) excludes\n // the character at the position 'end'.\n substrings.add(str.substring(beg, end));\n // Set the starting point for the next search.\n // The following is equivalent to beg = end + (separatorLength - 1) + 1,\n // which is the right calculation:\n beg = end + separatorLength;\n }\n } else {\n // We found a consecutive occurrence of the separator, so skip it.\n if (preserveAllTokens) {\n numberOfSubstrings += 1;\n if (numberOfSubstrings == max) {\n end = len;\n substrings.add(str.substring(beg));\n } else {\n substrings.add(StringUtils.EMPTY);\n }\n }\n beg = end + separatorLength;\n }\n } else {\n // String.substring( beg ) goes from 'beg' to the end of the String.\n substrings.add(str.substring(beg));\n end = len;\n }\n }\n return substrings.toArray(new String[0]);\n }\n // -----------------------------------------------------------------------\n\n /**\n *

Splits the provided text into an array, using whitespace as the\n * separator, preserving all tokens, including empty tokens created by\n * adjacent separators. This is an alternative to using StringTokenizer.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.splitPreserveAllTokens(null)       = null\n     * StringUtils.splitPreserveAllTokens(\"\")         = []\n     * StringUtils.splitPreserveAllTokens(\"abc def\")  = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc  def\") = [\"abc\", \"\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\" abc \")    = [\"\", \"abc\", \"\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str) {\n return StringUtils.splitWorker(str, null, -1, true);\n }\n\n /**\n *

Splits the provided text into an array, separator specified,\n * preserving all tokens, including empty tokens created by adjacent\n * separators. This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.splitPreserveAllTokens(null, *)         = null\n     * StringUtils.splitPreserveAllTokens(\"\", *)           = []\n     * StringUtils.splitPreserveAllTokens(\"a.b.c\", '.')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a..b.c\", '.')   = [\"a\", \"\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a:b:c\", '.')    = [\"a:b:c\"]\n     * StringUtils.splitPreserveAllTokens(\"a\\tb\\nc\", null) = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c\", ' ')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c \", ' ')   = [\"a\", \"b\", \"c\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c  \", ' ')   = [\"a\", \"b\", \"c\", \"\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\" a b c\", ' ')   = [\"\", a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"  a b c\", ' ')  = [\"\", \"\", a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\" a b c \", ' ')  = [\"\", a\", \"b\", \"c\", \"\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChar the character used as the delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final char separatorChar) {\n return StringUtils.splitWorker(str, separatorChar, true);\n }\n\n /**\n * Performs the logic for the split and\n * splitPreserveAllTokens methods that do not return a\n * maximum array length.\n *\n * @param str the String to parse, may be null\n * @param separatorChar the separate character\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n */\n private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n List list = new ArrayList<>();\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n while (i < len) {\n if (str.charAt(i) == separatorChar) {\n if (match || preserveAllTokens) {\n list.add(str.substring(start, i));\n match = false;\n lastMatch = true;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[0]);\n }\n\n /**\n *

Splits the provided text into an array, separators specified,\n * preserving all tokens, including empty tokens created by adjacent\n * separators. This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *
\n     * StringUtils.splitPreserveAllTokens(null, *)           = null\n     * StringUtils.splitPreserveAllTokens(\"\", *)             = []\n     * StringUtils.splitPreserveAllTokens(\"abc def\", null)   = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc def\", \" \")    = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc  def\", \" \")   = [\"abc\", \"\", def\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\")   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef:\", \":\")  = [\"ab\", \"cd\", \"ef\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef::\", \":\") = [\"ab\", \"cd\", \"ef\", \"\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"ab::cd:ef\", \":\")  = [\"ab\", \"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\":cd:ef\", \":\")     = [\"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"::cd:ef\", \":\")    = [\"\", \"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\":cd:ef:\", \":\")    = [\"\", cd\", \"ef\", \"\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final String separatorChars) {\n return StringUtils.splitWorker(str, separatorChars, -1, true);\n }\n\n /**\n *

Splits the provided text into an array with a maximum length,\n * separators specified, preserving all tokens, including empty tokens\n * created by adjacent separators.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * Adjacent separators are treated as one separator.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *

If more than max delimited substrings are found, the last\n * returned string includes all characters after the first max - 1\n * returned strings (including separator characters).

\n *\n *
\n     * StringUtils.splitPreserveAllTokens(null, *, *)            = null\n     * StringUtils.splitPreserveAllTokens(\"\", *, *)              = []\n     * StringUtils.splitPreserveAllTokens(\"ab de fg\", null, 0)   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 0) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\", 0)    = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\", 2)    = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 2) = [\"ab\", \"  de fg\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 3) = [\"ab\", \"\", \" de fg\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 4) = [\"ab\", \"\", \"\", \"de fg\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) {\n return StringUtils.splitWorker(str, separatorChars, max, true);\n }\n\n /**\n * Performs the logic for the split and\n * splitPreserveAllTokens methods that return a maximum array\n * length.\n *\n * @param str the String to parse, may be null\n * @param separatorChars the separate character\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit.\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n */\n private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n // Direct code is quicker than StringTokenizer.\n // Also, StringTokenizer uses isSpace() not isWhitespace()\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n List list = new ArrayList<>();\n int sizePlus1 = 1;\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n if (separatorChars == null) {\n // Null separator means use whitespace\n while (i < len) {\n if (Character.isWhitespace(str.charAt(i))) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else if (separatorChars.length() == 1) {\n // Optimise 1 character case\n char sep = separatorChars.charAt(0);\n while (i < len) {\n if (str.charAt(i) == sep) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else {\n // standard case\n while (i < len) {\n if (separatorChars.indexOf(str.charAt(i)) >= 0) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[0]);\n }\n\n /**\n *

Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens.\n *

\n     * StringUtils.splitByCharacterType(null)         = null\n     * StringUtils.splitByCharacterType(\"\")           = []\n     * StringUtils.splitByCharacterType(\"ab de fg\")   = [\"ab\", \" \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterType(\"ab   de fg\") = [\"ab\", \"   \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterType(\"ab:cd:ef\")   = [\"ab\", \":\", \"cd\", \":\", \"ef\"]\n     * StringUtils.splitByCharacterType(\"number5\")    = [\"number\", \"5\"]\n     * StringUtils.splitByCharacterType(\"fooBar\")     = [\"foo\", \"B\", \"ar\"]\n     * StringUtils.splitByCharacterType(\"foo200Bar\")  = [\"foo\", \"200\", \"B\", \"ar\"]\n     * StringUtils.splitByCharacterType(\"ASFRules\")   = [\"ASFR\", \"ules\"]\n     * 
\n * @param str the String to split, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n public static String[] splitByCharacterType(final String str) {\n return StringUtils.splitByCharacterType(str, false);\n }\n\n /**\n *

Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens, with the\n * following exception: the character of type\n * Character.UPPERCASE_LETTER, if any, immediately\n * preceding a token of type Character.LOWERCASE_LETTER\n * will belong to the following token rather than to the preceding, if any,\n * Character.UPPERCASE_LETTER token.\n *

\n     * StringUtils.splitByCharacterTypeCamelCase(null)         = null\n     * StringUtils.splitByCharacterTypeCamelCase(\"\")           = []\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab de fg\")   = [\"ab\", \" \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab   de fg\") = [\"ab\", \"   \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab:cd:ef\")   = [\"ab\", \":\", \"cd\", \":\", \"ef\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"number5\")    = [\"number\", \"5\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"fooBar\")     = [\"foo\", \"Bar\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"foo200Bar\")  = [\"foo\", \"200\", \"Bar\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ASFRules\")   = [\"ASF\", \"Rules\"]\n     * 
\n * @param str the String to split, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n public static String[] splitByCharacterTypeCamelCase(final String str) {\n return StringUtils.splitByCharacterType(str, true);\n }\n\n /**\n *

Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens, with the\n * following exception: if camelCase is true,\n * the character of type Character.UPPERCASE_LETTER, if any,\n * immediately preceding a token of type Character.LOWERCASE_LETTER\n * will belong to the following token rather than to the preceding, if any,\n * Character.UPPERCASE_LETTER token.\n * @param str the String to split, may be null\n * @param camelCase whether to use so-called \"camel-case\" for letter types\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n private static String[] splitByCharacterType(final String str, final boolean camelCase) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n char[] c = str.toCharArray();\n List list = new ArrayList();\n int tokenStart = 0;\n int currentType = Character.getType(c[tokenStart]);\n for (int pos = tokenStart + 1; pos < c.length; pos++) {\n int type = Character.getType(c[pos]);\n if (type == currentType) {\n continue;\n }\n if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) {\n int newTokenStart = pos - 1;\n if (newTokenStart != tokenStart) {\n list.add(new String(c, tokenStart, newTokenStart - tokenStart));\n tokenStart = newTokenStart;\n }\n } else {\n list.add(new String(c, tokenStart, pos - tokenStart));\n tokenStart = pos;\n }\n currentType = type;\n }\n list.add(new String(c, tokenStart, c.length - tokenStart));\n return list.toArray(new String[0]);\n }\n // Joining\n //-----------------------------------------------------------------------\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No separator is added to the joined String.\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null)            = null\n     * StringUtils.join([])              = \"\"\n     * StringUtils.join([null])          = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"]) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"]) = \"a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array) {\n return StringUtils.join(array, null);\n }\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No delimiter is added before or after the list.\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null, *)               = null\n     * StringUtils.join([], *)                 = \"\"\n     * StringUtils.join([null], *)             = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], ';')  = \"a;b;c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ';')  = \";;a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array, final char separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array, separator, 0, array.length);\n }\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No delimiter is added before or after the list.\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null, *)               = null\n     * StringUtils.join([], *)                 = \"\"\n     * StringUtils.join([null], *)             = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], ';')  = \"a;b;c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ';')  = \";;a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use\n * @param startIndex the first index to start joining from. It is\n * an error to pass in an end index past the end of the array\n * @param endIndex the index to stop joining from (exclusive). It is\n * an error to pass in an end index past the end of the array\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) {\n if (array == null) {\n return null;\n }\n int bufSize = endIndex - startIndex;\n if (bufSize <= 0) {\n return StringUtils.EMPTY;\n }\n bufSize *= (array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1;\n StringBuilder buf = new StringBuilder(bufSize);\n for (int i = startIndex; i < endIndex; i++) {\n if (i > startIndex) {\n buf.append(separator);\n }\n if (array[i] != null) {\n buf.append(array[i]);\n }\n }\n return buf.toString();\n }\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No delimiter is added before or after the list.\n * A null separator is the same as an empty String (\"\").\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null, *)                = null\n     * StringUtils.join([], *)                  = \"\"\n     * StringUtils.join([null], *)              = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"--\")  = \"a--b--c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null)  = \"abc\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"\")    = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ',')   = \",,a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use, null treated as \"\"\n * @return the joined String, null if null array input\n */\n public static String join(final Object[] array, final String separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array, separator, 0, array.length);\n }\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No delimiter is added before or after the list.\n * A null separator is the same as an empty String (\"\").\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null, *)                = null\n     * StringUtils.join([], *)                  = \"\"\n     * StringUtils.join([null], *)              = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"--\")  = \"a--b--c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null)  = \"abc\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"\")    = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ',')   = \",,a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use, null treated as \"\"\n * @param startIndex the first index to start joining from. It is\n * an error to pass in an end index past the end of the array\n * @param endIndex the index to stop joining from (exclusive). It is\n * an error to pass in an end index past the end of the array\n * @return the joined String, null if null array input\n */\n public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {\n if (array == null) {\n return null;\n }\n if (separator == null) {\n separator = StringUtils.EMPTY;\n }\n // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))\n // (Assuming that all Strings are roughly equally long)\n int bufSize = endIndex - startIndex;\n if (bufSize <= 0) {\n return StringUtils.EMPTY;\n }\n bufSize *= (array[startIndex] == null ? 16 : array[startIndex].toString().length()) + separator.length();\n StringBuilder buf = new StringBuilder(bufSize);\n for (int i = startIndex; i < endIndex; i++) {\n if (i > startIndex) {\n buf.append(separator);\n }\n if (array[i] != null) {\n buf.append(array[i]);\n }\n }\n return buf.toString();\n }\n // Delete\n //-----------------------------------------------------------------------\n\n /**\n *

Deletes all whitespaces from a String as defined by\n * {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.deleteWhitespace(null)         = null\n     * StringUtils.deleteWhitespace(\"\")           = \"\"\n     * StringUtils.deleteWhitespace(\"abc\")        = \"abc\"\n     * StringUtils.deleteWhitespace(\"   ab  c  \") = \"abc\"\n     * 
\n *\n * @param str the String to delete whitespace from, may be null\n * @return the String without whitespaces, null if null String input\n */\n public static String deleteWhitespace(final String str) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n int sz = str.length();\n char[] chs = new char[sz];\n int count = 0;\n for (int i = 0; i < sz; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n chs[count++] = str.charAt(i);\n }\n }\n if (count == sz) {\n return str;\n }\n return new String(chs, 0, count);\n }\n // Remove\n //-----------------------------------------------------------------------\n\n /**\n *

Removes a substring only if it is at the begining of a source string,\n * otherwise returns the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

\n *\n *
\n     * StringUtils.removeStart(null, *)      = null\n     * StringUtils.removeStart(\"\", *)        = \"\"\n     * StringUtils.removeStart(*, null)      = *\n     * StringUtils.removeStart(\"www.domain.com\", \"www.\")   = \"domain.com\"\n     * StringUtils.removeStart(\"domain.com\", \"www.\")       = \"domain.com\"\n     * StringUtils.removeStart(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeStart(\"abc\", \"\")    = \"abc\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String removeStart(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (str.startsWith(remove)) {\n return str.substring(remove.length());\n }\n return str;\n }\n\n /**\n *

Case insensitive removal of a substring if it is at the begining of a source string,\n * otherwise returns the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

\n *\n *
\n     * StringUtils.removeStartIgnoreCase(null, *)      = null\n     * StringUtils.removeStartIgnoreCase(\"\", *)        = \"\"\n     * StringUtils.removeStartIgnoreCase(*, null)      = *\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"www.\")   = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"WWW.\")   = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"domain.com\", \"www.\")       = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"abc\", \"\")    = \"abc\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for (case insensitive) and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.4\n */\n public static String removeStartIgnoreCase(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (StringUtils.startsWithIgnoreCase(str, remove)) {\n return str.substring(remove.length());\n }\n return str;\n }\n\n /**\n *

Removes a substring only if it is at the end of a source string,\n * otherwise returns the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

\n *\n *
\n     * StringUtils.removeEnd(null, *)      = null\n     * StringUtils.removeEnd(\"\", *)        = \"\"\n     * StringUtils.removeEnd(*, null)      = *\n     * StringUtils.removeEnd(\"www.domain.com\", \".com.\")  = \"www.domain.com\"\n     * StringUtils.removeEnd(\"www.domain.com\", \".com\")   = \"www.domain\"\n     * StringUtils.removeEnd(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeEnd(\"abc\", \"\")    = \"abc\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String removeEnd(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (str.endsWith(remove)) {\n return str.substring(0, str.length() - remove.length());\n }\n return str;\n }\n\n /**\n *

Case insensitive removal of a substring if it is at the end of a source string,\n * otherwise returns the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

\n *\n *
\n     * StringUtils.removeEndIgnoreCase(null, *)      = null\n     * StringUtils.removeEndIgnoreCase(\"\", *)        = \"\"\n     * StringUtils.removeEndIgnoreCase(*, null)      = *\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".com.\")  = \"www.domain.com\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".com\")   = \"www.domain\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeEndIgnoreCase(\"abc\", \"\")    = \"abc\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".COM\") = \"www.domain\")\n     * StringUtils.removeEndIgnoreCase(\"www.domain.COM\", \".com\") = \"www.domain\")\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for (case insensitive) and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.4\n */\n public static String removeEndIgnoreCase(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (StringUtils.endsWithIgnoreCase(str, remove)) {\n return str.substring(0, str.length() - remove.length());\n }\n return str;\n }\n\n /**\n *

Removes all occurrences of a substring from within the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null remove string will return the source string.\n * An empty (\"\") remove string will return the source string.

\n *\n *
\n     * StringUtils.remove(null, *)        = null\n     * StringUtils.remove(\"\", *)          = \"\"\n     * StringUtils.remove(*, null)        = *\n     * StringUtils.remove(*, \"\")          = *\n     * StringUtils.remove(\"queued\", \"ue\") = \"qd\"\n     * StringUtils.remove(\"queued\", \"zz\") = \"queued\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String remove(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n return StringUtils.replace(str, remove, StringUtils.EMPTY, -1);\n }\n\n /**\n *

Removes all occurrences of a character from within the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.

\n *\n *
\n     * StringUtils.remove(null, *)       = null\n     * StringUtils.remove(\"\", *)         = \"\"\n     * StringUtils.remove(\"queued\", 'u') = \"qeed\"\n     * StringUtils.remove(\"queued\", 'z') = \"queued\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the char to search for and remove, may be null\n * @return the substring with the char removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String remove(final String str, final char remove) {\n if (StringUtils.isEmpty(str) || str.indexOf(remove) == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n char[] chars = str.toCharArray();\n int pos = 0;\n for (int i = 0; i < chars.length; i++) {\n if (chars[i] != remove) {\n chars[pos++] = chars[i];\n }\n }\n return new String(chars, 0, pos);\n }\n // Replacing\n //-----------------------------------------------------------------------\n\n /**\n *

Replaces a String with another String inside a larger String, once.

\n *\n *

A null reference passed to this method is a no-op.

\n *\n *
\n     * StringUtils.replaceOnce(null, *, *)        = null\n     * StringUtils.replaceOnce(\"\", *, *)          = \"\"\n     * StringUtils.replaceOnce(\"any\", null, *)    = \"any\"\n     * StringUtils.replaceOnce(\"any\", *, null)    = \"any\"\n     * StringUtils.replaceOnce(\"any\", \"\", *)      = \"any\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", null)  = \"aba\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", \"\")    = \"ba\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", \"z\")   = \"zba\"\n     * 
\n *\n * @see #replace(String text, String searchString, String replacement, int max)\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace with, may be null\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replaceOnce(final String text, final String searchString, final String replacement) {\n return StringUtils.replace(text, searchString, replacement, 1);\n }\n\n /**\n *

Replaces all occurrences of a String within another String.

\n *\n *

A null reference passed to this method is a no-op.

\n *\n *
\n     * StringUtils.replace(null, *, *)        = null\n     * StringUtils.replace(\"\", *, *)          = \"\"\n     * StringUtils.replace(\"any\", null, *)    = \"any\"\n     * StringUtils.replace(\"any\", *, null)    = \"any\"\n     * StringUtils.replace(\"any\", \"\", *)      = \"any\"\n     * StringUtils.replace(\"aba\", \"a\", null)  = \"aba\"\n     * StringUtils.replace(\"aba\", \"a\", \"\")    = \"b\"\n     * StringUtils.replace(\"aba\", \"a\", \"z\")   = \"zbz\"\n     * 
\n *\n * @see #replace(String text, String searchString, String replacement, int max)\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace it with, may be null\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replace(final String text, final String searchString, final String replacement) {\n return StringUtils.replace(text, searchString, replacement, -1);\n }\n\n /**\n *

Replaces a String with another String inside a larger String,\n * for the first max values of the search String.

\n *\n *

A null reference passed to this method is a no-op.

\n *\n *
\n     * StringUtils.replace(null, *, *, *)         = null\n     * StringUtils.replace(\"\", *, *, *)           = \"\"\n     * StringUtils.replace(\"any\", null, *, *)     = \"any\"\n     * StringUtils.replace(\"any\", *, null, *)     = \"any\"\n     * StringUtils.replace(\"any\", \"\", *, *)       = \"any\"\n     * StringUtils.replace(\"any\", *, *, 0)        = \"any\"\n     * StringUtils.replace(\"abaa\", \"a\", null, -1) = \"abaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"\", -1)   = \"b\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 0)   = \"abaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 1)   = \"zbaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 2)   = \"zbza\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", -1)  = \"zbzz\"\n     * 
\n *\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace it with, may be null\n * @param max maximum number of values to replace, or -1 if no maximum\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replace(final String text, final String searchString, final String replacement, int max) {\n if (StringUtils.isEmpty(text) || StringUtils.isEmpty(searchString) || replacement == null || max == 0) {\n return text;\n }\n int start = 0;\n int end = text.indexOf(searchString, start);\n if (end == StringUtils.INDEX_NOT_FOUND) {\n return text;\n }\n int replLength = searchString.length();\n int increase = replacement.length() - replLength;\n increase = Math.max(increase, 0);\n increase *= max < 0 ? 16 : Math.min(max, 64);\n StringBuilder buf = new StringBuilder(text.length() + increase);\n while (end != StringUtils.INDEX_NOT_FOUND) {\n buf.append(text.substring(start, end)).append(replacement);\n start = end + replLength;\n if (--max == 0) {\n break;\n }\n end = text.indexOf(searchString, start);\n }\n buf.append(text.substring(start));\n return buf.toString();\n }\n\n /**\n *

\n * Replaces all occurrences of Strings within another String.\n *

\n *\n *

\n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored. This will not repeat. For repeating replaces, call the\n * overloaded method.\n *

\n *\n *
\n     *  StringUtils.replaceEach(null, *, *)        = null\n     *  StringUtils.replaceEach(\"\", *, *)          = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0]) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null)  = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"})  = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"})  = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"})  = \"wcte\"\n     *  (example of how it does not repeat)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"})  = \"dcte\"\n     * 
\n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) {\n return StringUtils.replaceEach(text, searchList, replacementList, false, 0);\n }\n\n /**\n *

\n * Replaces all occurrences of Strings within another String.\n *

\n *\n *

\n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored. This will not repeat. For repeating replaces, call the\n * overloaded method.\n *

\n *\n *
\n     *  StringUtils.replaceEach(null, *, *, *) = null\n     *  StringUtils.replaceEach(\"\", *, *, *) = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0], *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"}, *) = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"}, *) = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"}, *) = \"wcte\"\n     *  (example of how it repeats)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, false) = \"dcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, true) = \"tcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, true) = IllegalArgumentException\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, false) = \"dcabe\"\n     * 
\n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IllegalArgumentException\n * if the search is repeating and there is an endless loop due\n * to outputs of one being inputs to another\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) {\n // timeToLive should be 0 if not used or nothing to replace, else it's\n // the length of the replace array\n int timeToLive = searchList == null ? 0 : searchList.length;\n return StringUtils.replaceEach(text, searchList, replacementList, true, timeToLive);\n }\n\n /**\n *

\n * Replaces all occurrences of Strings within another String.\n *

\n *\n *

\n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored.\n *

\n *\n *
\n     *  StringUtils.replaceEach(null, *, *, *) = null\n     *  StringUtils.replaceEach(\"\", *, *, *) = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0], *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"}, *) = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"}, *) = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"}, *) = \"wcte\"\n     *  (example of how it repeats)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, false) = \"dcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, true) = \"tcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, *) = IllegalArgumentException\n     * 
\n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @param repeat if true, then replace repeatedly\n * until there are no more possible replacements or timeToLive < 0\n * @param timeToLive\n * if less than 0 then there is a circular reference and endless\n * loop\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IllegalArgumentException\n * if the search is repeating and there is an endless loop due\n * to outputs of one being inputs to another\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n private static String replaceEach(final String text, final String[] searchList, final String[] replacementList, final boolean repeat, final int timeToLive) {\n // mchyzer Performance note: This creates very few new objects (one major goal)\n // let me know if there are performance requests, we can create a harness to measure\n if (text == null || text.length() == 0 || searchList == null || searchList.length == 0 || replacementList == null || replacementList.length == 0) {\n return text;\n }\n // if recursing, this shouldnt be less than 0\n if (timeToLive < 0) {\n throw new IllegalStateException(\"TimeToLive of \" + timeToLive + \" is less than 0: \" + text);\n }\n int searchLength = searchList.length;\n int replacementLength = replacementList.length;\n // make sure lengths are ok, these need to be equal\n if (searchLength != replacementLength) {\n throw new IllegalArgumentException(\"Search and Replace array lengths don't match: \" + searchLength + \" vs \" + replacementLength);\n }\n // keep track of which still have matches\n boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];\n // index on index that the match was found\n int textIndex = -1;\n int replaceIndex = -1;\n int tempIndex = -1;\n // index of replace array that will replace the search string found\n // NOTE: logic duplicated below START\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) {\n continue;\n }\n tempIndex = text.indexOf(searchList[i]);\n // see if we need to keep searching for this\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n // NOTE: logic mostly below END\n // no search strings found, we are done\n if (textIndex == -1) {\n return text;\n }\n int start = 0;\n // get a good guess on the size of the result buffer so it doesnt have to double if it goes over a bit\n int increase = 0;\n // count the replacement text elements that are larger than their corresponding text being replaced\n for (int i = 0; i < searchList.length; i++) {\n if (searchList[i] == null || replacementList[i] == null) {\n continue;\n }\n int greater = replacementList[i].length() - searchList[i].length();\n if (greater > 0) {\n increase += 3 * greater; // assume 3 matches\n }\n }\n // have upper-bound at 20% increase, then let Java take over\n increase = Math.min(increase, text.length() / 5);\n StringBuilder buf = new StringBuilder(text.length() + increase);\n while (textIndex != -1) {\n for (int i = start; i < textIndex; i++) {\n buf.append(text.charAt(i));\n }\n buf.append(replacementList[replaceIndex]);\n start = textIndex + searchList[replaceIndex].length();\n textIndex = -1;\n replaceIndex = -1;\n tempIndex = -1;\n // find the next earliest match\n // NOTE: logic mostly duplicated above START\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) {\n continue;\n }\n tempIndex = text.indexOf(searchList[i], start);\n // see if we need to keep searching for this\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n // NOTE: logic duplicated above END\n }\n int textLength = text.length();\n for (int i = start; i < textLength; i++) {\n buf.append(text.charAt(i));\n }\n String result = buf.toString();\n if (!repeat) {\n return result;\n }\n return StringUtils.replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);\n }\n // Replace, character based\n //-----------------------------------------------------------------------\n\n /**\n *

Replaces all occurrences of a character in a String with another.\n * This is a null-safe version of {@link String#replace(char, char)}.

\n *\n *

A null string input returns null.\n * An empty (\"\") string input returns an empty string.

\n *\n *
\n     * StringUtils.replaceChars(null, *, *)        = null\n     * StringUtils.replaceChars(\"\", *, *)          = \"\"\n     * StringUtils.replaceChars(\"abcba\", 'b', 'y') = \"aycya\"\n     * StringUtils.replaceChars(\"abcba\", 'z', 'y') = \"abcba\"\n     * 
\n *\n * @param str String to replace characters in, may be null\n * @param searchChar the character to search for, may be null\n * @param replaceChar the character to replace, may be null\n * @return modified String, null if null string input\n * @since 2.0\n */\n public static String replaceChars(final String str, final char searchChar, final char replaceChar) {\n if (str == null) {\n return null;\n }\n return str.replace(searchChar, replaceChar);\n }\n\n /**\n *

Replaces multiple characters in a String in one go.\n * This method can also be used to delete characters.

\n *\n *

For example:
\n * replaceChars("hello", "ho", "jy") = jelly.

\n *\n *

A null string input returns null.\n * An empty (\"\") string input returns an empty string.\n * A null or empty set of search characters returns the input string.

\n *\n *

The length of the search characters should normally equal the length\n * of the replace characters.\n * If the search characters is longer, then the extra search characters\n * are deleted.\n * If the search characters is shorter, then the extra replace characters\n * are ignored.

\n *\n *
\n     * StringUtils.replaceChars(null, *, *)           = null\n     * StringUtils.replaceChars(\"\", *, *)             = \"\"\n     * StringUtils.replaceChars(\"abc\", null, *)       = \"abc\"\n     * StringUtils.replaceChars(\"abc\", \"\", *)         = \"abc\"\n     * StringUtils.replaceChars(\"abc\", \"b\", null)     = \"ac\"\n     * StringUtils.replaceChars(\"abc\", \"b\", \"\")       = \"ac\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"yz\")  = \"ayzya\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"y\")   = \"ayya\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"yzx\") = \"ayzya\"\n     * 
\n *\n * @param str String to replace characters in, may be null\n * @param searchChars a set of characters to search for, may be null\n * @param replaceChars a set of characters to replace, may be null\n * @return modified String, null if null string input\n * @since 2.0\n */\n public static String replaceChars(final String str, final String searchChars, String replaceChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return str;\n }\n if (replaceChars == null) {\n replaceChars = StringUtils.EMPTY;\n }\n boolean modified = false;\n int replaceCharsLength = replaceChars.length();\n int strLength = str.length();\n StringBuilder buf = new StringBuilder(strLength);\n for (int i = 0; i < strLength; i++) {\n char ch = str.charAt(i);\n int index = searchChars.indexOf(ch);\n if (index >= 0) {\n modified = true;\n if (index < replaceCharsLength) {\n buf.append(replaceChars.charAt(index));\n }\n } else {\n buf.append(ch);\n }\n }\n if (modified) {\n return buf.toString();\n }\n return str;\n }\n // Overlay\n //-----------------------------------------------------------------------\n\n /**\n *

Overlays part of a String with another String.

\n *\n *

A null string input returns null.\n * A negative index is treated as zero.\n * An index greater than the string length is treated as the string length.\n * The start index is always the smaller of the two indices.

\n *\n *
\n     * StringUtils.overlay(null, *, *, *)            = null\n     * StringUtils.overlay(\"\", \"abc\", 0, 0)          = \"abc\"\n     * StringUtils.overlay(\"abcdef\", null, 2, 4)     = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"\", 2, 4)       = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"\", 4, 2)       = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 2, 4)   = \"abzzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 4, 2)   = \"abzzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", -1, 4)  = \"zzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 2, 8)   = \"abzzzz\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", -2, -3) = \"zzzzabcdef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 8, 10)  = \"abcdefzzzz\"\n     * 
\n *\n * @param str the String to do overlaying in, may be null\n * @param overlay the String to overlay, may be null\n * @param start the position to start overlaying at\n * @param end the position to stop overlaying before\n * @return overlayed String, null if null String input\n * @since 2.0\n */\n public static String overlay(final String str, String overlay, int start, int end) {\n if (str == null) {\n return null;\n }\n if (overlay == null) {\n overlay = StringUtils.EMPTY;\n }\n int len = str.length();\n if (start < 0) {\n start = 0;\n }\n if (start > len) {\n start = len;\n }\n if (end < 0) {\n end = 0;\n }\n if (end > len) {\n end = len;\n }\n if (start > end) {\n int temp = start;\n start = end;\n end = temp;\n }\n return str.substring(0, start) + overlay + str.substring(end);\n }\n // Chomping\n //-----------------------------------------------------------------------\n\n /**\n *

Removes one newline from end of a String if it's there,\n * otherwise leave it alone. A newline is "\\n",\n * "\\r", or "\\r\\n".

\n *\n *

NOTE: This method changed in 2.0.\n * It now more closely matches Perl chomp.

\n *\n *
\n     * StringUtils.chomp(null)          = null\n     * StringUtils.chomp(\"\")            = \"\"\n     * StringUtils.chomp(\"abc \\r\")      = \"abc \"\n     * StringUtils.chomp(\"abc\\n\")       = \"abc\"\n     * StringUtils.chomp(\"abc\\r\\n\")     = \"abc\"\n     * StringUtils.chomp(\"abc\\r\\n\\r\\n\") = \"abc\\r\\n\"\n     * StringUtils.chomp(\"abc\\n\\r\")     = \"abc\\n\"\n     * StringUtils.chomp(\"abc\\n\\rabc\")  = \"abc\\n\\rabc\"\n     * StringUtils.chomp(\"\\r\")          = \"\"\n     * StringUtils.chomp(\"\\n\")          = \"\"\n     * StringUtils.chomp(\"\\r\\n\")        = \"\"\n     * 
\n *\n * @param str the String to chomp a newline from, may be null\n * @return String without newline, null if null String input\n */\n public static String chomp(final String str) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (str.length() == 1) {\n char ch = str.charAt(0);\n if (ch == CharUtils.CR || ch == CharUtils.LF) {\n return StringUtils.EMPTY;\n }\n return str;\n }\n int lastIdx = str.length() - 1;\n char last = str.charAt(lastIdx);\n if (last == CharUtils.LF) {\n if (str.charAt(lastIdx - 1) == CharUtils.CR) {\n lastIdx--;\n }\n } else if (last != CharUtils.CR) {\n lastIdx++;\n }\n return str.substring(0, lastIdx);\n }\n\n /**\n *

Removes separator from the end of\n * str if it's there, otherwise leave it alone.

\n *\n *

NOTE: This method changed in version 2.0.\n * It now more closely matches Perl chomp.\n * For the previous behavior, use {@link #substringBeforeLast(String, String)}.\n * This method uses {@link String#endsWith(String)}.

\n *\n *
\n     * StringUtils.chomp(null, *)         = null\n     * StringUtils.chomp(\"\", *)           = \"\"\n     * StringUtils.chomp(\"foobar\", \"bar\") = \"foo\"\n     * StringUtils.chomp(\"foobar\", \"baz\") = \"foobar\"\n     * StringUtils.chomp(\"foo\", \"foo\")    = \"\"\n     * StringUtils.chomp(\"foo \", \"foo\")   = \"foo \"\n     * StringUtils.chomp(\" foo\", \"foo\")   = \" \"\n     * StringUtils.chomp(\"foo\", \"foooo\")  = \"foo\"\n     * StringUtils.chomp(\"foo\", \"\")       = \"foo\"\n     * StringUtils.chomp(\"foo\", null)     = \"foo\"\n     * 
\n *\n * @param str the String to chomp from, may be null\n * @param separator separator String, may be null\n * @return String without trailing separator, null if null String input\n */\n public static String chomp(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || separator == null) {\n return str;\n }\n if (str.endsWith(separator)) {\n return str.substring(0, str.length() - separator.length());\n }\n return str;\n }\n // Chopping\n //-----------------------------------------------------------------------\n\n /**\n *

Remove the last character from a String.

\n *\n *

If the String ends in \\r\\n, then remove both\n * of them.

\n *\n *
\n     * StringUtils.chop(null)          = null\n     * StringUtils.chop(\"\")            = \"\"\n     * StringUtils.chop(\"abc \\r\")      = \"abc \"\n     * StringUtils.chop(\"abc\\n\")       = \"abc\"\n     * StringUtils.chop(\"abc\\r\\n\")     = \"abc\"\n     * StringUtils.chop(\"abc\")         = \"ab\"\n     * StringUtils.chop(\"abc\\nabc\")    = \"abc\\nab\"\n     * StringUtils.chop(\"a\")           = \"\"\n     * StringUtils.chop(\"\\r\")          = \"\"\n     * StringUtils.chop(\"\\n\")          = \"\"\n     * StringUtils.chop(\"\\r\\n\")        = \"\"\n     * 
\n *\n * @param str the String to chop last character from, may be null\n * @return String without last character, null if null String input\n */\n public static String chop(final String str) {\n if (str == null) {\n return null;\n }\n int strLen = str.length();\n if (strLen < 2) {\n return StringUtils.EMPTY;\n }\n int lastIdx = strLen - 1;\n String ret = str.substring(0, lastIdx);\n char last = str.charAt(lastIdx);\n if (last == CharUtils.LF) {\n if (ret.charAt(lastIdx - 1) == CharUtils.CR) {\n return ret.substring(0, lastIdx - 1);\n }\n }\n return ret;\n }\n // Padding\n //-----------------------------------------------------------------------\n\n /**\n *

Repeat a String repeat times to form a\n * new String.

\n *\n *
\n     * StringUtils.repeat(null, 2) = null\n     * StringUtils.repeat(\"\", 0)   = \"\"\n     * StringUtils.repeat(\"\", 2)   = \"\"\n     * StringUtils.repeat(\"a\", 3)  = \"aaa\"\n     * StringUtils.repeat(\"ab\", 2) = \"abab\"\n     * StringUtils.repeat(\"a\", -2) = \"\"\n     * 
\n *\n * @param character the Character to to repeat, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n */\n public static String repeat(final char character, final int repeat) {\n return repeat(character + \"\", repeat);\n }\n\n /**\n *

Repeat a String repeat times to form a\n * new String.

\n *\n *
\n     * StringUtils.repeat(null, 2) = null\n     * StringUtils.repeat(\"\", 0)   = \"\"\n     * StringUtils.repeat(\"\", 2)   = \"\"\n     * StringUtils.repeat(\"a\", 3)  = \"aaa\"\n     * StringUtils.repeat(\"ab\", 2) = \"abab\"\n     * StringUtils.repeat(\"a\", -2) = \"\"\n     * 
\n *\n * @param str the String to repeat, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n */\n public static String repeat(final String str, final int repeat) {\n // Performance tuned for 2.0 (JDK1.4)\n if (str == null) {\n return null;\n }\n if (repeat <= 0) {\n return StringUtils.EMPTY;\n }\n int inputLength = str.length();\n if (repeat == 1 || inputLength == 0) {\n return str;\n }\n if (inputLength == 1 && repeat <= StringUtils.PAD_LIMIT) {\n return StringUtils.padding(repeat, str.charAt(0));\n }\n int outputLength = inputLength * repeat;\n switch (inputLength) {\n case 1:\n char ch = str.charAt(0);\n char[] output1 = new char[outputLength];\n for (int i = repeat - 1; i >= 0; i--) {\n output1[i] = ch;\n }\n return new String(output1);\n case 2:\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n char[] output2 = new char[outputLength];\n for (int i = repeat * 2 - 2; i >= 0; i--, i--) {\n output2[i] = ch0;\n output2[i + 1] = ch1;\n }\n return new String(output2);\n default:\n StringBuilder buf = new StringBuilder(outputLength);\n for (int i = 0; i < repeat; i++) {\n buf.append(str);\n }\n return buf.toString();\n }\n }\n\n /**\n *

Repeat a String repeat times to form a\n * new String, with a String separator injected each time.

\n *\n *
\n     * StringUtils.repeat(null, null, 2) = null\n     * StringUtils.repeat(null, \"x\", 2)  = null\n     * StringUtils.repeat(\"\", null, 0)   = \"\"\n     * StringUtils.repeat(\"\", \"\", 2)     = \"\"\n     * StringUtils.repeat(\"\", \"x\", 3)    = \"xxx\"\n     * StringUtils.repeat(\"?\", \", \", 3)  = \"?, ?, ?\"\n     * 
\n *\n * @param str the String to repeat, may be null\n * @param separator the String to inject, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n * @since 2.5\n */\n public static String repeat(final String str, final String separator, final int repeat) {\n if (str == null || separator == null) {\n return StringUtils.repeat(str, repeat);\n } else {\n // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it\n String result = StringUtils.repeat(str + separator, repeat);\n return StringUtils.removeEnd(result, separator);\n }\n }\n\n /**\n *

Returns padding using the specified delimiter repeated\n * to a given length.

\n *\n *
\n     * StringUtils.padding(0, 'e')  = \"\"\n     * StringUtils.padding(3, 'e')  = \"eee\"\n     * StringUtils.padding(-2, 'e') = IndexOutOfBoundsException\n     * 
\n *\n *

Note: this method doesn't not support padding with\n * Unicode Supplementary Characters\n * as they require a pair of chars to be represented.\n * If you are needing to support full I18N of your applications\n * consider using {@link #repeat(String, int)} instead.\n *

\n *\n * @param repeat number of times to repeat delim\n * @param padChar character to repeat\n * @return String with repeated character\n * @throws IndexOutOfBoundsException if repeat < 0\n * @see #repeat(String, int)\n */\n private static String padding(final int repeat, final char padChar) throws IndexOutOfBoundsException {\n if (repeat < 0) {\n throw new IndexOutOfBoundsException(\"Cannot pad a negative amount: \" + repeat);\n }\n final char[] buf = new char[repeat];\n Arrays.fill(buf, padChar);\n return new String(buf);\n }\n\n /**\n *

Right pad a String with spaces (' ').

\n *\n *

The String is padded to the size of size.

\n *\n *
\n     * StringUtils.rightPad(null, *)   = null\n     * StringUtils.rightPad(\"\", 3)     = \"   \"\n     * StringUtils.rightPad(\"bat\", 3)  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5)  = \"bat  \"\n     * StringUtils.rightPad(\"bat\", 1)  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1) = \"bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String rightPad(final String str, final int size) {\n return StringUtils.rightPad(str, size, ' ');\n }\n\n /**\n *

Right pad a String with a specified character.

\n *\n *

The String is padded to the size of size.

\n *\n *
\n     * StringUtils.rightPad(null, *, *)     = null\n     * StringUtils.rightPad(\"\", 3, 'z')     = \"zzz\"\n     * StringUtils.rightPad(\"bat\", 3, 'z')  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, 'z')  = \"batzz\"\n     * StringUtils.rightPad(\"bat\", 1, 'z')  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1, 'z') = \"bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padChar the character to pad with\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n * @since 2.0\n */\n public static String rightPad(final String str, final int size, final char padChar) {\n if (str == null) {\n return null;\n }\n int pads = size - str.length();\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (pads > StringUtils.PAD_LIMIT) {\n return StringUtils.rightPad(str, size, String.valueOf(padChar));\n }\n return str.concat(StringUtils.padding(pads, padChar));\n }\n\n /**\n *

Right pad a String with a specified String.

\n *\n *

The String is padded to the size of size.

\n *\n *
\n     * StringUtils.rightPad(null, *, *)      = null\n     * StringUtils.rightPad(\"\", 3, \"z\")      = \"zzz\"\n     * StringUtils.rightPad(\"bat\", 3, \"yz\")  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, \"yz\")  = \"batyz\"\n     * StringUtils.rightPad(\"bat\", 8, \"yz\")  = \"batyzyzy\"\n     * StringUtils.rightPad(\"bat\", 1, \"yz\")  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1, \"yz\") = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, null)  = \"bat  \"\n     * StringUtils.rightPad(\"bat\", 5, \"\")    = \"bat  \"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padStr the String to pad with, null or empty treated as single space\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String rightPad(final String str, final int size, String padStr) {\n if (str == null) {\n return null;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int padLen = padStr.length();\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (padLen == 1 && pads <= StringUtils.PAD_LIMIT) {\n return StringUtils.rightPad(str, size, padStr.charAt(0));\n }\n if (pads == padLen) {\n return str.concat(padStr);\n } else if (pads < padLen) {\n return str.concat(padStr.substring(0, pads));\n } else {\n char[] padding = new char[pads];\n char[] padChars = padStr.toCharArray();\n for (int i = 0; i < pads; i++) {\n padding[i] = padChars[i % padLen];\n }\n return str.concat(new String(padding));\n }\n }\n\n /**\n *

Left pad a String with spaces (' ').

\n *\n *

The String is padded to the size of size.

\n *\n *
\n     * StringUtils.leftPad(null, *)   = null\n     * StringUtils.leftPad(\"\", 3)     = \"   \"\n     * StringUtils.leftPad(\"bat\", 3)  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5)  = \"  bat\"\n     * StringUtils.leftPad(\"bat\", 1)  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1) = \"bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String leftPad(final String str, final int size) {\n return StringUtils.leftPad(str, size, ' ');\n }\n\n /**\n *

Left pad a String with a specified character.

\n *\n *

Pad to a size of size.

\n *\n *
\n     * StringUtils.leftPad(null, *, *)     = null\n     * StringUtils.leftPad(\"\", 3, 'z')     = \"zzz\"\n     * StringUtils.leftPad(\"bat\", 3, 'z')  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, 'z')  = \"zzbat\"\n     * StringUtils.leftPad(\"bat\", 1, 'z')  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1, 'z') = \"bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padChar the character to pad with\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n * @since 2.0\n */\n public static String leftPad(final String str, final int size, final char padChar) {\n if (str == null) {\n return null;\n }\n int pads = size - str.length();\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (pads > StringUtils.PAD_LIMIT) {\n return StringUtils.leftPad(str, size, String.valueOf(padChar));\n }\n return StringUtils.padding(pads, padChar).concat(str);\n }\n\n /**\n *

Left pad a String with a specified String.

\n *\n *

Pad to a size of size.

\n *\n *
\n     * StringUtils.leftPad(null, *, *)      = null\n     * StringUtils.leftPad(\"\", 3, \"z\")      = \"zzz\"\n     * StringUtils.leftPad(\"bat\", 3, \"yz\")  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, \"yz\")  = \"yzbat\"\n     * StringUtils.leftPad(\"bat\", 8, \"yz\")  = \"yzyzybat\"\n     * StringUtils.leftPad(\"bat\", 1, \"yz\")  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1, \"yz\") = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, null)  = \"  bat\"\n     * StringUtils.leftPad(\"bat\", 5, \"\")    = \"  bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padStr the String to pad with, null or empty treated as single space\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String leftPad(final String str, final int size, String padStr) {\n if (str == null) {\n return null;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int padLen = padStr.length();\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (padLen == 1 && pads <= StringUtils.PAD_LIMIT) {\n return StringUtils.leftPad(str, size, padStr.charAt(0));\n }\n if (pads == padLen) {\n return padStr.concat(str);\n } else if (pads < padLen) {\n return padStr.substring(0, pads).concat(str);\n } else {\n char[] padding = new char[pads];\n char[] padChars = padStr.toCharArray();\n for (int i = 0; i < pads; i++) {\n padding[i] = padChars[i % padLen];\n }\n return new String(padding).concat(str);\n }\n }\n\n /**\n * Gets a String's length or 0 if the String is null.\n *\n * @param str\n * a String or null\n * @return String length or 0 if the String is null.\n * @since 2.4\n */\n public static int length(final String str) {\n return str == null ? 0 : str.length();\n }\n // Centering\n //-----------------------------------------------------------------------\n\n /**\n *

Centers a String in a larger String of size size\n * using the space character (' ').

\n *\n *

If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

\n *\n *

Equivalent to center(str, size, \" \").

\n *\n *
\n     * StringUtils.center(null, *)   = null\n     * StringUtils.center(\"\", 4)     = \"    \"\n     * StringUtils.center(\"ab\", -1)  = \"ab\"\n     * StringUtils.center(\"ab\", 4)   = \" ab \"\n     * StringUtils.center(\"abcd\", 2) = \"abcd\"\n     * StringUtils.center(\"a\", 4)    = \" a  \"\n     * 
\n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @return centered String, null if null String input\n */\n public static String center(final String str, final int size) {\n return StringUtils.center(str, size, ' ');\n }\n\n /**\n *

Centers a String in a larger String of size size.\n * Uses a supplied character as the value to pad the String with.

\n *\n *

If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

\n *\n *
\n     * StringUtils.center(null, *, *)     = null\n     * StringUtils.center(\"\", 4, ' ')     = \"    \"\n     * StringUtils.center(\"ab\", -1, ' ')  = \"ab\"\n     * StringUtils.center(\"ab\", 4, ' ')   = \" ab\"\n     * StringUtils.center(\"abcd\", 2, ' ') = \"abcd\"\n     * StringUtils.center(\"a\", 4, ' ')    = \" a  \"\n     * StringUtils.center(\"a\", 4, 'y')    = \"yayy\"\n     * 
\n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @param padChar the character to pad the new String with\n * @return centered String, null if null String input\n * @since 2.0\n */\n public static String center(String str, final int size, final char padChar) {\n if (str == null || size <= 0) {\n return str;\n }\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str;\n }\n str = StringUtils.leftPad(str, strLen + pads / 2, padChar);\n str = StringUtils.rightPad(str, size, padChar);\n return str;\n }\n\n /**\n *

Centers a String in a larger String of size size.\n * Uses a supplied String as the value to pad the String with.

\n *\n *

If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

\n *\n *
\n     * StringUtils.center(null, *, *)     = null\n     * StringUtils.center(\"\", 4, \" \")     = \"    \"\n     * StringUtils.center(\"ab\", -1, \" \")  = \"ab\"\n     * StringUtils.center(\"ab\", 4, \" \")   = \" ab\"\n     * StringUtils.center(\"abcd\", 2, \" \") = \"abcd\"\n     * StringUtils.center(\"a\", 4, \" \")    = \" a  \"\n     * StringUtils.center(\"a\", 4, \"yz\")   = \"yayz\"\n     * StringUtils.center(\"abc\", 7, null) = \"  abc  \"\n     * StringUtils.center(\"abc\", 7, \"\")   = \"  abc  \"\n     * 
\n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @param padStr the String to pad the new String with, must not be null or empty\n * @return centered String, null if null String input\n * @throws IllegalArgumentException if padStr is null or empty\n */\n public static String center(String str, final int size, String padStr) {\n if (str == null || size <= 0) {\n return str;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str;\n }\n str = StringUtils.leftPad(str, strLen + pads / 2, padStr);\n str = StringUtils.rightPad(str, size, padStr);\n return str;\n }\n // Case conversion\n //-----------------------------------------------------------------------\n\n /**\n *

Converts a String to upper case as per {@link String#toUpperCase()}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.upperCase(null)  = null\n     * StringUtils.upperCase(\"\")    = \"\"\n     * StringUtils.upperCase(\"aBc\") = \"ABC\"\n     * 
\n *\n *

Note: As described in the documentation for {@link String#toUpperCase()},\n * the result of this method is affected by the current locale.\n * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}\n * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

\n *\n * @param str the String to upper case, may be null\n * @return the upper cased String, null if null String input\n */\n public static String upperCase(final String str) {\n if (str == null) {\n return null;\n }\n return str.toUpperCase();\n }\n\n /**\n *

Converts a String to upper case as per {@link String#toUpperCase(Locale)}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.upperCase(null, Locale.ENGLISH)  = null\n     * StringUtils.upperCase(\"\", Locale.ENGLISH)    = \"\"\n     * StringUtils.upperCase(\"aBc\", Locale.ENGLISH) = \"ABC\"\n     * 
\n *\n * @param str the String to upper case, may be null\n * @param locale the locale that defines the case transformation rules, must not be null\n * @return the upper cased String, null if null String input\n * @since 2.5\n */\n public static String upperCase(final String str, final Locale locale) {\n if (str == null) {\n return null;\n }\n return str.toUpperCase(locale);\n }\n\n /**\n *

Converts a String to lower case as per {@link String#toLowerCase()}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.lowerCase(null)  = null\n     * StringUtils.lowerCase(\"\")    = \"\"\n     * StringUtils.lowerCase(\"aBc\") = \"abc\"\n     * 
\n *\n *

Note: As described in the documentation for {@link String#toLowerCase()},\n * the result of this method is affected by the current locale.\n * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}\n * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

\n *\n * @param str the String to lower case, may be null\n * @return the lower cased String, null if null String input\n */\n public static String lowerCase(final String str) {\n if (str == null) {\n return null;\n }\n return str.toLowerCase();\n }\n\n /**\n *

Converts a String to lower case as per {@link String#toLowerCase(Locale)}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.lowerCase(null, Locale.ENGLISH)  = null\n     * StringUtils.lowerCase(\"\", Locale.ENGLISH)    = \"\"\n     * StringUtils.lowerCase(\"aBc\", Locale.ENGLISH) = \"abc\"\n     * 
\n *\n * @param str the String to lower case, may be null\n * @param locale the locale that defines the case transformation rules, must not be null\n * @return the lower cased String, null if null String input\n * @since 2.5\n */\n public static String lowerCase(final String str, final Locale locale) {\n if (str == null) {\n return null;\n }\n return str.toLowerCase(locale);\n }\n\n /**\n *

Capitalizes a String changing the first letter to title case as\n * per {@link Character#toTitleCase(char)}. No other letters are changed.

\n *\n * A null input String returns null.

\n *\n *
\n     * StringUtils.capitalize(null)  = null\n     * StringUtils.capitalize(\"\")    = \"\"\n     * StringUtils.capitalize(\"cat\") = \"Cat\"\n     * StringUtils.capitalize(\"cAt\") = \"CAt\"\n     * 
\n *\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null String input\n * @see #uncapitalize(String)\n * @since 2.0\n */\n public static String capitalize(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n return Character.toTitleCase(str.charAt(0)) + str.substring(1);\n }\n\n /**\n *

Uncapitalizes a String changing the first letter to title case as\n * per {@link Character#toLowerCase(char)}. No other letters are changed.

\n *\n * A null input String returns null.

\n *\n *
\n     * StringUtils.uncapitalize(null)  = null\n     * StringUtils.uncapitalize(\"\")    = \"\"\n     * StringUtils.uncapitalize(\"Cat\") = \"cat\"\n     * StringUtils.uncapitalize(\"CAT\") = \"cAT\"\n     * 
\n *\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null String input\n * @see #capitalize(String)\n * @since 2.0\n */\n public static String uncapitalize(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n return Character.toLowerCase(str.charAt(0)) + str.substring(1);\n }\n\n /**\n *

Swaps the case of a String changing upper and title case to\n * lower case, and lower case to upper case.

\n *\n *
    \n *
  • Upper case character converts to Lower case
  • \n *
  • Title case character converts to Lower case
  • \n *
  • Lower case character converts to Upper case
  • \n *
\n *\n * A null input String returns null.

\n *\n *
\n     * StringUtils.swapCase(null)                 = null\n     * StringUtils.swapCase(\"\")                   = \"\"\n     * StringUtils.swapCase(\"The dog has a BONE\") = \"tHE DOG HAS A bone\"\n     * 
\n *\n *

NOTE: This method changed in Lang version 2.0.\n * It no longer performs a word based algorithm.\n * If you only use ASCII, you will notice no change.\n * That functionality is available in WordUtils.

\n *\n * @param str the String to swap case, may be null\n * @return the changed String, null if null String input\n */\n public static String swapCase(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n StringBuilder buffer = new StringBuilder(strLen);\n char ch = 0;\n for (int i = 0; i < strLen; i++) {\n ch = str.charAt(i);\n if (Character.isUpperCase(ch)) {\n ch = Character.toLowerCase(ch);\n } else if (Character.isTitleCase(ch)) {\n ch = Character.toLowerCase(ch);\n } else if (Character.isLowerCase(ch)) {\n ch = Character.toUpperCase(ch);\n }\n buffer.append(ch);\n }\n return buffer.toString();\n }\n // Count matches\n //-----------------------------------------------------------------------\n\n /**\n *

Counts how many times the substring appears in the larger String.

\n *\n *

A null or empty (\"\") String input returns 0.

\n *\n *
\n     * StringUtils.countMatches(null, *)       = 0\n     * StringUtils.countMatches(\"\", *)         = 0\n     * StringUtils.countMatches(\"abba\", null)  = 0\n     * StringUtils.countMatches(\"abba\", \"\")    = 0\n     * StringUtils.countMatches(\"abba\", \"a\")   = 2\n     * StringUtils.countMatches(\"abba\", \"ab\")  = 1\n     * StringUtils.countMatches(\"abba\", \"xxx\") = 0\n     * 
\n *\n * @param str the String to check, may be null\n * @param sub the substring to count, may be null\n * @return the number of occurrences, 0 if either String is null\n */\n public static int countMatches(final String str, final String sub) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(sub)) {\n return 0;\n }\n int count = 0;\n int idx = 0;\n while ((idx = str.indexOf(sub, idx)) != StringUtils.INDEX_NOT_FOUND) {\n count++;\n idx += sub.length();\n }\n return count;\n }\n // Character Tests\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if the String contains only unicode letters.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAlpha(null)   = false\n     * StringUtils.isAlpha(\"\")     = true\n     * StringUtils.isAlpha(\"  \")   = false\n     * StringUtils.isAlpha(\"abc\")  = true\n     * StringUtils.isAlpha(\"ab2c\") = false\n     * StringUtils.isAlpha(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains letters, and is non-null\n */\n public static boolean isAlpha(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetter(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode letters and\n * space (' ').

\n *\n *

null will return false\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAlphaSpace(null)   = false\n     * StringUtils.isAlphaSpace(\"\")     = true\n     * StringUtils.isAlphaSpace(\"  \")   = true\n     * StringUtils.isAlphaSpace(\"abc\")  = true\n     * StringUtils.isAlphaSpace(\"ab c\") = true\n     * StringUtils.isAlphaSpace(\"ab2c\") = false\n     * StringUtils.isAlphaSpace(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains letters and space,\n * and is non-null\n */\n public static boolean isAlphaSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetter(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode letters or digits.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAlphanumeric(null)   = false\n     * StringUtils.isAlphanumeric(\"\")     = true\n     * StringUtils.isAlphanumeric(\"  \")   = false\n     * StringUtils.isAlphanumeric(\"abc\")  = true\n     * StringUtils.isAlphanumeric(\"ab c\") = false\n     * StringUtils.isAlphanumeric(\"ab2c\") = true\n     * StringUtils.isAlphanumeric(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains letters or digits,\n * and is non-null\n */\n public static boolean isAlphanumeric(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetterOrDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode letters, digits\n * or space (' ').

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAlphanumeric(null)   = false\n     * StringUtils.isAlphanumeric(\"\")     = true\n     * StringUtils.isAlphanumeric(\"  \")   = true\n     * StringUtils.isAlphanumeric(\"abc\")  = true\n     * StringUtils.isAlphanumeric(\"ab c\") = true\n     * StringUtils.isAlphanumeric(\"ab2c\") = true\n     * StringUtils.isAlphanumeric(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains letters, digits or space,\n * and is non-null\n */\n public static boolean isAlphanumericSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetterOrDigit(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the string contains only ASCII printable characters.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAsciiPrintable(null)     = false\n     * StringUtils.isAsciiPrintable(\"\")       = true\n     * StringUtils.isAsciiPrintable(\" \")      = true\n     * StringUtils.isAsciiPrintable(\"Ceki\")   = true\n     * StringUtils.isAsciiPrintable(\"ab2c\")   = true\n     * StringUtils.isAsciiPrintable(\"!ab-c~\") = true\n     * StringUtils.isAsciiPrintable(\"\\u0020\") = true\n     * StringUtils.isAsciiPrintable(\"\\u0021\") = true\n     * StringUtils.isAsciiPrintable(\"\\u007e\") = true\n     * StringUtils.isAsciiPrintable(\"\\u007f\") = false\n     * StringUtils.isAsciiPrintable(\"Ceki G\\u00fclc\\u00fc\") = false\n     * 
\n *\n * @param str the string to check, may be null\n * @return true if every character is in the range\n * 32 thru 126\n * @since 2.1\n */\n public static boolean isAsciiPrintable(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!CharUtils.isAsciiPrintable(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode digits.\n * A decimal point is not a unicode digit and returns false.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isNumeric(null)   = false\n     * StringUtils.isNumeric(\"\")     = true\n     * StringUtils.isNumeric(\"  \")   = false\n     * StringUtils.isNumeric(\"123\")  = true\n     * StringUtils.isNumeric(\"12 3\") = false\n     * StringUtils.isNumeric(\"ab2c\") = false\n     * StringUtils.isNumeric(\"12-3\") = false\n     * StringUtils.isNumeric(\"12.3\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains digits, and is non-null\n */\n public static boolean isNumeric(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode digits or space\n * (' ').\n * A decimal point is not a unicode digit and returns false.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isNumeric(null)   = false\n     * StringUtils.isNumeric(\"\")     = true\n     * StringUtils.isNumeric(\"  \")   = true\n     * StringUtils.isNumeric(\"123\")  = true\n     * StringUtils.isNumeric(\"12 3\") = true\n     * StringUtils.isNumeric(\"ab2c\") = false\n     * StringUtils.isNumeric(\"12-3\") = false\n     * StringUtils.isNumeric(\"12.3\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains digits or space,\n * and is non-null\n */\n public static boolean isNumericSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only whitespace.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isWhitespace(null)   = false\n     * StringUtils.isWhitespace(\"\")     = true\n     * StringUtils.isWhitespace(\"  \")   = true\n     * StringUtils.isWhitespace(\"abc\")  = false\n     * StringUtils.isWhitespace(\"ab2c\") = false\n     * StringUtils.isWhitespace(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains whitespace, and is non-null\n * @since 2.0\n */\n public static boolean isWhitespace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only lowercase characters.

\n *\n *

null will return false.\n * An empty String (length()=0) will return false.

\n *\n *
\n     * StringUtils.isAllLowerCase(null)   = false\n     * StringUtils.isAllLowerCase(\"\")     = false\n     * StringUtils.isAllLowerCase(\"  \")   = false\n     * StringUtils.isAllLowerCase(\"abc\")  = true\n     * StringUtils.isAllLowerCase(\"abC\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains lowercase characters, and is non-null\n * @since 2.5\n */\n public static boolean isAllLowerCase(final String str) {\n if (str == null || StringUtils.isEmpty(str)) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLowerCase(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only uppercase characters.

\n *\n *

null will return false.\n * An empty String (length()=0) will return false.

\n *\n *
\n     * StringUtils.isAllUpperCase(null)   = false\n     * StringUtils.isAllUpperCase(\"\")     = false\n     * StringUtils.isAllUpperCase(\"  \")   = false\n     * StringUtils.isAllUpperCase(\"ABC\")  = true\n     * StringUtils.isAllUpperCase(\"aBC\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains uppercase characters, and is non-null\n * @since 2.5\n */\n public static boolean isAllUpperCase(final String str) {\n if (str == null || StringUtils.isEmpty(str)) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isUpperCase(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n // Defaults\n //-----------------------------------------------------------------------\n\n /**\n *

Returns either the passed in String,\n * or if the String is null, an empty String (\"\").

\n *\n *
\n     * StringUtils.defaultString(null)  = \"\"\n     * StringUtils.defaultString(\"\")    = \"\"\n     * StringUtils.defaultString(\"bat\") = \"bat\"\n     * 
\n *\n * @see ObjectUtils#toString(Object)\n * @see String#valueOf(Object)\n * @param str the String to check, may be null\n * @return the passed in String, or the empty String if it\n * was null\n */\n public static String defaultString(final String str) {\n return str == null ? StringUtils.EMPTY : str;\n }\n\n /**\n *

Returns either the passed in String, or if the String is\n * null, the value of defaultStr.

\n *\n *
\n     * StringUtils.defaultString(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultString(\"\", \"NULL\")    = \"\"\n     * StringUtils.defaultString(\"bat\", \"NULL\") = \"bat\"\n     * 
\n *\n * @see ObjectUtils#toString(Object, String)\n * @see String#valueOf(Object)\n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is null, may be null\n * @return the passed in String, or the default if it was null\n */\n public static String defaultString(final String str, final String defaultStr) {\n return str == null ? defaultStr : str;\n }\n\n /**\n *

Returns either the passed in String, or if the String is\n * whitespace, empty (\"\") or null, the value of defaultStr.

\n *\n *
\n     * StringUtils.defaultIfBlank(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultIfBlank(\"\", \"NULL\")    = \"NULL\"\n     * StringUtils.defaultIfBlank(\" \", \"NULL\")   = \"NULL\"\n     * StringUtils.defaultIfBlank(\"bat\", \"NULL\") = \"bat\"\n     * StringUtils.defaultIfBlank(\"\", null)      = null\n     * 
\n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is whitespace, empty (\"\") or null, may be null\n * @return the passed in String, or the default\n * @see StringUtils#defaultString(String, String)\n * @since 2.6\n */\n public static String defaultIfBlank(final String str, final String defaultStr) {\n return StringUtils.isBlank(str) ? defaultStr : str;\n }\n\n /**\n *

Returns either the passed in String, or if the String is\n * empty or null, the value of defaultStr.

\n *\n *
\n     * StringUtils.defaultIfEmpty(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultIfEmpty(\"\", \"NULL\")    = \"NULL\"\n     * StringUtils.defaultIfEmpty(\"bat\", \"NULL\") = \"bat\"\n     * StringUtils.defaultIfEmpty(\"\", null)      = null\n     * 
\n *\n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is empty (\"\") or null, may be null\n * @return the passed in String, or the default\n * @see StringUtils#defaultString(String, String)\n */\n public static String defaultIfEmpty(final String str, final String defaultStr) {\n return StringUtils.isEmpty(str) ? defaultStr : str;\n }\n // Reversing\n //-----------------------------------------------------------------------\n\n /**\n *

Reverses a String as per {@link StringBuilder#reverse()}.

\n *\n *

A null String returns null.

\n *\n *
\n     * StringUtils.reverse(null)  = null\n     * StringUtils.reverse(\"\")    = \"\"\n     * StringUtils.reverse(\"bat\") = \"tab\"\n     * 
\n *\n * @param str the String to reverse, may be null\n * @return the reversed String, null if null String input\n */\n public static String reverse(final String str) {\n if (str == null) {\n return null;\n }\n return new StringBuilder(str).reverse().toString();\n }\n\n /**\n *

Reverses a String that is delimited by a specific character.

\n *\n *

The Strings between the delimiters are not reversed.\n * Thus java.lang.String becomes String.lang.java (if the delimiter\n * is '.').

\n *\n *
\n     * StringUtils.reverseDelimited(null, *)      = null\n     * StringUtils.reverseDelimited(\"\", *)        = \"\"\n     * StringUtils.reverseDelimited(\"a.b.c\", 'x') = \"a.b.c\"\n     * StringUtils.reverseDelimited(\"a.b.c\", \".\") = \"c.b.a\"\n     * 
\n *\n * @param str the String to reverse, may be null\n * @param separatorChar the separator character to use\n * @return the reversed String, null if null String input\n * @since 2.0\n */\n public static String reverseDelimited(final String str, final char separatorChar) {\n if (str == null) {\n return null;\n }\n // could implement manually, but simple way is to reuse other,\n // probably slower, methods.\n String[] strs = StringUtils.split(str, separatorChar);\n ArrayUtils.reverse(strs);\n return StringUtils.join(strs, separatorChar);\n }\n // Abbreviating\n //-----------------------------------------------------------------------\n\n /**\n *

Abbreviates a String using ellipses. This will turn\n * \"Now is the time for all good men\" into \"Now is the time for...\"

\n *\n *

Specifically:\n *

    \n *
  • If str is less than maxWidth characters\n * long, return it.
  • \n *
  • Else abbreviate it to (substring(str, 0, max-3) + \"...\").
  • \n *
  • If maxWidth is less than 4, throw an\n * IllegalArgumentException.
  • \n *
  • In no case will it return a String of length greater than\n * maxWidth.
  • \n *
\n *

\n *\n *
\n     * StringUtils.abbreviate(null, *)      = null\n     * StringUtils.abbreviate(\"\", 4)        = \"\"\n     * StringUtils.abbreviate(\"abcdefg\", 6) = \"abc...\"\n     * StringUtils.abbreviate(\"abcdefg\", 7) = \"abcdefg\"\n     * StringUtils.abbreviate(\"abcdefg\", 8) = \"abcdefg\"\n     * StringUtils.abbreviate(\"abcdefg\", 4) = \"a...\"\n     * StringUtils.abbreviate(\"abcdefg\", 3) = IllegalArgumentException\n     * 
\n *\n * @param str the String to check, may be null\n * @param maxWidth maximum length of result String, must be at least 4\n * @return abbreviated String, null if null String input\n * @throws IllegalArgumentException if the width is too small\n * @since 2.0\n */\n public static String abbreviate(final String str, final int maxWidth) {\n return StringUtils.abbreviate(str, 0, maxWidth);\n }\n\n /**\n *

Abbreviates a String using ellipses. This will turn\n * \"Now is the time for all good men\" into \"...is the time for...\"

\n *\n *

Works like abbreviate(String, int), but allows you to specify\n * a \"left edge\" offset. Note that this left edge is not necessarily going to\n * be the leftmost character in the result, or the first character following the\n * ellipses, but it will appear somewhere in the result.\n *\n *

In no case will it return a String of length greater than\n * maxWidth.

\n *\n *
\n     * StringUtils.abbreviate(null, *, *)                = null\n     * StringUtils.abbreviate(\"\", 0, 4)                  = \"\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", -1, 10) = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 0, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 1, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 4, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 5, 10)  = \"...fghi...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 6, 10)  = \"...ghij...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 8, 10)  = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 10, 10) = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 12, 10) = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghij\", 0, 3)        = IllegalArgumentException\n     * StringUtils.abbreviate(\"abcdefghij\", 5, 6)        = IllegalArgumentException\n     * 
\n *\n * @param str the String to check, may be null\n * @param offset left edge of source String\n * @param maxWidth maximum length of result String, must be at least 4\n * @return abbreviated String, null if null String input\n * @throws IllegalArgumentException if the width is too small\n * @since 2.0\n */\n public static String abbreviate(final String str, int offset, final int maxWidth) {\n if (str == null) {\n return null;\n }\n if (maxWidth < 4) {\n throw new IllegalArgumentException(\"Minimum abbreviation width is 4\");\n }\n if (str.length() <= maxWidth) {\n return str;\n }\n if (offset > str.length()) {\n offset = str.length();\n }\n if (str.length() - offset < maxWidth - 3) {\n offset = str.length() - (maxWidth - 3);\n }\n if (offset <= 4) {\n return str.substring(0, maxWidth - 3) + \"...\";\n }\n if (maxWidth < 7) {\n throw new IllegalArgumentException(\"Minimum abbreviation width with offset is 7\");\n }\n if (offset + maxWidth - 3 < str.length()) {\n return \"...\" + StringUtils.abbreviate(str.substring(offset), maxWidth - 3);\n }\n return \"...\" + str.substring(str.length() - (maxWidth - 3));\n }\n\n /**\n *

Abbreviates a String to the length passed, replacing the middle characters with the supplied\n * replacement String.

\n *\n *

This abbreviation only occurs if the following criteria is met:\n *

    \n *
  • Neither the String for abbreviation nor the replacement String are null or empty
  • \n *
  • The length to truncate to is less than the length of the supplied String
  • \n *
  • The length to truncate to is greater than 0
  • \n *
  • The abbreviated String will have enough room for the length supplied replacement String\n * and the first and last characters of the supplied String for abbreviation
  • \n *
\n * Otherwise, the returned String will be the same as the supplied String for abbreviation.\n *

\n *\n *
\n     * StringUtils.abbreviateMiddle(null, null, 0)      = null\n     * StringUtils.abbreviateMiddle(\"abc\", null, 0)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abc\", \".\", 0)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abc\", \".\", 3)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abcdef\", \".\", 4)     = \"ab.f\"\n     * 
\n *\n * @param str the String to abbreviate, may be null\n * @param middle the String to replace the middle characters with, may be null\n * @param length the length to abbreviate str to.\n * @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation.\n * @since 2.5\n */\n public static String abbreviateMiddle(final String str, final String middle, final int length) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(middle)) {\n return str;\n }\n if (length >= str.length() || length < middle.length() + 2) {\n return str;\n }\n int targetSting = length - middle.length();\n int startOffset = targetSting / 2 + targetSting % 2;\n int endOffset = str.length() - targetSting / 2;\n return str.substring(0, startOffset) + middle + str.substring(endOffset);\n }\n // Difference\n //-----------------------------------------------------------------------\n\n /**\n *

Compares two Strings, and returns the portion where they differ.\n * (More precisely, return the remainder of the second String,\n * starting from where it's different from the first.)

\n *\n *

For example,\n * difference(\"i am a machine\", \"i am a robot\") -> \"robot\".

\n *\n *
\n     * StringUtils.difference(null, null) = null\n     * StringUtils.difference(\"\", \"\") = \"\"\n     * StringUtils.difference(\"\", \"abc\") = \"abc\"\n     * StringUtils.difference(\"abc\", \"\") = \"\"\n     * StringUtils.difference(\"abc\", \"abc\") = \"\"\n     * StringUtils.difference(\"ab\", \"abxyz\") = \"xyz\"\n     * StringUtils.difference(\"abcde\", \"abxyz\") = \"xyz\"\n     * StringUtils.difference(\"abcde\", \"xyz\") = \"xyz\"\n     * 
\n *\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return the portion of str2 where it differs from str1; returns the\n * empty String if they are equal\n * @since 2.0\n */\n public static String difference(final String str1, final String str2) {\n if (str1 == null) {\n return str2;\n }\n if (str2 == null) {\n return str1;\n }\n int at = StringUtils.indexOfDifference(str1, str2);\n if (at == StringUtils.INDEX_NOT_FOUND) {\n return StringUtils.EMPTY;\n }\n return str2.substring(at);\n }\n\n /**\n *

Compares two Strings, and returns the index at which the\n * Strings begin to differ.

\n *\n *

For example,\n * indexOfDifference(\"i am a machine\", \"i am a robot\") -> 7

\n *\n *
\n     * StringUtils.indexOfDifference(null, null) = -1\n     * StringUtils.indexOfDifference(\"\", \"\") = -1\n     * StringUtils.indexOfDifference(\"\", \"abc\") = 0\n     * StringUtils.indexOfDifference(\"abc\", \"\") = 0\n     * StringUtils.indexOfDifference(\"abc\", \"abc\") = -1\n     * StringUtils.indexOfDifference(\"ab\", \"abxyz\") = 2\n     * StringUtils.indexOfDifference(\"abcde\", \"abxyz\") = 2\n     * StringUtils.indexOfDifference(\"abcde\", \"xyz\") = 0\n     * 
\n *\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return the index where str2 and str1 begin to differ; -1 if they are equal\n * @since 2.0\n */\n public static int indexOfDifference(final String str1, final String str2) {\n if (str1 != null && str1.equals(str2)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (str1 == null || str2 == null) {\n return 0;\n }\n int i;\n for (i = 0; i < str1.length() && i < str2.length(); ++i) {\n if (str1.charAt(i) != str2.charAt(i)) {\n break;\n }\n }\n if (i < str2.length() || i < str1.length()) {\n return i;\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Compares all Strings in an array and returns the index at which the\n * Strings begin to differ.

\n *\n *

For example,\n * indexOfDifference(new String[] {\"i am a machine\", \"i am a robot\"}) -> 7

\n *\n *
\n     * StringUtils.indexOfDifference(null) = -1\n     * StringUtils.indexOfDifference(new String[] {}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"abc\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {null, null}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"\", \"\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"\", null}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", null, null}) = 0\n     * StringUtils.indexOfDifference(new String[] {null, null, \"abc\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"\", \"abc\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"abc\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"a\"}) = 1\n     * StringUtils.indexOfDifference(new String[] {\"ab\", \"abxyz\"}) = 2\n     * StringUtils.indexOfDifference(new String[] {\"abcde\", \"abxyz\"}) = 2\n     * StringUtils.indexOfDifference(new String[] {\"abcde\", \"xyz\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"xyz\", \"abcde\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"i am a machine\", \"i am a robot\"}) = 7\n     * 
\n *\n * @param strs array of strings, entries may be null\n * @return the index where the strings begin to differ; -1 if they are all equal\n * @since 2.4\n */\n public static int indexOfDifference(final String[] strs) {\n if (strs == null || strs.length <= 1) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n boolean anyStringNull = false;\n boolean allStringsNull = true;\n int arrayLen = strs.length;\n int shortestStrLen = Integer.MAX_VALUE;\n int longestStrLen = 0;\n // find the min and max string lengths; this avoids checking to make\n // sure we are not exceeding the length of the string each time through\n // the bottom loop.\n for (int i = 0; i < arrayLen; i++) {\n if (strs[i] == null) {\n anyStringNull = true;\n shortestStrLen = 0;\n } else {\n allStringsNull = false;\n shortestStrLen = Math.min(strs[i].length(), shortestStrLen);\n longestStrLen = Math.max(strs[i].length(), longestStrLen);\n }\n }\n // handle lists containing all nulls or all empty strings\n if (allStringsNull || longestStrLen == 0 && !anyStringNull) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n // handle lists containing some nulls or some empty strings\n if (shortestStrLen == 0) {\n return 0;\n }\n // find the position with the first difference across all strings\n int firstDiff = -1;\n for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {\n char comparisonChar = strs[0].charAt(stringPos);\n for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {\n if (strs[arrayPos].charAt(stringPos) != comparisonChar) {\n firstDiff = stringPos;\n break;\n }\n }\n if (firstDiff != -1) {\n break;\n }\n }\n if (firstDiff == -1 && shortestStrLen != longestStrLen) {\n // we compared all of the characters up to the length of the\n // shortest string and didn't find a match, but the string lengths\n // vary, so return the length of the shortest string.\n return shortestStrLen;\n }\n return firstDiff;\n }\n\n /**\n *

Compares all Strings in an array and returns the initial sequence of\n * characters that is common to all of them.

\n *\n *

For example,\n * getCommonPrefix(new String[] {\"i am a machine\", \"i am a robot\"}) -> \"i am a \"

\n *\n *
\n     * StringUtils.getCommonPrefix(null) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\"}) = \"abc\"\n     * StringUtils.getCommonPrefix(new String[] {null, null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", \"\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", null, null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {null, null, \"abc\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", \"abc\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"abc\"}) = \"abc\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"a\"}) = \"a\"\n     * StringUtils.getCommonPrefix(new String[] {\"ab\", \"abxyz\"}) = \"ab\"\n     * StringUtils.getCommonPrefix(new String[] {\"abcde\", \"abxyz\"}) = \"ab\"\n     * StringUtils.getCommonPrefix(new String[] {\"abcde\", \"xyz\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"xyz\", \"abcde\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"i am a machine\", \"i am a robot\"}) = \"i am a \"\n     * 
\n *\n * @param strs array of String objects, entries may be null\n * @return the initial sequence of characters that are common to all Strings\n * in the array; empty String if the array is null, the elements are all null\n * or if there is no common prefix.\n * @since 2.4\n */\n public static String getCommonPrefix(final String[] strs) {\n if (strs == null || strs.length == 0) {\n return StringUtils.EMPTY;\n }\n int smallestIndexOfDiff = StringUtils.indexOfDifference(strs);\n if (smallestIndexOfDiff == StringUtils.INDEX_NOT_FOUND) {\n // all strings were identical\n if (strs[0] == null) {\n return StringUtils.EMPTY;\n }\n return strs[0];\n } else if (smallestIndexOfDiff == 0) {\n // there were no common initial characters\n return StringUtils.EMPTY;\n } else {\n // we found a common initial character sequence\n return strs[0].substring(0, smallestIndexOfDiff);\n }\n }\n // Misc\n //-----------------------------------------------------------------------\n\n /**\n *

Find the Levenshtein distance between two Strings.

\n *\n *

This is the number of changes needed to change one String into\n * another, where each change is a single character modification (deletion,\n * insertion or substitution).

\n *\n *

The previous implementation of the Levenshtein distance algorithm\n * was from http://www.merriampark.com/ld.htm

\n *\n *

Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError\n * which can occur when my Java implementation is used with very large strings.
\n * This implementation of the Levenshtein distance algorithm\n * is from http://www.merriampark.com/ldjava.htm

\n *\n *
\n     * StringUtils.getLevenshteinDistance(null, *)             = IllegalArgumentException\n     * StringUtils.getLevenshteinDistance(*, null)             = IllegalArgumentException\n     * StringUtils.getLevenshteinDistance(\"\",\"\")               = 0\n     * StringUtils.getLevenshteinDistance(\"\",\"a\")              = 1\n     * StringUtils.getLevenshteinDistance(\"aaapppp\", \"\")       = 7\n     * StringUtils.getLevenshteinDistance(\"frog\", \"fog\")       = 1\n     * StringUtils.getLevenshteinDistance(\"fly\", \"ant\")        = 3\n     * StringUtils.getLevenshteinDistance(\"elephant\", \"hippo\") = 7\n     * StringUtils.getLevenshteinDistance(\"hippo\", \"elephant\") = 7\n     * StringUtils.getLevenshteinDistance(\"hippo\", \"zzzzzzzz\") = 8\n     * StringUtils.getLevenshteinDistance(\"hello\", \"hallo\")    = 1\n     * 
\n *\n * @param s the first String, must not be null\n * @param t the second String, must not be null\n * @return result distance\n * @throws IllegalArgumentException if either String input null\n */\n public static int getLevenshteinDistance(String s, String t) {\n if (s == null || t == null) {\n throw new IllegalArgumentException(\"Strings must not be null\");\n }\n /*\n The difference between this impl. and the previous is that, rather\n than creating and retaining a matrix of size s.length()+1 by t.length()+1,\n we maintain two single-dimensional arrays of length s.length()+1. The first, d,\n is the 'current working' distance array that maintains the newest distance cost\n counts as we iterate through the characters of String s. Each time we increment\n the index of String t we are comparing, d is copied to p, the second int[]. Doing so\n allows us to retain the previous cost counts as required by the algorithm (taking\n the minimum of the cost count to the left, up one, and diagonally up and to the left\n of the current cost count being calculated). (Note that the arrays aren't really\n copied anymore, just switched...this is clearly much better than cloning an array\n or doing a System.arraycopy() each time through the outer loop.)\n\n Effectively, the difference between the two implementations is this one does not\n cause an out of memory condition when calculating the LD over two very large strings.\n */\n int n = s.length(); // length of s\n int m = t.length(); // length of t\n if (n == 0) {\n return m;\n } else if (m == 0) {\n return n;\n }\n if (n > m) {\n // swap the input strings to consume less memory\n String tmp = s;\n s = t;\n t = tmp;\n n = m;\n m = t.length();\n }\n int[] p = new int[n + 1]; //'previous' cost array, horizontally\n int[] d = new int[n + 1]; // cost array, horizontally\n int[] _d; //placeholder to assist in swapping p and d\n // indexes into strings s and t\n int i; // iterates through s\n int j; // iterates through t\n char t_j; // jth character of t\n int cost; // cost\n for (i = 0; i <= n; i++) {\n p[i] = i;\n }\n for (j = 1; j <= m; j++) {\n t_j = t.charAt(j - 1);\n d[0] = j;\n for (i = 1; i <= n; i++) {\n cost = s.charAt(i - 1) == t_j ? 0 : 1;\n // minimum of cell to the left+1, to the top+1, diagonally left and up +cost\n d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);\n }\n // copy current distance counts to 'previous row' distance counts\n _d = p;\n p = d;\n d = _d;\n }\n // our last action in the above loop was to switch d and p, so p now\n // actually has the most recent cost counts\n return p[n];\n }\n // startsWith\n //-----------------------------------------------------------------------\n\n /**\n *

Check if a String starts with a specified prefix.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

\n *\n *
\n     * StringUtils.startsWith(null, null)      = true\n     * StringUtils.startsWith(null, \"abc\")     = false\n     * StringUtils.startsWith(\"abcdef\", null)  = false\n     * StringUtils.startsWith(\"abcdef\", \"abc\") = true\n     * StringUtils.startsWith(\"ABCDEF\", \"abc\") = false\n     * 
\n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @return true if the String starts with the prefix, case sensitive, or\n * both null\n * @since 2.4\n */\n public static boolean startsWith(final String str, final String prefix) {\n return StringUtils.startsWith(str, prefix, false);\n }\n\n /**\n *

Case insensitive check if a String starts with a specified prefix.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case insensitive.

\n *\n *
\n     * StringUtils.startsWithIgnoreCase(null, null)      = true\n     * StringUtils.startsWithIgnoreCase(null, \"abc\")     = false\n     * StringUtils.startsWithIgnoreCase(\"abcdef\", null)  = false\n     * StringUtils.startsWithIgnoreCase(\"abcdef\", \"abc\") = true\n     * StringUtils.startsWithIgnoreCase(\"ABCDEF\", \"abc\") = true\n     * 
\n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @return true if the String starts with the prefix, case insensitive, or\n * both null\n * @since 2.4\n */\n public static boolean startsWithIgnoreCase(final String str, final String prefix) {\n return StringUtils.startsWith(str, prefix, true);\n }\n\n /**\n *

Check if a String starts with a specified prefix (optionally case insensitive).

\n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @param ignoreCase inidicates whether the compare should ignore case\n * (case insensitive) or not.\n * @return true if the String starts with the prefix or\n * both null\n */\n private static boolean startsWith(final String str, final String prefix, final boolean ignoreCase) {\n if (str == null || prefix == null) {\n return str == null && prefix == null;\n }\n if (prefix.length() > str.length()) {\n return false;\n }\n return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());\n }\n\n /**\n *

Check if a String starts with any of an array of specified strings.

\n *\n *
\n     * StringUtils.startsWithAny(null, null)      = false\n     * StringUtils.startsWithAny(null, new String[] {\"abc\"})  = false\n     * StringUtils.startsWithAny(\"abcxyz\", null)     = false\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {\"\"}) = false\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {\"abc\"}) = true\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {null, \"xyz\", \"abc\"}) = true\n     * 
\n *\n * @see #startsWith(String, String)\n * @param string the String to check, may be null\n * @param searchStrings the Strings to find, may be null or empty\n * @return true if the String starts with any of the the prefixes, case insensitive, or\n * both null\n * @since 2.5\n */\n public static boolean startsWithAny(final String string, final String[] searchStrings) {\n if (StringUtils.isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {\n return false;\n }\n for (String searchString : searchStrings) {\n if (StringUtils.startsWith(string, searchString)) {\n return true;\n }\n }\n return false;\n }\n // endsWith\n //-----------------------------------------------------------------------\n\n /**\n *

Check if a String ends with a specified suffix.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

\n *\n *
\n     * StringUtils.endsWith(null, null)      = true\n     * StringUtils.endsWith(null, \"def\")     = false\n     * StringUtils.endsWith(\"abcdef\", null)  = false\n     * StringUtils.endsWith(\"abcdef\", \"def\") = true\n     * StringUtils.endsWith(\"ABCDEF\", \"def\") = false\n     * StringUtils.endsWith(\"ABCDEF\", \"cde\") = false\n     * 
\n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @return true if the String ends with the suffix, case sensitive, or\n * both null\n * @since 2.4\n */\n public static boolean endsWith(final String str, final String suffix) {\n return StringUtils.endsWith(str, suffix, false);\n }\n\n /**\n *

Case insensitive check if a String ends with a specified suffix.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case insensitive.

\n *\n *
\n     * StringUtils.endsWithIgnoreCase(null, null)      = true\n     * StringUtils.endsWithIgnoreCase(null, \"def\")     = false\n     * StringUtils.endsWithIgnoreCase(\"abcdef\", null)  = false\n     * StringUtils.endsWithIgnoreCase(\"abcdef\", \"def\") = true\n     * StringUtils.endsWithIgnoreCase(\"ABCDEF\", \"def\") = true\n     * StringUtils.endsWithIgnoreCase(\"ABCDEF\", \"cde\") = false\n     * 
\n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @return true if the String ends with the suffix, case insensitive, or\n * both null\n * @since 2.4\n */\n public static boolean endsWithIgnoreCase(final String str, final String suffix) {\n return StringUtils.endsWith(str, suffix, true);\n }\n\n /**\n *

Check if a String ends with a specified suffix (optionally case insensitive).

\n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @param ignoreCase inidicates whether the compare should ignore case\n * (case insensitive) or not.\n * @return true if the String starts with the prefix or\n * both null\n */\n private static boolean endsWith(final String str, final String suffix, final boolean ignoreCase) {\n if (str == null || suffix == null) {\n return str == null && suffix == null;\n }\n if (suffix.length() > str.length()) {\n return false;\n }\n int strOffset = str.length() - suffix.length();\n return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());\n }\n\n /**\n *

\n * Similar to http://www.w3.org/TR/xpath/#function-normalize\n * -space\n *

\n *

\n * The function returns the argument string with whitespace normalized by using\n * {@link #trim(String)} to remove leading and trailing whitespace\n * and then replacing sequences of whitespace characters by a single space.\n *

\n * In XML Whitespace characters are the same as those allowed by the S production, which is S ::= (#x20 | #x9 | #xD | #xA)+\n *

\n * See Java's {@link Character#isWhitespace(char)} for which characters are considered whitespace.\n *

\n * The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also\n * normalize. Additonally {@link #trim(String)} removes control characters (char <= 32) from both\n * ends of this String.\n *

\n *\n * @see Character#isWhitespace(char)\n * @see #trim(String)\n * @see \n * http://www.w3.org/TR/xpath/#function-normalize-space\n * @param str the source String to normalize whitespaces from, may be null\n * @return the modified string with whitespace normalized, null if null String input\n *\n * @since 2.6\n */\n public static String normalizeSpace(String str) {\n str = StringUtils.strip(str);\n if (str == null || str.length() <= 2) {\n return str;\n }\n StringBuilder b = new StringBuilder(str.length());\n for (int i = 0; i < str.length(); i++) {\n char c = str.charAt(i);\n if (Character.isWhitespace(c)) {\n if (i > 0 && !Character.isWhitespace(str.charAt(i - 1))) {\n b.append(' ');\n }\n } else {\n b.append(c);\n }\n }\n return b.toString();\n }\n\n /**\n *

Check if a String ends with any of an array of specified strings.

\n *\n *
\n     * StringUtils.endsWithAny(null, null)      = false\n     * StringUtils.endsWithAny(null, new String[] {\"abc\"})  = false\n     * StringUtils.endsWithAny(\"abcxyz\", null)     = false\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {\"\"}) = true\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {\"xyz\"}) = true\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {null, \"xyz\", \"abc\"}) = true\n     * 
\n *\n * @param string the String to check, may be null\n * @param searchStrings the Strings to find, may be null or empty\n * @return true if the String ends with any of the the prefixes, case insensitive, or\n * both null\n * @since 2.6\n */\n public static boolean endsWithAny(final String string, final String[] searchStrings) {\n if (StringUtils.isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {\n return false;\n }\n for (String searchString : searchStrings) {\n if (StringUtils.endsWith(string, searchString)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 转换首字母大写。\n *
\n     * StringUtils.firstCharToUpperCase(null)      = null\n     * StringUtils.firstCharToUpperCase(\"\")        = \"\"\n     * StringUtils.firstCharToUpperCase(\"abc\")     = \"Abc\"\n     * StringUtils.firstCharToUpperCase(\"Abc\")     = \"Abc\"\n     * StringUtils.firstCharToUpperCase(\"ABC\")     = \"ABC\"\n     * 
\n */\n public static String firstCharToUpperCase(final String value) {\n if (StringUtils.isBlank(value)) {\n return value;\n }\n StringBuilder sb = new StringBuilder(value);\n char firstChar = sb.charAt(0);\n sb.delete(0, 1);\n sb.insert(0, (char) (firstChar >= 97 ? firstChar - 32 : firstChar));\n return sb.toString();\n }\n\n /**\n * 转换首字母小写。\n *
\n     * StringUtils.firstCharToLowerCase(null)      = null\n     * StringUtils.firstCharToLowerCase(\"\")        = \"\"\n     * StringUtils.firstCharToLowerCase(\"abc\")     = \"abc\"\n     * StringUtils.firstCharToLowerCase(\"Abc\")     = \"abc\"\n     * StringUtils.firstCharToLowerCase(\"ABC\")     = \"aBC\"\n     * 
\n */\n public static String firstCharToLowerCase(final String value) {\n if (StringUtils.isBlank(value)) {\n return value;\n }\n StringBuilder sb = new StringBuilder(value);\n char firstChar = sb.charAt(0);\n sb.delete(0, 1);\n sb.insert(0, (char) (firstChar <= 90 ? firstChar + 32 : firstChar));\n return sb.toString();\n }\n\n /**\n * 执行字符串匹配。\n *
\n     * StringUtils.equalsBlankIgnoreCase(null,\"\")         = true\n     * StringUtils.equalsBlankIgnoreCase(\"\",\"\")           = true\n     * StringUtils.equalsBlankIgnoreCase(\" \",\"\")          = true\n     * StringUtils.equalsBlankIgnoreCase(\" \",null)        = true\n     * StringUtils.equalsBlankIgnoreCase(\"bob\",\"\")        = false\n     * StringUtils.equalsBlankIgnoreCase(\"  bob  \",\"bob\") = true\n     * 
\n */\n public static boolean equalsBlankIgnoreCase(final String str1, final String str2) {\n return StringUtils.equalsIgnoreCase(StringUtils.trimToEmpty(str1), StringUtils.trimToEmpty(str2));\n }\n\n /* ------------------------------------------------------------ */\n private static final char[] escapes = new char[32];\n\n static {\n Arrays.fill(escapes, (char) 0xFFFF);\n escapes['\\b'] = 'b';\n escapes['\\t'] = 't';\n escapes['\\n'] = 'n';\n escapes['\\f'] = 'f';\n escapes['\\r'] = 'r';\n }\n\n /** Quote a string into an Appendable.\n * The characters \", \\, \\n, \\r, \\t, \\f and \\b are escaped\n * @param input The String to quote.\n */\n public static String quote(String input) {\n StringBuilder buffer = new StringBuilder();\n quote(buffer, input);\n return buffer.toString();\n }\n\n public static void quote(Appendable buffer, String input) {\n try {\n buffer.append('\"');\n for (int i = 0; i < input.length(); ++i) {\n char c = input.charAt(i);\n if (c >= 32) {\n if (c == '\"' || c == '\\\\')\n buffer.append('\\\\');\n buffer.append(c);\n } else {\n char escape = escapes[c];\n if (escape == 0xFFFF) {\n // Unicode escape\n buffer.append('\\\\').append('u').append('0').append('0');\n if (c < 0x10)\n buffer.append('0');\n buffer.append(Integer.toString(c, 16));\n } else {\n buffer.append('\\\\').append(escape);\n }\n }\n }\n buffer.append('\"');\n } catch (IOException x) {\n throw new RuntimeException(x);\n }\n }\n\n /** Object to String ,when null object then null else return toString(); */\n public static String toString(Object object) {\n return (object == null) ? null : object.toString();\n }\n}", "file_name": "StringUtils.java", "human_label": "Reverse the given String as per.", "level": "slib_runnable", "lineno": "5253", "name": "reverse", "oracle_context": "{ \"apis\" : \"[toString]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636766ff1a6d9265ec01783b", "all_context": "{ \"class_level\" : \"import net.hasor.core.Singleton;\\nimport net.hasor.dataql.UdfSourceAssembly;\\nimport net.hasor.utils.StringUtils;\\nimport java.util.Arrays;\\nimport java.util.List;\\nimport java.util.regex.Matcher;\\nimport java.util.regex.Pattern;\\nPattern linePattern;\\nPattern humpPattern;\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWith(String str,String suffix);\\nendsWithIgnoreCase(String str,String suffix);\\n_startsWith(String str,String prefix,boolean ignoreCase);\\n_endsWith(String str,String suffix,boolean ignoreCase);\\nlineToHump(String str);\\nhumpToLine(String str);\\nfirstCharToUpperCase(String value);\\nfirstCharToLowerCase(String value);\\ntoUpperCase(String value);\\ntoLowerCase(String value);\\nindexOf(String str,String searchStr);\\nindexOfWithStart(String str,String searchStr,int startPos);\\nindexOfIgnoreCase(String str,String searchStr);\\nindexOfIgnoreCaseWithStart(String str,String searchStr,int startPos);\\nlastIndexOf(String str,String searchStr);\\nlastIndexOfWithStart(String str,String searchChar,int startPos);\\nlastIndexOfIgnoreCase(String str,String searchStr);\\nlastIndexOfIgnoreCaseWithStart(String str,String searchStr,int startPos);\\ncontains(String str,String searchStr);\\ncontainsIgnoreCase(String str,String searchStr);\\ncontainsAny(String str,List searchStrArray);\\ncontainsAnyIgnoreCase(String str,List searchStrArray);\\ntrim(String str);\\nsub(String str,int start,int end);\\nleft(String str,int len);\\nright(String str,int len);\\nalignRight(String str,String padChar,int len);\\nalignLeft(String str,String padChar,int len);\\nalignCenter(String str,String padChar,int len);\\ncompareString(String str1,String str2);\\ncompareStringIgnoreCase(String str1,String str2);\\nsplit(String str,String separatorChars);\\njoin(List array,String separator);\\nisEmpty(String str);\\nequalsIgnoreCase(String str1,String str2);\\nstartsWith(String str,String prefix);\\n\", \"repo_level\" : \"public interface UdfSourceAssembly {default Supplier getSupplier(Class targetType,Finder finder);\\ndefault Predicate getPredicate(Class targetType);\\npublic Object[] allParams();\\ndefault Supplier> getUdfResource(Finder finder);\\npublic Class annotationType();\\npublic String value();\\npublic Object call(Hints readOnly,Object values);\\npublic Object call(Hints readOnly,Object values);\\n }\\npublic interface StringUtils {static boolean isEmpty(String str);\\nstatic boolean isNotEmpty(String str);\\nstatic boolean isBlank(String str);\\nstatic boolean isNotBlank(String str);\\nstatic String trim(String str);\\nstatic String trimToNull(String str);\\nstatic String trimToEmpty(String str);\\nstatic String strip(String str);\\nstatic String stripToNull(String str);\\nstatic String stripToEmpty(String str);\\nstatic String strip(String str,String stripChars);\\nstatic String stripStart(String str,String stripChars);\\nstatic String stripEnd(String str,String stripChars);\\nstatic String[] stripAll(String[] strs);\\nstatic String[] stripAll(String[] strs,String stripChars);\\nstatic boolean equals(String str1,String str2);\\nstatic boolean equalsIgnoreCase(String str1,String str2);\\nstatic int indexOf(String str,char searchChar);\\nstatic int indexOf(String str,char searchChar,int startPos);\\nstatic int indexOf(String str,String searchStr);\\nstatic int ordinalIndexOf(String str,String searchStr,int ordinal);\\nstatic int indexOf(String str,String searchStr,int startPos);\\nstatic int indexOfIgnoreCase(String str,String searchStr);\\nstatic int indexOfIgnoreCase(String str,String searchStr,int startPos);\\nstatic int lastIndexOf(String str,char searchChar);\\nstatic int lastIndexOf(String str,char searchChar,int startPos);\\nstatic int lastIndexOf(String str,String searchStr);\\nstatic int lastOrdinalIndexOf(String str,String searchStr,int ordinal);\\nstatic int lastIndexOf(String str,String searchStr,int startPos);\\nstatic int lastIndexOfIgnoreCase(String str,String searchStr);\\nstatic int lastIndexOfIgnoreCase(String str,String searchStr,int startPos);\\nstatic boolean contains(String str,char searchChar);\\nstatic boolean contains(String str,String searchStr);\\nstatic boolean containsIgnoreCase(String str,String searchStr);\\nstatic int indexOfAny(String str,char[] searchChars);\\nstatic int indexOfAny(String str,String searchChars);\\nstatic boolean containsAny(String str,char[] searchChars);\\nstatic boolean containsAny(String str,String searchChars);\\nstatic int indexOfAnyBut(String str,char[] searchChars);\\nstatic int indexOfAnyBut(String str,String searchChars);\\nstatic boolean containsOnly(String str,char[] valid);\\nstatic boolean containsOnly(String str,String validChars);\\nstatic boolean containsNone(String str,char[] searchChars);\\nstatic boolean containsNone(String str,String invalidChars);\\nstatic int indexOfAny(String str,String[] searchStrs);\\nstatic int lastIndexOfAny(String str,String[] searchStrs);\\nstatic String substring(String str,int start);\\nstatic String substring(String str,int start,int end);\\nstatic String left(String str,int len);\\nstatic String right(String str,int len);\\nstatic String mid(String str,int pos,int len);\\nstatic String substringBefore(String str,String separator);\\nstatic String substringAfter(String str,String separator);\\nstatic String substringBeforeLast(String str,String separator);\\nstatic String substringAfterLast(String str,String separator);\\nstatic String substringBetween(String str,String tag);\\nstatic String substringBetween(String str,String open,String close);\\nstatic String[] substringsBetween(String str,String open,String close);\\nstatic String[] splitKeep(String str,char separatorChar);\\nstatic String[] splitKeep(String str,String separatorStr);\\nstatic String[] split(String str);\\nstatic String[] split(String str,char separatorChar);\\nstatic String[] split(String str,String separatorChars);\\nstatic String[] split(String str,String separatorChars,int max);\\nstatic String[] splitByWholeSeparator(String str,String separator);\\nstatic String[] splitByWholeSeparator(String str,String separator,int max);\\nstatic String[] splitByWholeSeparatorPreserveAllTokens(String str,String separator);\\nstatic String[] splitByWholeSeparatorPreserveAllTokens(String str,String separator,int max);\\nstatic String[] splitPreserveAllTokens(String str);\\nstatic String[] splitPreserveAllTokens(String str,char separatorChar);\\nstatic String[] splitPreserveAllTokens(String str,String separatorChars);\\nstatic String[] splitPreserveAllTokens(String str,String separatorChars,int max);\\nstatic String[] splitByCharacterType(String str);\\nstatic String[] splitByCharacterTypeCamelCase(String str);\\nstatic String join(Object[] array);\\nstatic String join(Object[] array,char separator);\\nstatic String join(Object[] array,char separator,int startIndex,int endIndex);\\nstatic String join(Object[] array,String separator);\\nstatic String join(Object[] array,String separator,int startIndex,int endIndex);\\nstatic String deleteWhitespace(String str);\\nstatic String removeStart(String str,String remove);\\nstatic String removeStartIgnoreCase(String str,String remove);\\nstatic String removeEnd(String str,String remove);\\nstatic String removeEndIgnoreCase(String str,String remove);\\nstatic String remove(String str,String remove);\\nstatic String remove(String str,char remove);\\nstatic String replaceOnce(String text,String searchString,String replacement);\\nstatic String replace(String text,String searchString,String replacement);\\nstatic String replace(String text,String searchString,String replacement,int max);\\nstatic String replaceEach(String text,String[] searchList,String[] replacementList);\\nstatic String replaceEachRepeatedly(String text,String[] searchList,String[] replacementList);\\nstatic String replaceChars(String str,char searchChar,char replaceChar);\\nstatic String replaceChars(String str,String searchChars,String replaceChars);\\nstatic String overlay(String str,String overlay,int start,int end);\\nstatic String chomp(String str);\\nstatic String chomp(String str,String separator);\\nstatic String chop(String str);\\nstatic String repeat(char character,int repeat);\\nstatic String repeat(String str,int repeat);\\nstatic String repeat(String str,String separator,int repeat);\\nstatic String rightPad(String str,int size);\\nstatic String rightPad(String str,int size,char padChar);\\nstatic String rightPad(String str,int size,String padStr);\\nstatic String leftPad(String str,int size);\\nstatic String leftPad(String str,int size,char padChar);\\nstatic String leftPad(String str,int size,String padStr);\\nstatic int length(String str);\\nstatic String center(String str,int size);\\nstatic String center(String str,int size,char padChar);\\nstatic String center(String str,int size,String padStr);\\nstatic String upperCase(String str);\\nstatic String upperCase(String str,Locale locale);\\nstatic String lowerCase(String str);\\nstatic String lowerCase(String str,Locale locale);\\nstatic String capitalize(String str);\\nstatic String uncapitalize(String str);\\nstatic String swapCase(String str);\\nstatic int countMatches(String str,String sub);\\nstatic boolean isAlpha(String str);\\nstatic boolean isAlphaSpace(String str);\\nstatic boolean isAlphanumeric(String str);\\nstatic boolean isAlphanumericSpace(String str);\\nstatic boolean isAsciiPrintable(String str);\\nstatic boolean isNumeric(String str);\\nstatic boolean isNumericSpace(String str);\\nstatic boolean isWhitespace(String str);\\nstatic boolean isAllLowerCase(String str);\\nstatic boolean isAllUpperCase(String str);\\nstatic String defaultString(String str);\\nstatic String defaultString(String str,String defaultStr);\\nstatic String defaultIfBlank(String str,String defaultStr);\\nstatic String defaultIfEmpty(String str,String defaultStr);\\nstatic String reverse(String str);\\nstatic String reverseDelimited(String str,char separatorChar);\\nstatic String abbreviate(String str,int maxWidth);\\nstatic String abbreviate(String str,int offset,int maxWidth);\\nstatic String abbreviateMiddle(String str,String middle,int length);\\nstatic String difference(String str1,String str2);\\nstatic int indexOfDifference(String str1,String str2);\\nstatic int indexOfDifference(String[] strs);\\nstatic String getCommonPrefix(String[] strs);\\nstatic int getLevenshteinDistance(String s,String t);\\nstatic boolean startsWith(String str,String prefix);\\nstatic boolean startsWithIgnoreCase(String str,String prefix);\\nstatic boolean startsWithAny(String string,String[] searchStrings);\\nstatic boolean endsWith(String str,String suffix);\\nstatic boolean endsWithIgnoreCase(String str,String suffix);\\nstatic String normalizeSpace(String str);\\nstatic boolean endsWithAny(String string,String[] searchStrings);\\nstatic String firstCharToUpperCase(String value);\\nstatic String firstCharToLowerCase(String value);\\nstatic boolean equalsBlankIgnoreCase(String str1,String str2);\\nstatic String quote(String input);\\nstatic void quote(Appendable buffer,String input);\\nstatic String toString(Object object);\\n }\\n\" }", "class_name": "StringUdfSource", "code": "public static String sub(String str,int start,int end){\n return StringUtils.substring(str,start,end);\n}\n", "docstring": "/** \n * Gets a substring from the specified String avoiding exceptions. \n */\n", "end_lineno": "234", "file_content": "/*\n * Copyright 2008-2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.dataql.fx.basic;\nimport net.hasor.core.Singleton;\nimport net.hasor.dataql.UdfSourceAssembly;\nimport net.hasor.utils.StringUtils;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * 字符串函数 import 'net.hasor.dataql.fx.basic.StringUdfSource' as string;\n * @version : 2019-12-12\n */\n@Singleton\npublic class StringUdfSource implements UdfSourceAssembly {\n // startsWith/endsWith\n //-----------------------------------------------------------------------\n\n /** Check if a String starts with a specified prefix. */\n public static boolean startsWith(String str, String prefix) {\n return _startsWith(str, prefix, false);\n }\n\n /** Case insensitive check if a String starts with a specified prefix. */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n return _startsWith(str, prefix, true);\n }\n\n /** Case insensitive check if a String ends with a specified suffix. */\n public static boolean endsWith(String str, String suffix) {\n return _endsWith(str, suffix, false);\n }\n\n /** Case insensitive check if a String ends with a specified suffix. */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n return _endsWith(str, suffix, true);\n }\n\n private static boolean _startsWith(String str, String prefix, boolean ignoreCase) {\n if (str == null || prefix == null) {\n return str == null && prefix == null;\n }\n if (prefix.length() > str.length()) {\n return false;\n }\n return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());\n }\n\n private static boolean _endsWith(String str, String suffix, boolean ignoreCase) {\n if (str == null || suffix == null) {\n return str == null && suffix == null;\n }\n if (suffix.length() > str.length()) {\n return false;\n }\n int strOffset = str.length() - suffix.length();\n return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());\n }\n\n // Hump\n //-----------------------------------------------------------------------\n private static final Pattern linePattern = Pattern.compile(\"_(\\\\w)\");\n private static final Pattern humpPattern = Pattern.compile(\"[A-Z]\");\n\n /** 下划线转驼峰 */\n public static String lineToHump(String str) {\n if (str == null) {\n return null;\n }\n str = str.toLowerCase();\n Matcher matcher = linePattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, matcher.group(1).toUpperCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n\n /** 驼峰转下划线 */\n public static String humpToLine(String str) {\n if (str == null) {\n return null;\n }\n Matcher matcher = humpPattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, \"_\" + matcher.group(0).toLowerCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n // UpperCase/LowerCase\n //-----------------------------------------------------------------------\n\n /** 转换首字母大写 */\n public static String firstCharToUpperCase(String value) {\n return StringUtils.firstCharToUpperCase(value);\n }\n\n /** 转换首字母小写 */\n public static String firstCharToLowerCase(String value) {\n return StringUtils.firstCharToLowerCase(value);\n }\n\n /** 转换大写 */\n public static String toUpperCase(String value) {\n return StringUtils.upperCase(value);\n }\n\n /** 转换小写 */\n public static String toLowerCase(String value) {\n return StringUtils.lowerCase(value);\n }\n // IndexOf/lastIndexOf\n //-----------------------------------------------------------------------\n\n /** Finds the first index within a String, handling null. This method uses {@link String#indexOf(String)}. */\n public static int indexOf(String str, String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr);\n }\n\n /** Finds the first index within a String from a start position, handling null. This method uses {@link String#indexOf(String, int)}. */\n public static int indexOfWithStart(String str, String searchStr, int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr, startPos);\n }\n\n /** Case in-sensitive find of the first index within a String. */\n public static int indexOfIgnoreCase(String str, String searchStr) {\n return StringUtils.indexOfIgnoreCase(str, searchStr, 0);\n }\n\n /** Case in-sensitive find of the first index within a String from the specified position. */\n public static int indexOfIgnoreCaseWithStart(String str, String searchStr, int startPos) {\n return StringUtils.indexOfIgnoreCase(str, searchStr, startPos);\n }\n\n /** Finds the last index within a String, handling null. This method uses {@link String#lastIndexOf(String)}. */\n public static int lastIndexOf(String str, String searchStr) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr);\n }\n\n /** Finds the last index within a String from a start position, handling null. This method uses {@link String#lastIndexOf(String, int)}. */\n public static int lastIndexOfWithStart(String str, String searchChar, int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar, startPos);\n }\n\n /** Case in-sensitive find of the last index within a String from the specified position. */\n public static int lastIndexOfIgnoreCase(String str, String searchStr) {\n return StringUtils.lastIndexOfIgnoreCase(str, searchStr, 0);\n }\n\n /** Case in-sensitive find of the last index within a String from the specified position. */\n public static int lastIndexOfIgnoreCaseWithStart(String str, String searchStr, int startPos) {\n return StringUtils.lastIndexOfIgnoreCase(str, searchStr, startPos);\n }\n // Contains\n //-----------------------------------------------------------------------\n\n /** Checks if String contains a search String, handling null. This method uses {@link String#indexOf(String)}. */\n public static boolean contains(String str, String searchStr) {\n return StringUtils.contains(str, searchStr);\n }\n\n /** Checks if String contains a search String irrespective of case, handling null. Case-insensitivity is defined as by {@link String#equalsIgnoreCase(String)}. */\n public static boolean containsIgnoreCase(String str, String searchStr) {\n return StringUtils.containsIgnoreCase(str, searchStr);\n }\n\n /** Checks if the String contains any character in the given set of string. */\n public static boolean containsAny(String str, List searchStrArray) {\n if (StringUtils.isEmpty(str) || searchStrArray == null || searchStrArray.isEmpty()) {\n return false;\n }\n for (String item : searchStrArray) {\n if (contains(str, item)) {\n return true;\n }\n }\n return false;\n }\n\n /** Case in-sensitive Checks if the String contains any character in the given set of string. */\n public static boolean containsAnyIgnoreCase(String str, List searchStrArray) {\n if (StringUtils.isEmpty(str) || searchStrArray == null || searchStrArray.isEmpty()) {\n return false;\n }\n for (String item : searchStrArray) {\n if (containsIgnoreCase(str, item)) {\n return true;\n }\n }\n return false;\n }\n // trim/Sub/left/right\n //-----------------------------------------------------------------------\n\n /** 截断两边空格,如果为空返回为空。 */\n public static String trim(final String str) {\n return str == null ? null : str.trim();\n }\n\n /** Gets a substring from the specified String avoiding exceptions. */\n public static String sub(String str, int start, int end) {\n return StringUtils.substring(str, start, end);\n }\n\n /** Gets the leftmost len characters of a String. */\n public static String left(String str, int len) {\n return StringUtils.left(str, len);\n }\n\n /** Gets the rightmost len characters of a String. */\n public static String right(String str, int len) {\n return StringUtils.right(str, len);\n }\n // align/pading\n //-----------------------------------------------------------------------\n\n /** 字符串在指定长度下进行右对齐,空出来的字符使用padChar补齐。如果传入多个字符将会取第一个字符。 */\n public static String alignRight(String str, String padChar, int len) {\n if (str != null) {\n if (str.length() > len) {\n return str;\n }\n }\n char pad = padChar.length() == 0 ? ' ' : padChar.charAt(0);\n return StringUtils.rightPad(str, len, pad);\n }\n\n /** 字符串在指定长度下进行左对齐,空出来的字符使用padChar补齐。如果传入多个字符将会取第一个字符。 */\n public static String alignLeft(String str, String padChar, int len) {\n if (str != null) {\n if (str.length() > len) {\n return str;\n }\n }\n char pad = padChar.length() == 0 ? ' ' : padChar.charAt(0);\n return StringUtils.leftPad(str, len, pad);\n }\n\n /** 字符串在指定长度下进行剧中对齐,空出来的字符使用padChar补齐。如果传入多个字符将会取第一个字符。 */\n public static String alignCenter(String str, String padChar, int len) {\n if (str != null) {\n if (str.length() > len) {\n return str;\n }\n }\n char pad = padChar.length() == 0 ? ' ' : padChar.charAt(0);\n return StringUtils.center(str, len, pad);\n }\n // compare\n //-----------------------------------------------------------------------\n\n /**\n * Compares two strings lexicographically.\n * The comparison is based on the Unicode value of each character in\n * the strings. The character sequence represented by this\n * {@code String} object is compared lexicographically to the\n * character sequence represented by the argument string. The result is\n * a negative integer if this {@code String} object\n * lexicographically precedes the argument string. The result is a\n * positive integer if this {@code String} object lexicographically\n * follows the argument string. The result is zero if the strings\n * are equal; {@code compareTo} returns {@code 0} exactly when\n * the {@link #equals(Object)} method would return {@code true}.\n *

\n * This is the definition of lexicographic ordering. If two strings are\n * different, then either they have different characters at some index\n * that is a valid index for both strings, or their lengths are different,\n * or both. If they have different characters at one or more index\n * positions, let k be the smallest such index; then the string\n * whose character at position k has the smaller value, as\n * determined by using the < operator, lexicographically precedes the\n * other string. In this case, {@code compareTo} returns the\n * difference of the two character values at position {@code k} in\n * the two string -- that is, the value:\n *

\n     * this.charAt(k)-anotherString.charAt(k)\n     * 
\n * If there is no index position at which they differ, then the shorter\n * string lexicographically precedes the longer string. In this case,\n * {@code compareTo} returns the difference of the lengths of the\n * strings -- that is, the value:\n *
\n     * this.length()-anotherString.length()\n     * 
\n *\n * @param str1 the {@code String} to be compared.\n * @param str2 the {@code String} to be compared.\n * @return the value {@code 0} if the argument string is equal to\n * this string; a value less than {@code 0} if this string\n * is lexicographically less than the string argument; and a\n * value greater than {@code 0} if this string is\n * lexicographically greater than the string argument.\n */\n public static int compareString(String str1, String str2) {\n str1 = str1 == null ? \"\" : str1;\n str2 = str2 == null ? \"\" : str2;\n return str1.compareTo(str2);\n }\n\n /**\n * Compares two strings lexicographically, ignoring case\n * differences. This method returns an integer whose sign is that of\n * calling {@code compareTo} with normalized versions of the strings\n * where case differences have been eliminated by calling\n * {@code Character.toLowerCase(Character.toUpperCase(character))} on\n * each character.\n *

\n * Note that this method does not take locale into account,\n * and will result in an unsatisfactory ordering for certain locales.\n * The java.text package provides collators to allow\n * locale-sensitive ordering.\n *\n * @param str1 the {@code String} to be compared.\n * @param str2 the {@code String} to be compared.\n * @return a negative integer, zero, or a positive integer as the\n * specified String is greater than, equal to, or less\n * than this String, ignoring case considerations.\n * @see java.text.Collator#compare(String, String)\n * @since 1.2\n */\n public static int compareStringIgnoreCase(String str1, String str2) {\n str1 = str1 == null ? \"\" : str1;\n str2 = str2 == null ? \"\" : str2;\n return str1.compareToIgnoreCase(str2);\n }\n // other\n //-----------------------------------------------------------------------\n\n /**\n *

Splits the provided text into an array, separators specified.\n * This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *
\n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"abc def\", null) = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc def\", \" \")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\", \" \") = [\"abc\", \"def\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\") = [\"ab\", \"cd\", \"ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters, null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n */\n public static List split(String str, String separatorChars) {\n return Arrays.asList(StringUtils.split(str, separatorChars));\n }\n\n /** Joins the elements of the provided array into a single String containing the provided list of elements. */\n public static String join(List array, String separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array.toArray(), separator);\n }\n\n /** Checks if a String is empty (\"\") or null.*/\n public static boolean isEmpty(String str) {\n return str == null || str.length() == 0;\n }\n\n /** 忽略大小写比较相等 */\n public static boolean equalsIgnoreCase(String str1, String str2) {\n return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);\n }\n}\n", "file_name": "StringUdfSource.java", "human_label": "Get a substring from the specified String avoiding exceptions. ", "level": "project_runnable", "lineno": "231", "name": "sub", "oracle_context": "{ \"apis\" : \"[substring]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.dataql.fx.basic", "project": "hasor-master" }, { "_id": "6367671a1a6d9265ec017c15", "all_context": "{ \"class_level\" : \"byte[] data;\\nint length;\\nByteVector();\\nByteVector(int initialCapacity);\\nByteVector(byte[] data);\\nput11(int byteValue1,int byteValue2);\\nputShort(int shortValue);\\nput12(int byteValue,int shortValue);\\nput112(int byteValue1,int byteValue2,int shortValue);\\nputInt(int intValue);\\nput122(int byteValue,int shortValue1,int shortValue2);\\nputLong(long longValue);\\nputUTF8(String stringValue);\\nencodeUtf8(String stringValue,int offset,int maxByteLength);\\nputByteArray(byte[] byteArrayValue,int byteOffset,int byteLength);\\nenlarge(int size);\\nputByte(int byteValue);\\n\", \"repo_level\" : \"\" }", "class_name": "ByteVector", "code": "public ByteVector putByteArray(final byte[] byteArrayValue,final int byteOffset,final int byteLength){\n if (length + byteLength > data.length) {\n enlarge(byteLength);\n }\n if (byteArrayValue != null) {\n System.arraycopy(byteArrayValue,byteOffset,data,length,byteLength);\n }\n length+=byteLength;\n return this;\n}\n", "docstring": "/** \n * Puts an array of bytes into this byte vector. The byte vector is automatically enlarged if necessary.\n * @param byteArrayValue an array of bytes. May be {@literal null} to put {@code byteLength} nullbytes into this byte vector.\n * @param byteOffset index of the first byte of byteArrayValue that must be copied.\n * @param byteLength number of bytes of byteArrayValue that must be copied.\n * @return this byte vector.\n */\n", "end_lineno": "343", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage net.hasor.utils.asm;\n/**\n * A dynamically extensible vector of bytes. This class is roughly equivalent to a DataOutputStream\n * on top of a ByteArrayOutputStream, but is more efficient.\n *\n * @author Eric Bruneton\n */\npublic class ByteVector {\n /** The content of this vector. Only the first {@link #length} bytes contain real data. */\n byte[] data;\n /** The actual number of bytes in this vector. */\n int length;\n\n /** Constructs a new {@link ByteVector} with a default initial capacity. */\n public ByteVector() {\n data = new byte[64];\n }\n\n /**\n * Constructs a new {@link ByteVector} with the given initial capacity.\n *\n * @param initialCapacity the initial capacity of the byte vector to be constructed.\n */\n public ByteVector(final int initialCapacity) {\n data = new byte[initialCapacity];\n }\n\n /**\n * Constructs a new {@link ByteVector} from the given initial data.\n *\n * @param data the initial data of the new byte vector.\n */\n ByteVector(final byte[] data) {\n this.data = data;\n this.length = data.length;\n }\n\n /**\n * Puts a byte into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param byteValue a byte.\n * @return this byte vector.\n */\n public ByteVector putByte(final int byteValue) {\n int currentLength = length;\n if (currentLength + 1 > data.length) {\n enlarge(1);\n }\n data[currentLength++] = (byte) byteValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts two bytes into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param byteValue1 a byte.\n * @param byteValue2 another byte.\n * @return this byte vector.\n */\n final ByteVector put11(final int byteValue1, final int byteValue2) {\n int currentLength = length;\n if (currentLength + 2 > data.length) {\n enlarge(2);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue1;\n currentData[currentLength++] = (byte) byteValue2;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a short into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param shortValue a short.\n * @return this byte vector.\n */\n public ByteVector putShort(final int shortValue) {\n int currentLength = length;\n if (currentLength + 2 > data.length) {\n enlarge(2);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a byte and a short into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteValue a byte.\n * @param shortValue a short.\n * @return this byte vector.\n */\n final ByteVector put12(final int byteValue, final int shortValue) {\n int currentLength = length;\n if (currentLength + 3 > data.length) {\n enlarge(3);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts two bytes and a short into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteValue1 a byte.\n * @param byteValue2 another byte.\n * @param shortValue a short.\n * @return this byte vector.\n */\n final ByteVector put112(final int byteValue1, final int byteValue2, final int shortValue) {\n int currentLength = length;\n if (currentLength + 4 > data.length) {\n enlarge(4);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue1;\n currentData[currentLength++] = (byte) byteValue2;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an int into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param intValue an int.\n * @return this byte vector.\n */\n public ByteVector putInt(final int intValue) {\n int currentLength = length;\n if (currentLength + 4 > data.length) {\n enlarge(4);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts one byte and two shorts into this byte vector. The byte vector is automatically enlarged\n * if necessary.\n *\n * @param byteValue a byte.\n * @param shortValue1 a short.\n * @param shortValue2 another short.\n * @return this byte vector.\n */\n final ByteVector put122(final int byteValue, final int shortValue1, final int shortValue2) {\n int currentLength = length;\n if (currentLength + 5 > data.length) {\n enlarge(5);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue;\n currentData[currentLength++] = (byte) (shortValue1 >>> 8);\n currentData[currentLength++] = (byte) shortValue1;\n currentData[currentLength++] = (byte) (shortValue2 >>> 8);\n currentData[currentLength++] = (byte) shortValue2;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a long into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param longValue a long.\n * @return this byte vector.\n */\n public ByteVector putLong(final long longValue) {\n int currentLength = length;\n if (currentLength + 8 > data.length) {\n enlarge(8);\n }\n byte[] currentData = data;\n int intValue = (int) (longValue >>> 32);\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n intValue = (int) longValue;\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param stringValue a String whose UTF8 encoded length must be less than 65536.\n * @return this byte vector.\n */\n // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility).\n public ByteVector putUTF8(final String stringValue) {\n int charLength = stringValue.length();\n if (charLength > 65535) {\n throw new IllegalArgumentException(\"UTF8 string too large\");\n }\n int currentLength = length;\n if (currentLength + 2 + charLength > data.length) {\n enlarge(2 + charLength);\n }\n byte[] currentData = data;\n // Optimistic algorithm: instead of computing the byte length and then serializing the string\n // (which requires two loops), we assume the byte length is equal to char length (which is the\n // most frequent case), and we start serializing the string right away. During the\n // serialization, if we find that this assumption is wrong, we continue with the general method.\n currentData[currentLength++] = (byte) (charLength >>> 8);\n currentData[currentLength++] = (byte) charLength;\n for (int i = 0; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= '\\u0001' && charValue <= '\\u007F') {\n currentData[currentLength++] = (byte) charValue;\n } else {\n length = currentLength;\n return encodeUtf8(stringValue, i, 65535);\n }\n }\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if\n * necessary. The string length is encoded in two bytes before the encoded characters, if there is\n * space for that (i.e. if this.length - offset - 2 >= 0).\n *\n * @param stringValue the String to encode.\n * @param offset the index of the first character to encode. The previous characters are supposed\n * to have already been encoded, using only one byte per character.\n * @param maxByteLength the maximum byte length of the encoded string, including the already\n * encoded characters.\n * @return this byte vector.\n */\n final ByteVector encodeUtf8(final String stringValue, final int offset, final int maxByteLength) {\n int charLength = stringValue.length();\n int byteLength = offset;\n for (int i = offset; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= 0x0001 && charValue <= 0x007F) {\n byteLength++;\n } else if (charValue <= 0x07FF) {\n byteLength += 2;\n } else {\n byteLength += 3;\n }\n }\n if (byteLength > maxByteLength) {\n throw new IllegalArgumentException(\"UTF8 string too large\");\n }\n // Compute where 'byteLength' must be stored in 'data', and store it at this location.\n int byteLengthOffset = length - offset - 2;\n if (byteLengthOffset >= 0) {\n data[byteLengthOffset] = (byte) (byteLength >>> 8);\n data[byteLengthOffset + 1] = (byte) byteLength;\n }\n if (length + byteLength - offset > data.length) {\n enlarge(byteLength - offset);\n }\n int currentLength = length;\n for (int i = offset; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= 0x0001 && charValue <= 0x007F) {\n data[currentLength++] = (byte) charValue;\n } else if (charValue <= 0x07FF) {\n data[currentLength++] = (byte) (0xC0 | charValue >> 6 & 0x1F);\n data[currentLength++] = (byte) (0x80 | charValue & 0x3F);\n } else {\n data[currentLength++] = (byte) (0xE0 | charValue >> 12 & 0xF);\n data[currentLength++] = (byte) (0x80 | charValue >> 6 & 0x3F);\n data[currentLength++] = (byte) (0x80 | charValue & 0x3F);\n }\n }\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an array of bytes into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteArrayValue an array of bytes. May be {@literal null} to put {@code byteLength} null\n * bytes into this byte vector.\n * @param byteOffset index of the first byte of byteArrayValue that must be copied.\n * @param byteLength number of bytes of byteArrayValue that must be copied.\n * @return this byte vector.\n */\n public ByteVector putByteArray(final byte[] byteArrayValue, final int byteOffset, final int byteLength) {\n if (length + byteLength > data.length) {\n enlarge(byteLength);\n }\n if (byteArrayValue != null) {\n System.arraycopy(byteArrayValue, byteOffset, data, length, byteLength);\n }\n length += byteLength;\n return this;\n }\n\n /**\n * Enlarges this byte vector so that it can receive 'size' more bytes.\n *\n * @param size number of additional bytes that this byte vector should be able to receive.\n */\n private void enlarge(final int size) {\n int doubleCapacity = 2 * data.length;\n int minimalCapacity = length + size;\n byte[] newData = new byte[doubleCapacity > minimalCapacity ? doubleCapacity : minimalCapacity];\n System.arraycopy(data, 0, newData, 0, length);\n data = newData;\n }\n}\n", "file_name": "ByteVector.java", "human_label": "Put an array of bytes into this byte vector, enlarge the byte vector automatically if necessary.", "level": "class_runnable", "lineno": "324", "name": "putByteArray", "oracle_context": "{ \"apis\" : \"[enlarge, arraycopy, ByteVector]\", \"classes\" : \"[data]\", \"vars\" : \"[length, data]\" }", "package": "net.hasor.utils.asm", "project": "hasor-master" }, { "_id": "636766821a6d9265ec0174d2", "all_context": "{ \"class_level\" : \"import org.atmosphere.util.FakeHttpSession;\\nimport org.atmosphere.util.QueryStringDecoder;\\nimport org.atmosphere.util.ReaderInputStream;\\nimport org.slf4j.Logger;\\nimport org.slf4j.LoggerFactory;\\nimport javax.servlet.AsyncContext;\\nimport javax.servlet.AsyncListener;\\nimport javax.servlet.DispatcherType;\\nimport javax.servlet.RequestDispatcher;\\nimport javax.servlet.ServletContext;\\nimport javax.servlet.ServletException;\\nimport javax.servlet.ServletInputStream;\\nimport javax.servlet.ServletRequest;\\nimport javax.servlet.ServletResponse;\\nimport javax.servlet.http.Cookie;\\nimport javax.servlet.http.HttpServletRequest;\\nimport javax.servlet.http.HttpServletRequestWrapper;\\nimport javax.servlet.http.HttpServletResponse;\\nimport javax.servlet.http.HttpSession;\\nimport javax.servlet.http.Part;\\nimport java.io.BufferedReader;\\nimport java.io.ByteArrayInputStream;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport java.io.InputStreamReader;\\nimport java.io.Reader;\\nimport java.io.StringReader;\\nimport java.io.UnsupportedEncodingException;\\nimport java.net.InetSocketAddress;\\nimport java.nio.charset.StandardCharsets;\\nimport java.security.Principal;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Collections;\\nimport java.util.Enumeration;\\nimport java.util.HashMap;\\nimport java.util.HashSet;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Map;\\nimport java.util.Objects;\\nimport java.util.Set;\\nimport java.util.concurrent.Callable;\\nimport java.util.concurrent.atomic.AtomicBoolean;\\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE;\\nLogger logger;\\nServletInputStream bis;\\nBufferedReader br;\\nBuilder b;\\nAtomicBoolean destroyed;\\nboolean queryComputed;\\nboolean cookieComputed;\\nBufferedReader voidReader;\\nServletInputStream voidStream;\\nAtomicBoolean streamSet;\\nAtomicBoolean readerSet;\\nString uuid;\\nboolean noopsAsyncContextStarted;\\nByteArrayInputStream bis;\\nBody NULL_BODY;\\nHttpServletRequest request;\\nString pathInfo;\\nString encoding;\\nString methodType;\\nString contentType;\\nboolean noContentType;\\nLong contentLength;\\nMap headers;\\nMap queryStrings;\\nString servletPath;\\nString requestURI;\\nString requestURL;\\nInputStream inputStream;\\nReader reader;\\nString remoteAddr;\\nString remoteHost;\\nint remotePort;\\nString localAddr;\\nString localName;\\nint localPort;\\nboolean dispatchRequestAsynchronously;\\nboolean destroyable;\\nSet cookies;\\nSet locales;\\nPrincipal principal;\\nString authType;\\nString contextPath;\\nString serverName;\\nint serverPort;\\nHttpSession webSocketFakeSession;\\nString queryString;\\nboolean isSecure;\\nLazyComputation lazyRemote;\\nLazyComputation lazyLocal;\\nBody body;\\nLocalAttributes localAttributes;\\nString data;\\nbyte[] dataBytes;\\nint offset;\\nint length;\\nboolean isEmpty;\\nInputStream innerStream;\\nboolean throwExceptionOnCloned;\\nHttpSession fake;\\nEnumeration EMPTY_ENUM_STRING;\\nEnumeration EMPTY_ENUM_LOCALE;\\nList EMPTY_ENUM_PART;\\nMap EMPTY_MAP_STRING;\\nString[] EMPTY_ARRAY;\\nStringBuffer EMPTY_STRING_BUFFER;\\nCookie[] EMPTY_COOKIE;\\nCallable callable;\\nInetSocketAddress address;\\nAsyncContext context;\\nCompletionAware callback;\\nServletRequest request;\\nServletResponse response;\\nlong timeout;\\nAtmosphereRequestImpl(Builder b);\\ngetVoidReader();\\nconfigureStream();\\nconfigureReader();\\ndestroyed();\\ndestroyable(boolean destroyable);\\ngetPathInfo();\\ngetPathTranslated();\\ngetQueryString();\\ntoQs();\\ngetRemoteUser();\\ngetRequestedSessionId();\\ngetMethod();\\ngetPart(String name);\\ngetParts();\\ngetContentType();\\ngetDispatcherType();\\ngetServletPath();\\ngetRequestURI();\\ngetRequestURL();\\ngetHeaders(String name);\\ngetIntHeader(String name);\\ngetHeaderNames();\\nauthenticate(HttpServletResponse response);\\ngetAuthType();\\ngetContextPath();\\ngetCookies();\\ngetDateHeader(String name);\\ngetHeader(String s);\\nwrappedRequest();\\ngetHeader(String s,boolean checkCase);\\ngetParameter(String s);\\ngetParameterMap();\\ngetParameterNames();\\ngetParameterValues(String s);\\ngetProtocol();\\ngetInputStream();\\ngetReader();\\ngetRealPath(String path);\\nheaders(Map headers);\\nheader(String name,String value);\\nqueryString(String qs);\\nheadersMap();\\nqueryStringsMap();\\nmethod(String m);\\ncontentType(String m);\\nbody(String body);\\nbody(byte[] bytes);\\nbody(InputStream body);\\nbody(Reader body);\\nbody();\\nservletPath(String servletPath);\\ncontextPath(String contextPath);\\nrequestURI(String requestURI);\\nByteInputStream(byte[] data,int offset,int length);\\nread();\\nsetAttribute(String s,Object o);\\nsetCharacterEncoding(String env);\\nstartAsync();\\nstartAsync(ServletRequest request,ServletResponse response);\\ngetAsyncContext();\\ngetAttribute(String s);\\nremoveAttribute(String name);\\nattributes();\\ngetSession();\\ngetSession(boolean create);\\ngetUserPrincipal();\\nisRequestedSessionIdFromCookie();\\nisRequestedSessionIdFromUrl();\\nisRequestedSessionIdFromURL();\\nisRequestedSessionIdValid();\\nisUserInRole(String role);\\nlogin(String username,String password);\\nlogout();\\ngetRemoteAddr();\\ngetRemoteHost();\\ngetRemotePort();\\ngetRequestDispatcher(String path);\\ngetScheme();\\ngetServerName();\\ngetServerPort();\\ngetServletContext();\\nisAsyncStarted();\\nisAsyncSupported();\\nisSecure();\\ngetLocalName();\\ngetLocalPort();\\ngetLocalAddr();\\nisNotNoOps();\\ngetLocale();\\nresource();\\ngetLocales();\\ndispatchRequestAsynchronously();\\nisDestroyable();\\npathInfo(String pathInfo);\\ngetAttributeNames();\\nattributeWithoutException(HttpServletRequest request,String attribute);\\nlocalAttributes();\\ngetCharacterEncoding();\\ngetContentLength();\\nuuid();\\ndestroy();\\ndestroy(boolean force);\\nsetRequest(ServletRequest request);\\nBuilder();\\ncookies(Set cookies);\\ndispatchRequestAsynchronously(boolean dispatchRequestAsynchronously);\\nremoteAddr(String remoteAddr);\\nremoteHost(String remoteHost);\\nremotePort(int remotePort);\\nlocalAddr(String localAddr);\\nlocalName(String localName);\\nlocalPort(int localPort);\\nremoteInetSocketAddress(Callable remoteAddr);\\nlocalInetSocketAddress(Callable localAddr);\\nattributes(Map attributes);\\nrequest(HttpServletRequest request);\\nrequestURL(String requestURL);\\nqueryString(String queryString);\\nbody(byte[] dataBytes);\\nbody(byte[] dataBytes,int offset,int length);\\nencoding(String encoding);\\nmethod(String methodType);\\ncontentType(String contentType);\\ncontentLength(Long contentLength);\\nbody(String data);\\ninputStream(InputStream inputStream);\\nreader(Reader reader);\\nbuild();\\nqueryStrings(Map queryStrings);\\nserverName(String serverName);\\nserverPort(int serverPort);\\nsession(HttpSession session);\\nprincipal(Principal principal);\\nauthType(String authType);\\nisSSecure(boolean isSecure);\\nlocale(Locale locale);\\nuserPrincipal(Principal userPrincipal);\\nBody(String data,byte[] dataBytes,int offset,int length);\\nhasBytes();\\nasString();\\nasBytes();\\nbyteOffset();\\nbyteLength();\\nisEmpty();\\nIS(InputStream innerStream);\\nread(byte[] bytes);\\nread(byte[] bytes,int i,int i1);\\nskip(long l);\\navailable();\\nclose();\\nmark(int i);\\nreset();\\nmarkSupported();\\nnewInstance();\\nwrap(HttpServletRequest request);\\ncloneRequest(HttpServletRequest request,boolean loadInMemory,boolean copySession,boolean isDestroyable,boolean createSession);\\nNoOpsRequest();\\nNoOpsRequest(boolean throwExceptionOnCloned);\\ngetHeader(String name);\\ninvalidate();\\ngetAttribute(String name);\\ngetParameter(String name);\\ngetParameterValues(String name);\\nsetAttribute(String name,Object o);\\nLazyComputation(Callable callable);\\naddress();\\ngetPort();\\ngetHostAddress();\\ngetHostName();\\nisCompletionAware();\\nCompletionAwareAsyncContext(AsyncContext context,CompletionAware callback);\\naddListener(AsyncListener listener);\\naddListener(AsyncListener listener,ServletRequest request,ServletResponse response);\\ncomplete();\\ncreateListener(Class clazz);\\ndispatch();\\ndispatch(ServletContext servletContext,String path);\\ndispatch(String path);\\ngetRequest();\\ngetResponse();\\ngetTimeout();\\nhasOriginalRequestAndResponse();\\nsetTimeout(long timeoutMilliseconds);\\nstart(Runnable run);\\nNoOpsAsyncContext(ServletRequest request,ServletResponse response);\\nsetTimeout(long timeout);\\nload(HttpServletRequest request,Builder b);\\ntoString();\\nrequestURL();\\nhasString();\\n\", \"repo_level\" : \"public interface FakeHttpSession {public void destroy();\\npublic long getCreationTime();\\npublic String getId();\\npublic long getLastAccessedTime();\\npublic ServletContext getServletContext();\\npublic void setMaxInactiveInterval(int interval);\\npublic int getMaxInactiveInterval();\\npublic HttpSessionContext getSessionContext();\\npublic Object getAttribute(String name);\\npublic Object getValue(String name);\\npublic Enumeration getAttributeNames();\\npublic String[] getValueNames();\\npublic void setAttribute(String name,Object value);\\npublic void putValue(String name,Object value);\\npublic void removeAttribute(String name);\\npublic void removeValue(String name);\\npublic FakeHttpSession copyAttributes(HttpSession httpSession);\\npublic void invalidate();\\npublic boolean isNew();\\n }\\npublic interface QueryStringDecoder {public String getPath();\\npublic Map> getParameters();\\nstatic String decodeComponent(String s);\\nstatic String decodeComponent(String s,Charset charset);\\n }\\npublic interface ReaderInputStream {public int read(byte[] b,int off,int len);\\npublic int read(byte[] b);\\npublic int read();\\npublic void close();\\n }\\n\" }", "class_name": "AtmosphereRequestImpl", "code": "public static AtmosphereRequest wrap(HttpServletRequest request){\n if (AtmosphereRequestImpl.class.isAssignableFrom(request.getClass())) {\n return (AtmosphereRequestImpl)request;\n }\n Builder b=new Builder();\n Enumeration e=request.getAttributeNames();\n String s;\n while (e.hasMoreElements()) {\n s=e.nextElement();\n b.localAttributes.put(s,attributeWithoutException(request,s));\n }\n return b.request(request).build();\n}\n", "docstring": "/** \n * Wrap an {@link HttpServletRequest}.\n * @param request {@link HttpServletRequest}\n * @return an {@link AtmosphereRequest}\n */\n", "end_lineno": "1423", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\npackage org.atmosphere.cpr;\n\nimport org.atmosphere.util.FakeHttpSession;\nimport org.atmosphere.util.QueryStringDecoder;\nimport org.atmosphere.util.ReaderInputStream;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.servlet.AsyncContext;\nimport javax.servlet.AsyncListener;\nimport javax.servlet.DispatcherType;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletInputStream;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.ServletResponse;\nimport javax.servlet.http.Cookie;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletRequestWrapper;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\nimport javax.servlet.http.Part;\n\nimport java.io.BufferedReader;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.Reader;\nimport java.io.StringReader;\nimport java.io.UnsupportedEncodingException;\nimport java.net.InetSocketAddress;\nimport java.nio.charset.StandardCharsets;\nimport java.security.Principal;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE;\n\n/**\n * An Atmosphere request representation. An {@link AtmosphereRequest} is a two-way communication channel between the\n * client and the server. If the {@link AtmosphereRequestImpl#isDestroyable()} is set to false, or if its\n * associated {@link AtmosphereResource} has been suspended, this object can be re-used at any moment between requests.\n * You can use its associated {@link AtmosphereResponse} to write bytes at any moment, making this object bi-directional.\n *
\n *\n * @author Jeanfrancois Arcand\n */\npublic class AtmosphereRequestImpl extends HttpServletRequestWrapper implements AtmosphereRequest {\n\n private final static Logger logger = LoggerFactory.getLogger(AtmosphereRequestImpl.class);\n private ServletInputStream bis;\n private BufferedReader br;\n private final Builder b;\n private final AtomicBoolean destroyed = new AtomicBoolean(false);\n private boolean queryComputed;\n private boolean cookieComputed;\n private volatile BufferedReader voidReader;\n private final ServletInputStream voidStream = new IS(new ByteArrayInputStream(new byte[0]));\n private final AtomicBoolean streamSet = new AtomicBoolean();\n private final AtomicBoolean readerSet = new AtomicBoolean();\n private String uuid;\n private boolean noopsAsyncContextStarted;\n\n private AtmosphereRequestImpl(Builder b) {\n super(b.request == null ? new NoOpsRequest() : b.request);\n if (b.request == null) b.request(new NoOpsRequest());\n\n this.b = b;\n this.uuid = resource() != null ? resource().uuid() : \"0\";\n }\n\n private BufferedReader getVoidReader() {\n if (voidReader == null) {\n voidReader = new BufferedReader(new StringReader(\"\"), 5);\n }\n return voidReader;\n }\n\n private void configureStream() {\n if (bis == null && !streamSet.getAndSet(true)) {\n if (b.inputStream != null) {\n bis = new IS(b.inputStream);\n } else if (b.reader == null) {\n if (b.body.dataBytes != null) {\n bis = new ByteInputStream(b.body.dataBytes, b.body.offset, b.body.length);\n } else if (b.body.data != null) {\n byte[] bytes = b.body.data.getBytes(StandardCharsets.UTF_8);\n bis = new ByteInputStream(bytes, 0, bytes.length);\n }\n } else {\n bis = new IS(new ReaderInputStream(b.reader));\n }\n }\n }\n\n private void configureReader() {\n if (br == null && !readerSet.getAndSet(false)) {\n if (b.reader != null) {\n br = new BufferedReader(b.reader);\n } else if (b.inputStream == null) {\n try {\n if (b.body.dataBytes != null) {\n br = new BufferedReader(new StringReader(new String(b.body.dataBytes, b.body.offset, b.body.length, b.encoding)));\n } else if (b.body.data != null) {\n br = new BufferedReader(new StringReader(b.body.data));\n }\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n } else {\n br = new BufferedReader(new InputStreamReader(b.inputStream));\n }\n }\n }\n\n @Override\n public boolean destroyed() {\n return destroyed.get();\n }\n\n @Override\n public AtmosphereRequest destroyable(boolean destroyable) {\n b.destroyable = destroyable;\n return this;\n }\n\n @Override\n public String getPathInfo() {\n return !Objects.equals(b.pathInfo, \"\") ? b.pathInfo : isNotNoOps() ? b.request.getPathInfo() : \"\";\n }\n\n @Override\n public String getPathTranslated() {\n return b.request.getPathTranslated();\n }\n\n @Override\n public String getQueryString() {\n return !Objects.equals(b.queryString, \"\") ? b.queryString : isNotNoOps() ? b.request.getQueryString() : toQs();\n }\n\n private String toQs() {\n StringBuilder q = new StringBuilder();\n for (Map.Entry e : b.queryStrings.entrySet()) {\n for (String k : e.getValue()) {\n q.append(e.getKey()).append(\"=\").append(k).append(\"&\");\n }\n }\n if (q.length() > 0) q.deleteCharAt(q.length() - 1);\n return q.toString();\n }\n\n @Override\n public String getRemoteUser() {\n return b.principal != null ? b.principal.getName() : b.request.getRemoteUser();\n }\n\n @Override\n public String getRequestedSessionId() {\n return b.request.getRequestedSessionId();\n }\n\n @Override\n public String getMethod() {\n return b.methodType != null ? b.methodType : b.request.getMethod();\n }\n\n @Override\n public Part getPart(String name) throws IOException, ServletException {\n return b.request.getPart(name);\n }\n\n @Override\n public Collection getParts() throws IOException, ServletException {\n return b.request.getParts();\n }\n\n @Override\n public String getContentType() {\n return b.contentType != null || b.noContentType ? b.contentType : b.request.getContentType();\n }\n\n @Override\n public DispatcherType getDispatcherType() {\n return b.request.getDispatcherType();\n }\n\n @Override\n public String getServletPath() {\n return !Objects.equals(b.servletPath, \"\") ? b.servletPath : (isNotNoOps() ? b.request.getServletPath() : \"\");\n }\n\n @Override\n public String getRequestURI() {\n return b.requestURI != null ? b.requestURI : (isNotNoOps() ? b.request.getRequestURI() : \"\");\n }\n\n @Override\n public StringBuffer getRequestURL() {\n return b.requestURL != null ? new StringBuffer(b.requestURL) : (isNotNoOps() ? b.request.getRequestURL() : new StringBuffer());\n }\n\n @Override\n public Enumeration getHeaders(String name) {\n\n ArrayList list = new ArrayList<>();\n // Never override the parent Request\n if (!name.equalsIgnoreCase(\"content-type\")) {\n Enumeration e = b.request.getHeaders(name);\n while (e.hasMoreElements())\n list.add(e.nextElement());\n }\n\n if (name.equalsIgnoreCase(\"content-type\")) {\n String s = getContentType();\n if (s != null) {\n list.add(s);\n }\n } else {\n if (b.headers.get(name) != null) {\n list.add(b.headers.get(name));\n }\n\n if (isNotNoOps()) {\n if (list.isEmpty() && name.startsWith(X_ATMOSPHERE)) {\n if (attributeWithoutException(b.request, name) != null) {\n list.add(attributeWithoutException(b.request, name));\n }\n }\n }\n }\n return Collections.enumeration(list);\n }\n\n @Override\n public int getIntHeader(String name) {\n return b.request.getIntHeader(name);\n }\n\n @Override\n public Enumeration getHeaderNames() {\n Set list = new HashSet<>();\n list.addAll(b.headers.keySet());\n\n list.addAll(Collections.list(b.request.getHeaderNames()));\n if (b.request != null) {\n Enumeration e = b.request.getAttributeNames();\n while (e.hasMoreElements()) {\n String name = e.nextElement();\n if (name.startsWith(X_ATMOSPHERE)) {\n list.add(name);\n }\n }\n }\n\n if (b.contentType != null) {\n list.add(\"Content-Type\");\n }\n return Collections.enumeration(list);\n }\n\n @Override\n public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {\n return b.request.authenticate(response);\n }\n\n @Override\n public String getAuthType() {\n return b.authType != null ? b.authType : b.request.getAuthType();\n }\n\n @Override\n public String getContextPath() {\n String c = \"/\";\n try {\n c = isNotNoOps() && b.request.getContextPath() != null ? b.request.getContextPath() : b.contextPath != null ? b.contextPath : \"\";\n } catch (NullPointerException ex) {\n // https://github.com/Atmosphere/atmosphere/issues/1804\n logger.warn(\"Unexpected getContextPath exception. Forcing `/`\", ex);\n }\n return c;\n }\n\n @Override\n public Cookie[] getCookies() {\n if (!cookieComputed) {\n if (b.cookies == null)\n return new Cookie[0];\n cookieComputed = true;\n Cookie[] c = b.request.getCookies();\n if (c != null && c.length > 0) {\n b.cookies.addAll(Arrays.asList(c));\n }\n }\n return b.cookies.toArray(new Cookie[]{});\n }\n\n @Override\n public long getDateHeader(String name) {\n return b.request.getDateHeader(name);\n }\n\n @Override\n public String getHeader(String s) {\n return getHeader(s, true);\n }\n\n @Override\n public HttpServletRequest wrappedRequest() {\n return b.request;\n }\n\n @Override\n public String getHeader(String s, boolean checkCase) {\n\n if (\"content-type\".equalsIgnoreCase(s)) {\n return getContentType();\n }\n\n String name = b.request.getHeader(s);\n if (name == null) {\n if (b.headers.get(s) != null) {\n return b.headers.get(s);\n }\n\n if (s.startsWith(X_ATMOSPHERE) && isNotNoOps()) {\n // Craziness with Struts 2 who wraps String attribute as BigDecimal\n // https://github.com/Atmosphere/atmosphere/issues/1367\n Object o = attributeWithoutException(b.request, s);\n if (o == null || String.class.isAssignableFrom(o.getClass())) {\n name = (String) o;\n } else {\n try {\n if (HttpServletRequestWrapper.class.isAssignableFrom(b.request.getClass())) {\n HttpServletRequest hsr = b.request;\n while (hsr instanceof HttpServletRequestWrapper) {\n hsr = (HttpServletRequest) ((HttpServletRequestWrapper) hsr).getRequest();\n o = attributeWithoutException(hsr, s);\n if (o == null || String.class.isAssignableFrom(o.getClass())) {\n name = (String) o;\n break;\n }\n }\n }\n } catch (Exception ex) {\n logger.warn(\"\", ex);\n }\n }\n }\n }\n\n if (name == null && checkCase) {\n return getHeader(s.toLowerCase(), false);\n }\n\n if (name == null && \"connection\".equalsIgnoreCase(s)) {\n return \"keep-alive\";\n }\n\n return name;\n }\n\n @Override\n public String getParameter(String s) {\n String name = isNotNoOps() ? b.request.getParameter(s) : null;\n if (name == null) {\n if (b.queryStrings.get(s) != null) {\n return b.queryStrings.get(s)[0];\n }\n }\n return name;\n }\n\n @Override\n public Map getParameterMap() {\n if (!queryComputed) {\n queryComputed = true;\n Map m = (isNotNoOps() ? b.request.getParameterMap() : Collections.emptyMap());\n for (String e : m.keySet()) {\n b.queryStrings.put(e, getParameterValues(e));\n }\n }\n return Collections.unmodifiableMap(b.queryStrings);\n }\n\n @Override\n public Enumeration getParameterNames() {\n return Collections.enumeration(getParameterMap().keySet());\n }\n\n @Override\n public String[] getParameterValues(String s) {\n String[] list = b.request.getParameterValues(s);\n if (list != null && b.queryStrings.get(s) != null) {\n String[] newList = b.queryStrings.get(s);\n if (!Arrays.deepEquals(list, newList)) {\n String[] s1 = new String[list.length + newList.length];\n System.arraycopy(list, 0, s1, 0, list.length);\n System.arraycopy(newList, 0, s1, list.length, newList.length);\n return s1;\n } else {\n return list;\n }\n } else {\n return list == null ? b.queryStrings.get(s) : list;\n }\n }\n\n @Override\n public String getProtocol() {\n return b.request.getProtocol();\n }\n\n @Override\n public ServletInputStream getInputStream() throws IOException {\n if (b.body.isEmpty()) {\n configureStream();\n return bis == null ? (isNotNoOps() ? b.request.getInputStream() : voidStream) : bis;\n } else if (b.body.hasString()) {\n bis = new IS(new ByteArrayInputStream(b.body.asString().getBytes()));\n } else if (b.body.hasBytes()) {\n bis = new IS(new ByteArrayInputStream(b.body.asBytes(), b.body.offset, b.body.byteLength()));\n }\n return bis;\n }\n\n @Override\n public BufferedReader getReader() throws IOException {\n if (b.body.isEmpty()) {\n configureReader();\n return br == null ? (isNotNoOps() ? b.request.getReader() : getVoidReader()) : br;\n } else if (b.body.hasString()) {\n br = new BufferedReader(new StringReader(body().asString()));\n } else if (b.body.hasBytes()) {\n br = new BufferedReader(new StringReader(new String(body().asBytes(), body().byteOffset(), body().length)));\n }\n return br;\n }\n\n @Override\n public String getRealPath(String path) {\n return b.request.getRealPath(path);\n }\n\n @Override\n public AtmosphereRequest headers(Map headers) {\n b.headers.putAll(headers);\n return this;\n }\n\n @Override\n public AtmosphereRequest header(String name, String value) {\n b.headers.put(name, value);\n return this;\n }\n\n @Override\n public AtmosphereRequest queryString(String qs) {\n\n if (qs == null) return this;\n\n if (!qs.isEmpty()) {\n QueryStringDecoder decoder = new QueryStringDecoder(getRequestURI() + \"?\" + qs);\n Map> m = decoder.getParameters();\n Map newM = new HashMap<>();\n for (Map.Entry> q : m.entrySet()) {\n newM.put(q.getKey(), q.getValue().toArray(new String[0]));\n }\n b.queryStrings(newM);\n }\n b.queryString = qs;\n return this;\n }\n\n @Override\n public Map headersMap() {\n return b.headers;\n }\n\n @Override\n public Map queryStringsMap() {\n return b.queryStrings;\n }\n\n @Override\n public AtmosphereRequest method(String m) {\n b.method(m);\n return this;\n }\n\n @Override\n public AtmosphereRequest contentType(String m) {\n b.contentType(m);\n return this;\n }\n\n @Override\n public AtmosphereRequest body(String body) {\n b.body = new Body(body, null, 0, 0);\n return this;\n }\n\n @Override\n public AtmosphereRequest body(byte[] bytes) {\n b.body = new Body(null, bytes, 0, bytes.length);\n return this;\n }\n\n @Override\n public AtmosphereRequest body(InputStream body) {\n bis = new IS(body);\n br = new BufferedReader(new InputStreamReader(body));\n return this;\n }\n\n @Override\n public AtmosphereRequest body(Reader body) {\n bis = new IS(new ReaderInputStream(body));\n br = new BufferedReader(body);\n return this;\n }\n\n @Override\n public Body body() {\n return b.body;\n }\n\n @Override\n public AtmosphereRequest servletPath(String servletPath) {\n b.servletPath = servletPath;\n return this;\n }\n\n @Override\n public AtmosphereRequest contextPath(String contextPath) {\n b.contextPath = contextPath;\n return this;\n }\n\n @Override\n public AtmosphereRequest requestURI(String requestURI) {\n b.requestURI = requestURI;\n return this;\n }\n\n private final static class ByteInputStream extends ServletInputStream {\n\n private final ByteArrayInputStream bis;\n\n public ByteInputStream(byte[] data, int offset, int length) {\n this.bis = new ByteArrayInputStream(data, offset, length);\n }\n\n @Override\n public int read() throws IOException {\n return bis.read();\n }\n }\n\n @Override\n public void setAttribute(String s, Object o) {\n if (o == null) {\n removeAttribute(s);\n return;\n }\n b.localAttributes.put(s, o);\n if (isNotNoOps() && !destroyed.get()) {\n try {\n synchronized (b.request) {\n b.request.setAttribute(s, o);\n }\n } catch (NullPointerException ex) {\n // https://github.com/Atmosphere/atmosphere/issues/1806\n logger.trace(\"\", ex);\n }\n }\n }\n\n @Override\n public void setCharacterEncoding(String env) throws UnsupportedEncodingException {\n b.request.setCharacterEncoding(env);\n }\n\n @Override\n public AsyncContext startAsync() {\n AsyncContext ac;\n if (AtmosphereResource.TRANSPORT.WEBSOCKET == resource().transport()) {\n noopsAsyncContextStarted = true;\n ac = new NoOpsAsyncContext(getRequest(), resource().getResponse().getResponse());\n } else {\n ac = b.request.startAsync();\n }\n return isCompletionAware()\n ? new CompletionAwareAsyncContext(ac, (CompletionAware) resource().getResponse()) : ac;\n }\n\n @Override\n public AsyncContext startAsync(ServletRequest request, ServletResponse response) {\n AsyncContext ac;\n if (AtmosphereResource.TRANSPORT.WEBSOCKET == resource().transport()) {\n noopsAsyncContextStarted = true;\n ac = new NoOpsAsyncContext(request, response);\n } else {\n ac = b.request.startAsync(request, response);\n }\n return isCompletionAware()\n ? new CompletionAwareAsyncContext(ac, (CompletionAware) resource().getResponse()) : ac;\n }\n\n @Override\n public AsyncContext getAsyncContext() {\n AsyncContext ac;\n if (AtmosphereResource.TRANSPORT.WEBSOCKET == resource().transport()) {\n noopsAsyncContextStarted = true;\n ac = new NoOpsAsyncContext(getRequest(), resource().getResponse().getResponse());\n } else {\n ac = b.request.getAsyncContext();\n }\n return isCompletionAware()\n ? new CompletionAwareAsyncContext(ac, (CompletionAware) resource().getResponse()) : ac;\n }\n\n @Override\n public Object getAttribute(String s) {\n return b.localAttributes.get(s) != null ? b.localAttributes.get(s) : (isNotNoOps() ? attributeWithoutException(b.request, s) : null);\n }\n\n @Override\n public void removeAttribute(String name) {\n\n b.localAttributes.remove(name);\n if (isNotNoOps() && !destroyed.get()) {\n synchronized (b.request) {\n b.request.removeAttribute(name);\n }\n }\n }\n\n @Override\n public LocalAttributes attributes() {\n return b.localAttributes;\n }\n\n @Override\n public HttpSession getSession() {\n return getSession(true);\n }\n\n @Override\n public HttpSession getSession(boolean create) {\n if (b.webSocketFakeSession != null) {\n return b.webSocketFakeSession;\n }\n\n if (resource() != null) {\n // UGLY, but we need to prevent looping here.\n HttpSession session = ((AtmosphereResourceImpl) resource()).session;\n try {\n if (session != null) {\n // check if session is valid (isNew() will throw if not)\n session.isNew();\n return session;\n }\n } catch (IllegalStateException e) {\n // session has been invalidated\n }\n }\n\n try {\n return b.request.getSession(create);\n } catch (java.lang.IllegalStateException ex) {\n // JettyAsyncSupportListenerAdapter\n if (ex.getMessage() != null && ex.getMessage().equals(\"No SessionManager\")) {\n return null;\n }\n throw ex;\n } catch (NullPointerException ex) {\n // GLASSFISH http://java.net/jira/browse/GLASSFISH-18856\n try {\n return b.request.getSession(create);\n } catch (Exception e) {\n logger.trace(\"\", ex);\n return null;\n }\n } catch (RuntimeException ex) {\n // https://github.com/Atmosphere/atmosphere/issues/1974\n logger.trace(\"\", ex);\n if (ex.getMessage() != null && ex.getMessage().contains(\"SESN0007E\")) {\n return null;\n }\n throw ex;\n }\n }\n\n @Override\n public Principal getUserPrincipal() {\n return b.principal != null ? b.principal : b.request.getUserPrincipal();\n }\n\n @Override\n public boolean isRequestedSessionIdFromCookie() {\n return b.request.isRequestedSessionIdFromCookie();\n }\n\n @Override\n public boolean isRequestedSessionIdFromUrl() {\n return b.request.isRequestedSessionIdFromUrl();\n }\n\n @Override\n public boolean isRequestedSessionIdFromURL() {\n return b.request.isRequestedSessionIdFromURL();\n }\n\n @Override\n public boolean isRequestedSessionIdValid() {\n return b.request.isRequestedSessionIdValid();\n }\n\n @Override\n public boolean isUserInRole(String role) {\n return b.request.isUserInRole(role);\n }\n\n @Override\n public void login(String username, String password) throws ServletException {\n b.request.login(username, password);\n }\n\n @Override\n public void logout() throws ServletException {\n b.request.logout();\n }\n\n @Override\n public String getRemoteAddr() {\n return isNotNoOps() ? b.request.getRemoteAddr() : b.lazyRemote != null ? b.lazyRemote.getHostAddress() : b.remoteAddr;\n }\n\n @Override\n public String getRemoteHost() {\n return isNotNoOps() ? b.request.getRemoteHost() : b.lazyRemote != null ? b.lazyRemote.getHostName() : b.remoteHost;\n }\n\n @Override\n public int getRemotePort() {\n return isNotNoOps() ? b.request.getRemotePort() : b.lazyRemote != null ? b.lazyRemote.getPort() : b.remotePort;\n }\n\n @Override\n public RequestDispatcher getRequestDispatcher(String path) {\n return b.request.getRequestDispatcher(path);\n }\n\n @Override\n public String getScheme() {\n return b.request.getScheme();\n }\n\n @Override\n public String getServerName() {\n return !b.serverName.equals(\"\") ? b.serverName : b.request.getServerName();\n }\n\n @Override\n public int getServerPort() {\n return b.serverPort != 0 ? b.serverPort : b.request.getServerPort();\n }\n\n @Override\n public ServletContext getServletContext() {\n return b.request.getServletContext();\n }\n\n @Override\n public boolean isAsyncStarted() {\n if (resource() != null && AtmosphereResource.TRANSPORT.WEBSOCKET == resource().transport()) {\n return noopsAsyncContextStarted;\n }\n try {\n return b.request.isAsyncStarted();\n } catch (Throwable ex) {\n logger.trace(\"\", ex);\n return false;\n }\n }\n\n @Override\n public boolean isAsyncSupported() {\n try {\n return b.request.isAsyncSupported();\n } catch (Throwable ex) {\n // Servlet 2.5 incompatible API.\n logger.trace(\"\", ex);\n return false;\n }\n }\n\n @Override\n public boolean isSecure() {\n return isNotNoOps() ? b.request.isSecure() : b.isSecure;\n }\n\n @Override\n public String getLocalName() {\n return isNotNoOps() ? b.request.getLocalName() : b.lazyLocal != null ? b.lazyLocal.getHostName() : b.localName;\n }\n\n @Override\n public int getLocalPort() {\n return isNotNoOps() ? b.request.getLocalPort() : b.lazyLocal != null ? b.lazyLocal.getPort() : b.localPort;\n }\n\n @Override\n public String getLocalAddr() {\n return isNotNoOps() ? b.request.getLocalAddr() : b.lazyLocal != null ? b.lazyLocal.getHostAddress() : b.localAddr;\n }\n\n private boolean isNotNoOps() {\n return !NoOpsRequest.class.isAssignableFrom(b.request.getClass());\n }\n\n @Override\n public Locale getLocale() {\n return isNotNoOps() ? b.request.getLocale() : b.locales.iterator().hasNext() ? b.locales.iterator().next() : Locale.getDefault();\n }\n\n @Override\n public AtmosphereResource resource() {\n try {\n Object o = getAttribute(FrameworkConfig.ATMOSPHERE_RESOURCE);\n if (!(o instanceof AtmosphereResource)) {\n // WebSphere is in trouble.\n return null;\n }\n return (AtmosphereResource) getAttribute(FrameworkConfig.ATMOSPHERE_RESOURCE);\n } catch (Exception ex) {\n logger.warn(\"\", ex);\n return null;\n }\n }\n\n @Override\n public Enumeration getLocales() {\n return isNotNoOps() ? b.request.getLocales() : Collections.enumeration(b.locales);\n }\n\n @Override\n public boolean dispatchRequestAsynchronously() {\n return b.dispatchRequestAsynchronously;\n }\n\n @Override\n public boolean isDestroyable() {\n return b.destroyable;\n }\n\n @Override\n public AtmosphereRequest pathInfo(String pathInfo) {\n b.pathInfo = pathInfo;\n return this;\n }\n\n @Override\n public Enumeration getAttributeNames() {\n Set l = new HashSet<>(b.localAttributes.unmodifiableMap().keySet());\n\n if (isNotNoOps()) {\n synchronized (b.request) {\n l.addAll(Collections.list(b.request.getAttributeNames()));\n }\n }\n return Collections.enumeration(l);\n }\n\n private static Object attributeWithoutException(HttpServletRequest request, String attribute) {\n try {\n return request.getAttribute(attribute);\n } catch (NullPointerException ex) {\n // https://github.com/Atmosphere/atmosphere/issues/1732\n logger.trace(\"Unexpected NPE\", ex);\n return \"\";\n }\n }\n\n @Override\n public LocalAttributes localAttributes() {\n return b.localAttributes;\n }\n\n @Override\n public String getCharacterEncoding() {\n return b.request.getCharacterEncoding() == null ? b.encoding : b.request.getCharacterEncoding();\n }\n\n @Override\n public int getContentLength() {\n if (b.contentLength == null) {\n return b.request.getContentLength();\n } else {\n return b.contentLength.intValue();\n }\n }\n\n @Override\n public String uuid() {\n if (Objects.equals(uuid, \"0\")) {\n this.uuid = resource() != null ? resource().uuid() : \"0\";\n }\n return uuid;\n }\n\n @Override\n public void destroy() {\n destroy(b.destroyable);\n }\n\n @Override\n public void destroy(boolean force) {\n if (!force) return;\n destroyed.set(true);\n b.localAttributes.clear();\n if (bis != null) {\n try {\n bis.close();\n } catch (IOException e) {\n }\n }\n\n if (br != null) {\n try {\n br.close();\n } catch (IOException e) {\n }\n }\n\n b.headers.clear();\n b.queryStrings.clear();\n }\n\n @Override\n public void setRequest(ServletRequest request) {\n super.setRequest(request);\n if (HttpServletRequest.class.isAssignableFrom(request.getClass())) {\n b.request = (HttpServletRequest) request;\n }\n }\n\n public final static class Builder implements AtmosphereRequest.Builder {\n private final static Body NULL_BODY = new Body(null, null, 0, 0);\n private HttpServletRequest request;\n private String pathInfo = \"\";\n private String encoding = \"UTF-8\";\n private String methodType;\n private String contentType;\n private boolean noContentType;\n private Long contentLength;\n private Map headers = Collections.synchronizedMap(new HashMap<>());\n private Map queryStrings = Collections.synchronizedMap(new HashMap<>());\n private String servletPath = \"\";\n private String requestURI;\n private String requestURL;\n private InputStream inputStream;\n private Reader reader;\n private String remoteAddr = \"\";\n private String remoteHost = \"\";\n private int remotePort;\n private String localAddr = \"\";\n private String localName = \"\";\n private int localPort;\n private boolean dispatchRequestAsynchronously;\n private boolean destroyable = true;\n private Set cookies = Collections.synchronizedSet(new HashSet<>());\n private final Set locales = Collections.synchronizedSet(new HashSet<>());\n private Principal principal;\n private String authType;\n private String contextPath = \"\";\n private String serverName = \"\";\n private int serverPort;\n private HttpSession webSocketFakeSession;\n private String queryString = \"\";\n private boolean isSecure;\n // Callable to lazily execute.\n private LazyComputation lazyRemote;\n private LazyComputation lazyLocal;\n public Body body;\n private LocalAttributes localAttributes = new LocalAttributes();\n\n public Builder() {\n }\n\n @Override\n public Builder destroyable(boolean destroyable) {\n this.destroyable = destroyable;\n return this;\n }\n\n @Override\n public Builder headers(Map headers) {\n this.headers = Collections.synchronizedMap(headers);\n return this;\n }\n\n @Override\n public Builder cookies(Set cookies) {\n this.cookies = cookies;\n return this;\n }\n\n @Override\n public Builder dispatchRequestAsynchronously(boolean dispatchRequestAsynchronously) {\n this.dispatchRequestAsynchronously = dispatchRequestAsynchronously;\n return this;\n }\n\n @Override\n public Builder remoteAddr(String remoteAddr) {\n this.remoteAddr = remoteAddr;\n return this;\n }\n\n @Override\n public Builder remoteHost(String remoteHost) {\n this.remoteHost = remoteHost;\n return this;\n }\n\n @Override\n public Builder remotePort(int remotePort) {\n this.remotePort = remotePort;\n return this;\n }\n\n @Override\n public Builder localAddr(String localAddr) {\n this.localAddr = localAddr;\n return this;\n }\n\n @Override\n public Builder localName(String localName) {\n this.localName = localName;\n return this;\n }\n\n @Override\n public Builder localPort(int localPort) {\n this.localPort = localPort;\n return this;\n }\n\n @Override\n public Builder remoteInetSocketAddress(Callable remoteAddr) {\n this.lazyRemote = new LazyComputation(remoteAddr);\n return this;\n }\n\n @Override\n public Builder localInetSocketAddress(Callable localAddr) {\n this.lazyLocal = new LazyComputation(localAddr);\n return this;\n }\n\n @Override\n public Builder attributes(Map attributes) {\n localAttributes = new LocalAttributes(attributes);\n return this;\n }\n\n @Override\n public Builder request(HttpServletRequest request) {\n this.request = request;\n return this;\n }\n\n @Override\n public Builder servletPath(String servletPath) {\n this.servletPath = servletPath;\n return this;\n }\n\n @Override\n public Builder requestURI(String requestURI) {\n this.requestURI = requestURI;\n return this;\n }\n\n @Override\n public Builder requestURL(String requestURL) {\n this.requestURL = requestURL;\n return this;\n }\n\n @Override\n public Builder pathInfo(String pathInfo) {\n this.pathInfo = pathInfo;\n return this;\n }\n\n @Override\n public Builder queryString(String queryString) {\n this.queryString = queryString;\n return this;\n }\n\n @Override\n public Builder body(byte[] dataBytes) {\n return body(dataBytes, 0, dataBytes.length);\n }\n\n @Override\n public Builder body(byte[] dataBytes, int offset, int length) {\n this.body = new Body(null, dataBytes, offset, length);\n return this;\n }\n\n @Override\n public Builder encoding(String encoding) {\n this.encoding = encoding;\n return this;\n }\n\n @Override\n public Builder method(String methodType) {\n this.methodType = methodType;\n return this;\n }\n\n @Override\n public Builder contentType(String contentType) {\n this.contentType = contentType;\n if (contentType == null) {\n noContentType = true;\n }\n return this;\n }\n\n @Override\n public Builder contentLength(Long contentLength) {\n this.contentLength = contentLength;\n return this;\n }\n\n @Override\n public Builder body(String data) {\n this.body = new Body(data, null, 0, 0);\n return this;\n }\n\n @Override\n public Builder inputStream(InputStream inputStream) {\n this.inputStream = inputStream;\n return this;\n }\n\n @Override\n public Builder reader(Reader reader) {\n this.reader = reader;\n return this;\n }\n\n @Override\n public AtmosphereRequest build() {\n if (body == null) {\n body = NULL_BODY;\n }\n return new AtmosphereRequestImpl(this);\n }\n\n @Override\n public Builder queryStrings(Map queryStrings) {\n this.queryStrings = Collections.synchronizedMap(queryStrings);\n return this;\n }\n\n @Override\n public Builder contextPath(String contextPath) {\n this.contextPath = contextPath == null ? \"\" : contextPath;\n return this;\n }\n\n @Override\n public Builder serverName(String serverName) {\n this.serverName = serverName;\n return this;\n }\n\n @Override\n public Builder serverPort(int serverPort) {\n this.serverPort = serverPort;\n return this;\n }\n\n @Override\n public Builder session(HttpSession session) {\n if (request == null) {\n request = new NoOpsRequest();\n }\n\n if (NoOpsRequest.class.isAssignableFrom(request.getClass())) {\n ((NoOpsRequest) request).fake = session;\n } else {\n webSocketFakeSession = session;\n }\n return this;\n }\n\n @Override\n public Builder principal(Principal principal) {\n this.principal = principal;\n return this;\n }\n\n @Override\n public Builder authType(String authType) {\n this.authType = authType;\n return this;\n }\n\n @Override\n public Builder isSSecure(boolean isSecure) {\n this.isSecure = isSecure;\n return this;\n }\n\n @Override\n public Builder locale(Locale locale) {\n locales.add(locale);\n return this;\n }\n\n @Override\n public Builder userPrincipal(Principal userPrincipal) {\n this.principal = userPrincipal;\n return this;\n }\n }\n\n public final static class Body {\n private final String data;\n private final byte[] dataBytes;\n private final int offset;\n private final int length;\n private final boolean isEmpty;\n\n public Body(String data, byte[] dataBytes, int offset, int length) {\n this.data = data;\n this.dataBytes = dataBytes;\n this.offset = offset;\n this.length = length;\n isEmpty = data == null && dataBytes == null;\n }\n\n /**\n * True is the body is a String\n *\n * @return True is the body is a String\n */\n public boolean hasString() {\n return data != null;\n }\n\n /**\n * True is the body is a byte array\n *\n * @return True is the body is a byte array\n */\n public boolean hasBytes() {\n return dataBytes != null;\n }\n\n /**\n * Return the request body as a String. If the body was a byte array, this method will return null.\n *\n * @return the request body as a String. If the body was a byte array, this method will return null.\n */\n public String asString() {\n return data;\n }\n\n /**\n * Return the request body as a byte array. If the body was String, this method will return null.\n *\n * @return the request body as a byte array. If the body was String, this method will return null.\n */\n public byte[] asBytes() {\n return dataBytes;\n }\n\n /**\n * The {@link #asBytes()} offset\n *\n * @return The {@link #asBytes()} offset\n */\n public int byteOffset() {\n return offset;\n }\n\n /**\n * The {@link #asBytes()} length\n *\n * @return The {@link #asBytes()} length\n */\n public int byteLength() {\n return length;\n }\n\n /**\n * True if this object is empty\n *\n * @return True if this object is empty\n */\n public boolean isEmpty() {\n return isEmpty;\n }\n }\n\n private final static class IS extends ServletInputStream {\n\n private final InputStream innerStream;\n\n public IS(InputStream innerStream) {\n super();\n this.innerStream = innerStream;\n }\n\n public int read() throws java.io.IOException {\n return innerStream.read();\n }\n\n public int read(byte[] bytes) throws java.io.IOException {\n return innerStream.read(bytes);\n }\n\n public int read(byte[] bytes, int i, int i1) throws java.io.IOException {\n return innerStream.read(bytes, i, i1);\n }\n\n\n public long skip(long l) throws java.io.IOException {\n return innerStream.skip(l);\n }\n\n public int available() throws java.io.IOException {\n return innerStream.available();\n }\n\n public void close() throws java.io.IOException {\n innerStream.close();\n }\n\n public synchronized void mark(int i) {\n innerStream.mark(i);\n }\n\n public synchronized void reset() throws java.io.IOException {\n innerStream.reset();\n }\n\n public boolean markSupported() {\n return innerStream.markSupported();\n }\n }\n\n /**\n * Create an instance of this class without an associated {@link HttpServletRequest}.\n *\n * @return an instance of this class without an associated {@link HttpServletRequest}\n */\n public static AtmosphereRequest newInstance() {\n return new Builder().build();\n }\n\n /**\n * Wrap an {@link HttpServletRequest}.\n *\n * @param request {@link HttpServletRequest}\n * @return an {@link AtmosphereRequest}\n */\n public static AtmosphereRequest wrap(HttpServletRequest request) {\n // Do not rewrap.\n if (AtmosphereRequestImpl.class.isAssignableFrom(request.getClass())) {\n return (AtmosphereRequestImpl) request;\n }\n\n Builder b = new Builder();\n Enumeration e = request.getAttributeNames();\n String s;\n while (e.hasMoreElements()) {\n s = e.nextElement();\n b.localAttributes.put(s, attributeWithoutException(request, s));\n }\n return b.request(request).build();\n }\n\n\n /**\n * Copy the HttpServletRequest content inside an AtmosphereRequest. By default the returned AtmosphereRequest\n * is not destroyable.\n *\n * @param request {@link HttpServletRequest}\n * @return an {@link AtmosphereRequest}\n */\n public static AtmosphereRequest cloneRequest(HttpServletRequest request, boolean loadInMemory, boolean copySession, boolean isDestroyable, boolean createSession) {\n Builder b;\n HttpServletRequest r;\n\n Cookie[] cs = request.getCookies();\n Set hs = Collections.synchronizedSet(new HashSet<>());\n if (cs != null) {\n Collections.addAll(hs, cs);\n }\n\n boolean isWrapped = false;\n if (AtmosphereRequestImpl.class.isAssignableFrom(request.getClass())) {\n b = ((AtmosphereRequestImpl) request).b;\n isWrapped = true;\n } else {\n b = new Builder();\n b.request(request);\n }\n\n HttpSession session = request.getSession(false);\n if (copySession) {\n session = request.getSession(createSession);\n if (session != null) {\n session = new FakeHttpSession(session);\n } else {\n session = new FakeHttpSession(\"\", null, System.currentTimeMillis(), -1);\n }\n }\n\n b.servletPath(request.getServletPath())\n .pathInfo(request.getPathInfo())\n .contextPath(request.getContextPath())\n .requestURI(request.getRequestURI())\n .requestURL(request.getRequestURL().toString())\n .method(request.getMethod())\n .serverName(request.getServerName())\n .serverPort(request.getServerPort())\n .remoteAddr(request.getRemoteAddr())\n .remoteHost(request.getRemoteHost())\n .remotePort(request.getRemotePort())\n .destroyable(isDestroyable)\n .cookies(hs)\n .session(session)\n .principal(request.getUserPrincipal())\n .authType(request.getAuthType())\n .isSSecure(request.isSecure());\n\n if (loadInMemory) {\n String s = (String) attributeWithoutException(request, FrameworkConfig.THROW_EXCEPTION_ON_CLONED_REQUEST);\n boolean throwException = Boolean.parseBoolean(s);\n r = new NoOpsRequest(throwException);\n if (isWrapped) {\n load(b.request, b);\n } else {\n load(request, b);\n }\n b.request(r);\n }\n\n return isWrapped ? (AtmosphereRequestImpl) request : b.build();\n }\n\n public final static class NoOpsRequest implements HttpServletRequest {\n\n private final boolean throwExceptionOnCloned;\n public HttpSession fake;\n private final static Enumeration EMPTY_ENUM_STRING = Collections.enumeration(Collections.emptyList());\n private final static Enumeration EMPTY_ENUM_LOCALE = Collections.enumeration(Collections.emptyList());\n private final static List EMPTY_ENUM_PART = Collections.emptyList();\n private final static Map EMPTY_MAP_STRING = Collections.emptyMap();\n private final static String[] EMPTY_ARRAY = new String[0];\n private final StringBuffer EMPTY_STRING_BUFFER = new StringBuffer();\n private final static Cookie[] EMPTY_COOKIE = new Cookie[0];\n private volatile BufferedReader voidReader;\n private final ServletInputStream voidStream = new AtmosphereRequestImpl.IS(new ByteArrayInputStream(new byte[0]));\n\n public NoOpsRequest() {\n this.throwExceptionOnCloned = false;\n }\n\n public NoOpsRequest(boolean throwExceptionOnCloned) {\n this.throwExceptionOnCloned = throwExceptionOnCloned;\n }\n\n private BufferedReader getVoidReader() {\n if (voidReader == null) {\n voidReader = new BufferedReader(new StringReader(\"\"));\n }\n return voidReader;\n }\n\n @Override\n public boolean authenticate(HttpServletResponse response) {\n return false;\n }\n\n @Override\n public String getAuthType() {\n return null;\n }\n\n @Override\n public String getContextPath() {\n return \"\";\n }\n\n @Override\n public Cookie[] getCookies() {\n return EMPTY_COOKIE;\n }\n\n @Override\n public long getDateHeader(String name) {\n return 0;\n }\n\n @Override\n public String getHeader(String name) {\n return null;\n }\n\n @Override\n public Enumeration getHeaderNames() {\n return EMPTY_ENUM_STRING;\n }\n\n @Override\n public Enumeration getHeaders(String name) {\n return EMPTY_ENUM_STRING;\n }\n\n @Override\n public int getIntHeader(String name) {\n return 0;\n }\n\n @Override\n public String getMethod() {\n return \"GET\";\n }\n\n @Override\n public Part getPart(String name) throws IOException, ServletException {\n return null;\n }\n\n @Override\n public Collection getParts() throws IOException, ServletException {\n return EMPTY_ENUM_PART;\n }\n\n @Override\n public String getPathInfo() {\n return \"\";\n }\n\n @Override\n public String getPathTranslated() {\n return \"\";\n }\n\n @Override\n public String getQueryString() {\n return \"\";\n }\n\n @Override\n public String getRemoteUser() {\n return \"\";\n }\n\n @Override\n public String getRequestedSessionId() {\n return \"\";\n }\n\n @Override\n public String getRequestURI() {\n return \"/\";\n }\n\n @Override\n public StringBuffer getRequestURL() {\n return EMPTY_STRING_BUFFER;\n }\n\n @Override\n public String getServletPath() {\n return \"\";\n }\n\n @Override\n public HttpSession getSession() {\n return fake;\n }\n\n @Override\n public HttpSession getSession(boolean create) {\n if (create && fake == null) {\n fake = new FakeHttpSession(\"\", null, System.currentTimeMillis(), -1) {\n @Override\n public void invalidate() {\n fake = null;\n super.invalidate();\n }\n };\n }\n return fake;\n }\n\n @Override\n public Principal getUserPrincipal() {\n return null;\n }\n\n @Override\n public boolean isRequestedSessionIdFromCookie() {\n return false;\n }\n\n @Override\n public boolean isRequestedSessionIdFromUrl() {\n return false;\n }\n\n @Override\n public boolean isRequestedSessionIdFromURL() {\n return false;\n }\n\n @Override\n public boolean isRequestedSessionIdValid() {\n return false;\n }\n\n @Override\n public boolean isUserInRole(String role) {\n if (this.throwExceptionOnCloned) {\n throw new UnsupportedOperationException();\n }\n return false;\n }\n\n @Override\n public void login(String username, String password) throws ServletException {\n if (this.throwExceptionOnCloned) {\n throw new ServletException();\n }\n }\n\n @Override\n public void logout() throws ServletException {\n if (this.throwExceptionOnCloned) {\n throw new ServletException();\n }\n }\n\n @Override\n public AsyncContext getAsyncContext() {\n return null;\n }\n\n @Override\n public Object getAttribute(String name) {\n return null;\n }\n\n @Override\n public Enumeration getAttributeNames() {\n return EMPTY_ENUM_STRING;\n }\n\n @Override\n public String getCharacterEncoding() {\n return null;\n }\n\n @Override\n public int getContentLength() {\n return 0;\n }\n\n @Override\n public String getContentType() {\n return \"text/plain\";\n }\n\n @Override\n public DispatcherType getDispatcherType() {\n return DispatcherType.REQUEST;\n }\n\n @Override\n public ServletInputStream getInputStream() throws IOException {\n return voidStream;\n }\n\n @Override\n public Locale getLocale() {\n return null;\n }\n\n @Override\n public Enumeration getLocales() {\n return EMPTY_ENUM_LOCALE;\n }\n\n @Override\n public String getLocalName() {\n return null;\n }\n\n @Override\n public int getLocalPort() {\n return 0;\n }\n\n @Override\n public String getLocalAddr() {\n return \"\";\n }\n\n @Override\n public String getParameter(String name) {\n return \"\";\n }\n\n @Override\n public Map getParameterMap() {\n return EMPTY_MAP_STRING;\n }\n\n @Override\n public Enumeration getParameterNames() {\n return EMPTY_ENUM_STRING;\n }\n\n @Override\n public String[] getParameterValues(String name) {\n return EMPTY_ARRAY;\n }\n\n @Override\n public String getProtocol() {\n return \"HTTP/1.1\";\n }\n\n @Override\n public BufferedReader getReader() throws IOException {\n return getVoidReader();\n }\n\n @Override\n public String getRealPath(String path) {\n return path;\n }\n\n @Override\n public String getRemoteAddr() {\n return \"\";\n }\n\n @Override\n public String getRemoteHost() {\n return \"\";\n }\n\n @Override\n public int getRemotePort() {\n return 0;\n }\n\n @Override\n public RequestDispatcher getRequestDispatcher(String path) {\n return null;\n }\n\n @Override\n public String getScheme() {\n return \"ws\";\n }\n\n @Override\n public String getServerName() {\n return \"\";\n }\n\n @Override\n public int getServerPort() {\n return 0;\n }\n\n @Override\n public ServletContext getServletContext() {\n return null;\n }\n\n @Override\n public boolean isAsyncStarted() {\n return false;\n }\n\n @Override\n public boolean isAsyncSupported() {\n return true;\n }\n\n @Override\n public boolean isSecure() {\n return false;\n }\n\n @Override\n public void removeAttribute(String name) {\n\n }\n\n @Override\n public void setAttribute(String name, Object o) {\n\n }\n\n @Override\n public void setCharacterEncoding(String env) throws UnsupportedEncodingException {\n }\n\n @Override\n public AsyncContext startAsync() {\n return null;\n }\n\n @Override\n public AsyncContext startAsync(ServletRequest request, ServletResponse response) {\n return null;\n }\n }\n\n public static final class LazyComputation {\n\n private final Callable callable;\n private InetSocketAddress address;\n\n public LazyComputation(Callable callable) {\n this.callable = callable;\n }\n\n public InetSocketAddress address() {\n if (address == null) {\n try {\n address = callable.call();\n } catch (Exception e) {\n logger.warn(\"\", e);\n }\n\n // Falback\n if (address == null) {\n address = new InetSocketAddress(8080);\n }\n }\n return address;\n }\n\n public int getPort() {\n return address().getPort();\n }\n\n public String getHostAddress() {\n return address().getAddress().getHostAddress();\n }\n\n public String getHostName() {\n return address().getHostName();\n }\n\n }\n\n private boolean isCompletionAware() {\n return Boolean.parseBoolean(resource().getAtmosphereConfig()\n .getInitParameter(ApplicationConfig.RESPONSE_COMPLETION_AWARE));\n }\n\n private class CompletionAwareAsyncContext implements AsyncContext {\n private AsyncContext context;\n private CompletionAware callback;\n\n public CompletionAwareAsyncContext(AsyncContext context, CompletionAware callback) {\n this.context = context;\n this.callback = callback;\n }\n\n public void addListener(AsyncListener listener) throws IllegalStateException {\n context.addListener(listener);\n }\n\n public void addListener(AsyncListener listener, ServletRequest request, ServletResponse response) throws IllegalStateException {\n context.addListener(listener, request, response);\n }\n\n public void complete() {\n context.complete();\n callback.onComplete();\n }\n\n public T createListener(Class clazz) throws ServletException {\n return context.createListener(clazz);\n }\n\n public void dispatch() throws IllegalStateException {\n context.dispatch();\n }\n\n public void dispatch(ServletContext servletContext, String path) throws IllegalStateException {\n context.dispatch(servletContext, path);\n }\n\n public void dispatch(String path) throws IllegalStateException {\n context.dispatch(path);\n }\n\n public ServletRequest getRequest() {\n return context.getRequest();\n }\n\n public ServletResponse getResponse() {\n return context.getResponse();\n }\n\n public long getTimeout() {\n return context.getTimeout();\n }\n\n public boolean hasOriginalRequestAndResponse() {\n return context.hasOriginalRequestAndResponse();\n }\n\n public void setTimeout(long timeoutMilliseconds) throws IllegalStateException {\n context.setTimeout(timeoutMilliseconds);\n }\n\n public void start(Runnable run) {\n context.start(run);\n }\n\n }\n\n private class NoOpsAsyncContext implements AsyncContext {\n private final ServletRequest request;\n private final ServletResponse response;\n private long timeout;\n\n public NoOpsAsyncContext(ServletRequest request, ServletResponse response) {\n this.request = request;\n this.response = response;\n this.timeout = -1;\n }\n\n @Override\n public void addListener(AsyncListener listener) throws IllegalStateException {\n }\n\n @Override\n public void addListener(AsyncListener listener, ServletRequest request, ServletResponse response) throws IllegalStateException {\n }\n\n @Override\n public void complete() {\n }\n\n @Override\n public T createListener(Class clazz) throws ServletException {\n throw new ServletException(\"Not supported\");\n }\n\n @Override\n public void dispatch() throws IllegalStateException {\n }\n\n @Override\n public void dispatch(ServletContext servletContext, String path) throws IllegalStateException {\n }\n\n @Override\n public void dispatch(String path) throws IllegalStateException {\n }\n\n @Override\n public ServletRequest getRequest() {\n return request;\n }\n\n @Override\n public ServletResponse getResponse() {\n return response;\n }\n\n @Override\n public long getTimeout() {\n return timeout;\n }\n\n @Override\n public boolean hasOriginalRequestAndResponse() {\n return false;\n }\n\n @Override\n public void setTimeout(long timeout) throws IllegalStateException {\n this.timeout = timeout;\n }\n\n @Override\n public void start(Runnable run) {\n throw new RuntimeException(\"Not supported\");\n }\n }\n\n private static void load(HttpServletRequest request, Builder b) {\n Enumeration e = request.getHeaderNames();\n String s;\n while (e.hasMoreElements()) {\n s = e.nextElement();\n b.headers.put(s, request.getHeader(s));\n }\n synchronized (b.request) {\n e = request.getAttributeNames();\n }\n while (e.hasMoreElements()) {\n s = e.nextElement();\n b.localAttributes.put(s, attributeWithoutException(request, s));\n }\n\n e = request.getParameterNames();\n while (e.hasMoreElements()) {\n s = e.nextElement();\n b.queryStrings.put(s, request.getParameterValues(s));\n }\n b.queryString = request.getQueryString();\n\n Enumeration l = request.getLocales();\n while (l.hasMoreElements()) {\n b.locale(l.nextElement());\n }\n }\n\n @Override\n public String toString() {\n try {\n return \"AtmosphereRequest{\" +\n \" method=\" + getMethod() +\n \" contextPath=\" + getContextPath() +\n \" servletPath=\" + getServletPath() +\n \" pathInfo=\" + getPathInfo() +\n \" requestURI=\" + getRequestURI() +\n \" requestURL=\" + getRequestURL() +\n \" AtmosphereResource UUID=\" + (resource() != null ? resource().uuid() : \"\") +\n \" destroyable=\" + b.destroyable +\n '}';\n } catch (Exception e) {\n // Jetty error\n return \"AtmosphereRequest{\" +\n \" contextPath=\" + getContextPath() +\n \" servletPath=\" + getServletPath() +\n \" pathInfo=\" + getPathInfo() +\n \" requestURI=\" + getRequestURI() +\n \" destroyable=\" + b.destroyable +\n '}';\n\n }\n }\n\n @Override\n public String requestURL() {\n return b.requestURL;\n }\n}\n", "file_name": "AtmosphereRequestImpl.java", "human_label": "Wrap an HttpServletRequest with the Builder.", "level": "class_runnable", "lineno": "1403", "name": "wrap", "oracle_context": "{ \"apis\" : \"[isAssignableFrom, getClass, getAttributeNames, hasMoreElements, nextElement, put, attributeWithoutException, build, AtmosphereRequestImpl, Builder, localAttributes]\", \"classes\" : \"[Builder, Enumeration, String]\", \"vars\" : \"[localAttributes]\" }", "package": "org.atmosphere.cpr", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767ab1a6d9265ec01867b", "all_context": "{ \"class_level\" : \"import java.io.UTFDataFormatException;\\nimport java.io.UnsupportedEncodingException;\\nimport static java.lang.Character.MIN_HIGH_SURROGATE;\\nimport static java.lang.Character.MIN_LOW_SURROGATE;\\nimport static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT;\\nint[] sizeTable;\\nchar[] DigitTens;\\nchar[] DigitOnes;\\nchar[] digits;\\nbyte[] INT_MIN_VALUE;\\nbyte[] LONG_MIN_VALUE;\\nint TWO_BYTE_LOWER_LIMIT;\\nint ONE_BYTE_EXCLUSIVE;\\nint THREE_BYTE_LOWER_LIMIT;\\nint TWO_BYTE_EXCLUSIVE;\\nint FOUR_BYTE_LOWER_LIMIT;\\nint THREE_BYTE_EXCLUSIVE;\\nint FIVE_BYTE_LOWER_LIMIT;\\nint FOUR_BYTE_EXCLUSIVE;\\nboolean CESU8_COMPAT;\\nStringSerializer();\\nputBytesFromInt(int i,int offset,int size,byte[] buf);\\nputBytesFromLong(long i,int offset,int size,byte[] buf);\\nstringSize(int x);\\nstringSize(long x);\\nwriteLong(long value,WriteSession session,LinkedBuffer lb);\\nwriteFloat(float value,WriteSession session,LinkedBuffer lb);\\nwriteDouble(double value,WriteSession session,LinkedBuffer lb);\\ncomputeUTF8Size(CharSequence str,int index,int len);\\nwriteUTF8(CharSequence str,int i,int len,byte[] buffer,int offset,int limit,WriteSession session,LinkedBuffer lb);\\nwriteUTF8(CharSequence str,int i,int len,WriteSession session,LinkedBuffer lb);\\nwriteUTF8(CharSequence str,WriteSession session,LinkedBuffer lb);\\nwriteAscii(CharSequence str,WriteSession session,LinkedBuffer lb);\\nwriteFixed2ByteInt(int value,byte[] buffer,int offset,boolean littleEndian);\\nwriteUTF8FixedDelimited(CharSequence str,WriteSession session,LinkedBuffer lb);\\nwriteUTF8FixedDelimited(CharSequence str,boolean littleEndian,WriteSession session,LinkedBuffer lb);\\nwriteUTF8OneByteDelimited(CharSequence str,int index,int len,WriteSession session,LinkedBuffer lb);\\nwriteUTF8VarDelimited(CharSequence str,int index,int len,int lowerLimit,int expectedSize,WriteSession session,LinkedBuffer lb);\\nwriteUTF8VarDelimited(CharSequence str,WriteSession session,LinkedBuffer lb);\\nSTRING();\\ndeser(byte[] nonNullValue);\\ndeser(byte[] nonNullValue,int offset,int len);\\ndeserCustomOnly(byte[] nonNullValue);\\nser(String nonNullValue);\\nreadUTF(byte[] buffer,int offset,int len);\\nhighSurrogate(int codePoint);\\nlowSurrogate(int codePoint);\\nwriteInt(int value,WriteSession session,LinkedBuffer lb);\\n\", \"repo_level\" : \"\" }", "class_name": "StringSerializer", "code": "public static LinkedBuffer writeUTF8(final CharSequence str,final WriteSession session,final LinkedBuffer lb){\n final int len=str.length();\n if (len == 0) return lb;\n return lb.offset + len > lb.buffer.length ? writeUTF8(str,0,len,lb.buffer,lb.offset,lb.buffer.length,session,lb) : writeUTF8(str,0,len,session,lb);\n}\n", "docstring": "/** \n * Writes the utf8-encoded bytes from the string into the {@link LinkedBuffer}.\n */\n", "end_lineno": "739", "file_content": "package io.protostuff;\r\n\r\nimport java.io.UTFDataFormatException;\r\nimport java.io.UnsupportedEncodingException;\r\n\r\nimport static java.lang.Character.MIN_HIGH_SURROGATE;\r\nimport static java.lang.Character.MIN_LOW_SURROGATE;\r\nimport static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT;\r\n\r\n/**\r\n * UTF-8 String serialization\r\n *\r\n * @author David Yu\r\n * @created Feb 4, 2010\r\n */\r\npublic final class StringSerializer\r\n{\r\n\r\n private StringSerializer()\r\n {\r\n }\r\n\r\n /**\r\n * From {@link java.lang.Integer#toString(int)}\r\n */\r\n static final int[] sizeTable = new int[] {\r\n 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE\r\n };\r\n\r\n static final char[] DigitTens = {\r\n '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',\r\n '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',\r\n '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',\r\n '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',\r\n '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',\r\n '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',\r\n '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',\r\n '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',\r\n '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',\r\n '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',\r\n };\r\n\r\n static final char[] DigitOnes = {\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\r\n };\r\n\r\n static final char[] digits = {\r\n '0', '1', '2', '3', '4', '5',\r\n '6', '7', '8', '9', 'a', 'b',\r\n 'c', 'd', 'e', 'f', 'g', 'h',\r\n 'i', 'j', 'k', 'l', 'm', 'n',\r\n 'o', 'p', 'q', 'r', 's', 't',\r\n 'u', 'v', 'w', 'x', 'y', 'z'\r\n };\r\n\r\n static final byte[] INT_MIN_VALUE = new byte[] {\r\n (byte) '-',\r\n (byte) '2',\r\n (byte) '1', (byte) '4', (byte) '7',\r\n (byte) '4', (byte) '8', (byte) '3',\r\n (byte) '6', (byte) '4', (byte) '8'\r\n };\r\n\r\n static final byte[] LONG_MIN_VALUE = new byte[] {\r\n (byte) '-',\r\n (byte) '9',\r\n (byte) '2', (byte) '2', (byte) '3',\r\n (byte) '3', (byte) '7', (byte) '2',\r\n (byte) '0', (byte) '3', (byte) '6',\r\n (byte) '8', (byte) '5', (byte) '4',\r\n (byte) '7', (byte) '7', (byte) '5',\r\n (byte) '8', (byte) '0', (byte) '8'\r\n };\r\n\r\n static final int TWO_BYTE_LOWER_LIMIT = 1 << 7;\r\n\r\n static final int ONE_BYTE_EXCLUSIVE = TWO_BYTE_LOWER_LIMIT / 3 + 1;\r\n\r\n static final int THREE_BYTE_LOWER_LIMIT = 1 << 14;\r\n\r\n static final int TWO_BYTE_EXCLUSIVE = THREE_BYTE_LOWER_LIMIT / 3 + 1;\r\n\r\n static final int FOUR_BYTE_LOWER_LIMIT = 1 << 21;\r\n\r\n static final int THREE_BYTE_EXCLUSIVE = FOUR_BYTE_LOWER_LIMIT / 3 + 1;\r\n\r\n static final int FIVE_BYTE_LOWER_LIMIT = 1 << 28;\r\n\r\n static final int FOUR_BYTE_EXCLUSIVE = FIVE_BYTE_LOWER_LIMIT / 3 + 1;\r\n\r\n static void putBytesFromInt(int i, final int offset, final int size, final byte[] buf)\r\n {\r\n int q, r;\r\n int charPos = offset + size;\r\n char sign = 0;\r\n\r\n if (i < 0)\r\n {\r\n sign = '-';\r\n i = -i;\r\n }\r\n\r\n // Generate two digits per iteration\r\n while (i >= 65536)\r\n {\r\n q = i / 100;\r\n // really: r = i - (q * 100);\r\n r = i - ((q << 6) + (q << 5) + (q << 2));\r\n i = q;\r\n buf[--charPos] = (byte) DigitOnes[r];\r\n buf[--charPos] = (byte) DigitTens[r];\r\n }\r\n\r\n // Fall thru to fast mode for smaller numbers\r\n // assert(i <= 65536, i);\r\n for (;;)\r\n {\r\n q = (i * 52429) >>> (16 + 3);\r\n r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...\r\n buf[--charPos] = (byte) digits[r];\r\n i = q;\r\n if (i == 0)\r\n break;\r\n }\r\n if (sign != 0)\r\n {\r\n buf[--charPos] = (byte) sign;\r\n }\r\n }\r\n\r\n static void putBytesFromLong(long i, final int offset, int size, final byte[] buf)\r\n {\r\n long q;\r\n int r;\r\n int charPos = offset + size;\r\n char sign = 0;\r\n\r\n if (i < 0)\r\n {\r\n sign = '-';\r\n i = -i;\r\n }\r\n\r\n // Get 2 digits/iteration using longs until quotient fits into an int\r\n while (i > Integer.MAX_VALUE)\r\n {\r\n q = i / 100;\r\n // really: r = i - (q * 100);\r\n r = (int) (i - ((q << 6) + (q << 5) + (q << 2)));\r\n i = q;\r\n buf[--charPos] = (byte) DigitOnes[r];\r\n buf[--charPos] = (byte) DigitTens[r];\r\n }\r\n\r\n // Get 2 digits/iteration using ints\r\n int q2;\r\n int i2 = (int) i;\r\n while (i2 >= 65536)\r\n {\r\n q2 = i2 / 100;\r\n // really: r = i2 - (q * 100);\r\n r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2));\r\n i2 = q2;\r\n buf[--charPos] = (byte) DigitOnes[r];\r\n buf[--charPos] = (byte) DigitTens[r];\r\n }\r\n\r\n // Fall thru to fast mode for smaller numbers\r\n // assert(i2 <= 65536, i2);\r\n for (;;)\r\n {\r\n q2 = (i2 * 52429) >>> (16 + 3);\r\n r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...\r\n buf[--charPos] = (byte) digits[r];\r\n i2 = q2;\r\n if (i2 == 0)\r\n break;\r\n }\r\n if (sign != 0)\r\n {\r\n buf[--charPos] = (byte) sign;\r\n }\r\n }\r\n\r\n // Requires positive x\r\n static int stringSize(int x)\r\n {\r\n for (int i = 0;; i++)\r\n {\r\n if (x <= sizeTable[i])\r\n return i + 1;\r\n }\r\n }\r\n\r\n // Requires positive x\r\n static int stringSize(long x)\r\n {\r\n long p = 10;\r\n for (int i = 1; i < 19; i++)\r\n {\r\n if (x < p)\r\n return i;\r\n p = 10 * p;\r\n }\r\n return 19;\r\n }\r\n\r\n /**\r\n * Writes the stringified int into the {@link LinkedBuffer}.\r\n */\r\n public static LinkedBuffer writeInt(final int value, final WriteSession session,\r\n LinkedBuffer lb)\r\n {\r\n if (value == Integer.MIN_VALUE)\r\n {\r\n final int valueLen = INT_MIN_VALUE.length;\r\n if (lb.offset + valueLen > lb.buffer.length)\r\n {\r\n // not enough size\r\n lb = new LinkedBuffer(session.nextBufferSize, lb);\r\n }\r\n\r\n System.arraycopy(INT_MIN_VALUE, 0, lb.buffer, lb.offset, valueLen);\r\n\r\n lb.offset += valueLen;\r\n session.size += valueLen;\r\n\r\n return lb;\r\n }\r\n\r\n final int size = (value < 0) ? stringSize(-value) + 1 : stringSize(value);\r\n\r\n if (lb.offset + size > lb.buffer.length)\r\n {\r\n // not enough size\r\n lb = new LinkedBuffer(session.nextBufferSize, lb);\r\n }\r\n\r\n putBytesFromInt(value, lb.offset, size, lb.buffer);\r\n\r\n lb.offset += size;\r\n session.size += size;\r\n\r\n return lb;\r\n }\r\n\r\n /**\r\n * Writes the stringified long into the {@link LinkedBuffer}.\r\n */\r\n public static LinkedBuffer writeLong(final long value, final WriteSession session,\r\n LinkedBuffer lb)\r\n {\r\n if (value == Long.MIN_VALUE)\r\n {\r\n final int valueLen = LONG_MIN_VALUE.length;\r\n if (lb.offset + valueLen > lb.buffer.length)\r\n {\r\n // TODO space efficiency (slower path)\r\n // not enough size\r\n lb = new LinkedBuffer(session.nextBufferSize, lb);\r\n }\r\n\r\n System.arraycopy(LONG_MIN_VALUE, 0, lb.buffer, lb.offset, valueLen);\r\n\r\n lb.offset += valueLen;\r\n session.size += valueLen;\r\n\r\n return lb;\r\n }\r\n\r\n final int size = (value < 0) ? stringSize(-value) + 1 : stringSize(value);\r\n\r\n if (lb.offset + size > lb.buffer.length)\r\n {\r\n // TODO space efficiency (slower path)\r\n // not enough size\r\n lb = new LinkedBuffer(session.nextBufferSize, lb);\r\n }\r\n\r\n putBytesFromLong(value, lb.offset, size, lb.buffer);\r\n\r\n lb.offset += size;\r\n session.size += size;\r\n\r\n return lb;\r\n }\r\n\r\n /**\r\n * Writes the stringified float into the {@link LinkedBuffer}. TODO - skip string conversion and write directly to\r\n * buffer\r\n */\r\n public static LinkedBuffer writeFloat(final float value, final WriteSession session,\r\n final LinkedBuffer lb)\r\n {\r\n return writeAscii(Float.toString(value), session, lb);\r\n }\r\n\r\n /**\r\n * Writes the stringified double into the {@link LinkedBuffer}. TODO - skip string conversion and write directly to\r\n * buffer\r\n */\r\n public static LinkedBuffer writeDouble(final double value, final WriteSession session,\r\n final LinkedBuffer lb)\r\n {\r\n return writeAscii(Double.toString(value), session, lb);\r\n }\r\n\r\n /**\r\n * Computes the size of the utf8 string beginning at the specified {@code index} with the specified {@code length}.\r\n */\r\n public static int computeUTF8Size(final CharSequence str, final int index, final int len)\r\n {\r\n int size = len;\r\n for (int i = index; i < len; i++)\r\n {\r\n final char c = str.charAt(i);\r\n if (c < 0x0080)\r\n continue;\r\n\r\n if (c < 0x0800)\r\n size++;\r\n else\r\n size += 2;\r\n }\r\n return size;\r\n }\r\n\r\n /**\r\n * Slow path. It checks the limit before every write. Shared with StreamedStringSerializer.\r\n */\r\n static LinkedBuffer writeUTF8(final CharSequence str, int i, final int len,\r\n byte[] buffer, int offset, int limit,\r\n final WriteSession session, LinkedBuffer lb)\r\n {\r\n for (char c = 0;; c = 0)\r\n {\r\n while (i != len && offset != limit && (c = str.charAt(i++)) < 0x0080)\r\n buffer[offset++] = (byte) c;\r\n\r\n if (i == len && c < 0x0080)\r\n {\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n return lb;\r\n }\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n\r\n continue;\r\n }\r\n\r\n if (c < 0x0800)\r\n {\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0xC0 | ((c >> 6) & 0x1F));\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0x80 | ((c >> 0) & 0x3F));\r\n }\r\n else if (Character.isHighSurrogate((char) c) && i < len && Character.isLowSurrogate((char) str.charAt(i)))\r\n {\r\n // We have a surrogate pair, so use the 4-byte encoding.\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n int codePoint = Character.toCodePoint((char) c, (char) str.charAt(i));\r\n\r\n buffer[offset++] = (byte) (0xF0 | ((codePoint >> 18) & 0x07));\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0x80 | ((codePoint >> 12) & 0x3F));\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0x80 | ((codePoint >> 6) & 0x3F));\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0x80 | ((codePoint >> 0) & 0x3F));\r\n\r\n i++;\r\n }\r\n else\r\n {\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0xE0 | ((c >> 12) & 0x0F));\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0x80 | ((c >> 6) & 0x3F));\r\n\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n\r\n if (lb.next == null)\r\n {\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n else\r\n {\r\n // use the existing buffer from previous utf8 write.\r\n // this condition happens only on streaming mode\r\n lb = lb.next;\r\n // reset\r\n lb.offset = offset = lb.start;\r\n buffer = lb.buffer;\r\n limit = buffer.length;\r\n }\r\n }\r\n\r\n buffer[offset++] = (byte) (0x80 | ((c >> 0) & 0x3F));\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Fast path. The {@link LinkedBuffer}'s capacity is >= string length.\r\n */\r\n static LinkedBuffer writeUTF8(final CharSequence str, int i, final int len,\r\n final WriteSession session, final LinkedBuffer lb)\r\n {\r\n final byte[] buffer = lb.buffer;\r\n for (int c = 0, offset = lb.offset, adjustableLimit = offset + len;; c = 0)\r\n {\r\n while (i != len && (c = str.charAt(i++)) < 0x0080)\r\n buffer[offset++] = (byte) c;\r\n\r\n if (i == len && c < 0x0080)\r\n {\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n return lb;\r\n }\r\n\r\n if (c < 0x0800)\r\n {\r\n if (++adjustableLimit > buffer.length)\r\n {\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n return writeUTF8(str, i - 1, len, buffer, offset, buffer.length, session, lb);\r\n }\r\n\r\n buffer[offset++] = (byte) (0xC0 | ((c >> 6) & 0x1F));\r\n buffer[offset++] = (byte) (0x80 | ((c >> 0) & 0x3F));\r\n }\r\n else if (Character.isHighSurrogate((char) c) && i < len && Character.isLowSurrogate((char) str.charAt(i)))\r\n {\r\n // We have a surrogate pair, so use the 4-byte encoding.\r\n adjustableLimit += 3;\r\n if (adjustableLimit > buffer.length)\r\n {\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n return writeUTF8(str, i - 1, len, buffer, offset, buffer.length, session, lb);\r\n }\r\n\r\n int codePoint = Character.toCodePoint((char) c, (char) str.charAt(i));\r\n buffer[offset++] = (byte) (0xF0 | ((codePoint >> 18) & 0x07));\r\n buffer[offset++] = (byte) (0x80 | ((codePoint >> 12) & 0x3F));\r\n buffer[offset++] = (byte) (0x80 | ((codePoint >> 6) & 0x3F));\r\n buffer[offset++] = (byte) (0x80 | ((codePoint >> 0) & 0x3F));\r\n\r\n i++;\r\n }\r\n else\r\n {\r\n adjustableLimit += 2;\r\n if (adjustableLimit > buffer.length)\r\n {\r\n session.size += (offset - lb.offset);\r\n lb.offset = offset;\r\n return writeUTF8(str, i - 1, len, buffer, offset, buffer.length, session, lb);\r\n }\r\n\r\n buffer[offset++] = (byte) (0xE0 | ((c >> 12) & 0x0F));\r\n buffer[offset++] = (byte) (0x80 | ((c >> 6) & 0x3F));\r\n buffer[offset++] = (byte) (0x80 | ((c >> 0) & 0x3F));\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Writes the utf8-encoded bytes from the string into the {@link LinkedBuffer}.\r\n */\r\n public static LinkedBuffer writeUTF8(final CharSequence str, final WriteSession session,\r\n final LinkedBuffer lb)\r\n {\r\n final int len = str.length();\r\n if (len == 0)\r\n return lb;\r\n\r\n return lb.offset + len > lb.buffer.length ? writeUTF8(str, 0, len, lb.buffer, lb.offset,\r\n lb.buffer.length, session, lb) : writeUTF8(str, 0, len, session, lb);\r\n }\r\n\r\n /**\r\n * Writes the ascii bytes from the string into the {@link LinkedBuffer}. It is the responsibility of the caller to\r\n * know in advance that the string is 100% ascii. E.g if you convert a double/float to a string, you are sure it\r\n * only contains ascii chars.\r\n */\r\n public static LinkedBuffer writeAscii(final CharSequence str, final WriteSession session,\r\n LinkedBuffer lb)\r\n {\r\n final int len = str.length();\r\n if (len == 0)\r\n return lb;\r\n\r\n byte[] buffer = lb.buffer;\r\n int offset = lb.offset, limit = lb.buffer.length;\r\n\r\n // actual size\r\n session.size += len;\r\n\r\n if (offset + len > limit)\r\n {\r\n // slow path\r\n for (int i = 0; i < len; i++)\r\n {\r\n if (offset == limit)\r\n {\r\n // we are done with this LinkedBuffer\r\n lb.offset = offset;\r\n // reset\r\n offset = 0;\r\n limit = session.nextBufferSize;\r\n buffer = new byte[limit];\r\n // grow\r\n lb = new LinkedBuffer(buffer, 0, lb);\r\n }\r\n buffer[offset++] = (byte) str.charAt(i);\r\n }\r\n }\r\n else\r\n {\r\n // fast path\r\n for (int i = 0; i < len; i++)\r\n buffer[offset++] = (byte) str.charAt(i);\r\n }\r\n\r\n lb.offset = offset;\r\n\r\n return lb;\r\n }\r\n\r\n static void writeFixed2ByteInt(final int value, final byte[] buffer, int offset,\r\n final boolean littleEndian)\r\n {\r\n if (littleEndian)\r\n {\r\n buffer[offset++] = (byte) value;\r\n buffer[offset] = (byte) ((value >>> 8) & 0xFF);\r\n }\r\n else\r\n {\r\n buffer[offset++] = (byte) ((value >>> 8) & 0xFF);\r\n buffer[offset] = (byte) value;\r\n }\r\n }\r\n\r\n /**\r\n * The length of the utf8 bytes is written first (big endian) before the string - which is fixed 2-bytes. Same\r\n * behavior as {@link java.io.DataOutputStream#writeUTF(String)}.\r\n */\r\n public static LinkedBuffer writeUTF8FixedDelimited(final CharSequence str,\r\n final WriteSession session, LinkedBuffer lb)\r\n {\r\n return writeUTF8FixedDelimited(str, false, session, lb);\r\n }\r\n\r\n /**\r\n * The length of the utf8 bytes is written first before the string - which is fixed 2-bytes.\r\n */\r\n public static LinkedBuffer writeUTF8FixedDelimited(final CharSequence str,\r\n final boolean littleEndian, final WriteSession session, LinkedBuffer lb)\r\n {\r\n final int lastSize = session.size, len = str.length(), withIntOffset = lb.offset + 2;\r\n\r\n if (withIntOffset > lb.buffer.length)\r\n {\r\n // not enough space for int (2 bytes).\r\n // create a new buffer.\r\n lb = new LinkedBuffer(len + 2 > session.nextBufferSize ? len + 2 : session.nextBufferSize,\r\n lb);\r\n\r\n lb.offset = 2;\r\n\r\n if (len == 0)\r\n {\r\n writeFixed2ByteInt(0, lb.buffer, 0, littleEndian);\r\n // update size\r\n session.size += 2;\r\n return lb;\r\n }\r\n\r\n // fast path\r\n final LinkedBuffer rb = writeUTF8(str, 0, len, session, lb);\r\n\r\n writeFixed2ByteInt((session.size - lastSize), lb.buffer, 0, littleEndian);\r\n\r\n // update size\r\n session.size += 2;\r\n\r\n return rb;\r\n }\r\n\r\n if (len == 0)\r\n {\r\n writeFixed2ByteInt(0, lb.buffer, lb.offset, littleEndian);\r\n lb.offset = withIntOffset;\r\n // update size\r\n session.size += 2;\r\n return lb;\r\n }\r\n\r\n if (withIntOffset + len > lb.buffer.length)\r\n {\r\n // not enough space for the string.\r\n lb.offset = withIntOffset;\r\n\r\n // slow path\r\n final LinkedBuffer rb = writeUTF8(str, 0, len,\r\n lb.buffer, withIntOffset, lb.buffer.length, session, lb);\r\n\r\n writeFixed2ByteInt((session.size - lastSize), lb.buffer,\r\n withIntOffset - 2, littleEndian);\r\n\r\n // update size\r\n session.size += 2;\r\n\r\n return rb;\r\n }\r\n\r\n // everything fits\r\n lb.offset = withIntOffset;\r\n\r\n final LinkedBuffer rb = writeUTF8(str, 0, len, session, lb);\r\n\r\n writeFixed2ByteInt((session.size - lastSize), lb.buffer,\r\n withIntOffset - 2, littleEndian);\r\n\r\n // update size\r\n session.size += 2;\r\n\r\n return rb;\r\n }\r\n\r\n private static LinkedBuffer writeUTF8OneByteDelimited(final CharSequence str, final int index,\r\n final int len, final WriteSession session, LinkedBuffer lb)\r\n {\r\n final int lastSize = session.size;\r\n\r\n if (lb.offset == lb.buffer.length)\r\n {\r\n // create a new buffer.\r\n lb = new LinkedBuffer(len + 1 > session.nextBufferSize ? len + 1 : session.nextBufferSize,\r\n lb);\r\n\r\n lb.offset = 1;\r\n\r\n // fast path\r\n final LinkedBuffer rb = writeUTF8(str, index, len, session, lb);\r\n\r\n lb.buffer[0] = (byte) (session.size - lastSize);\r\n\r\n // update size\r\n session.size++;\r\n\r\n return rb;\r\n }\r\n\r\n final int withIntOffset = lb.offset + 1;\r\n if (withIntOffset + len > lb.buffer.length)\r\n {\r\n // not enough space for the string.\r\n lb.offset = withIntOffset;\r\n\r\n final byte[] buffer = lb.buffer;\r\n\r\n // slow path\r\n final LinkedBuffer rb = writeUTF8(str, index, len, buffer, withIntOffset, buffer.length,\r\n session, lb);\r\n\r\n buffer[withIntOffset - 1] = (byte) (session.size - lastSize);\r\n\r\n // update size\r\n session.size++;\r\n\r\n return rb;\r\n }\r\n\r\n // everything fits\r\n lb.offset = withIntOffset;\r\n\r\n final LinkedBuffer rb = writeUTF8(str, index, len, session, lb);\r\n\r\n lb.buffer[withIntOffset - 1] = (byte) (session.size - lastSize);\r\n\r\n // update size\r\n session.size++;\r\n\r\n return rb;\r\n }\r\n\r\n private static LinkedBuffer writeUTF8VarDelimited(final CharSequence str, final int index,\r\n final int len, final int lowerLimit, int expectedSize,\r\n final WriteSession session, LinkedBuffer lb)\r\n {\r\n int lastSize = session.size, offset = lb.offset, withIntOffset = offset + expectedSize;\r\n\r\n if (withIntOffset > lb.buffer.length)\r\n {\r\n // not enough space for the varint.\r\n // create a new buffer.\r\n lb = new LinkedBuffer(len + expectedSize > session.nextBufferSize ? len + expectedSize\r\n : session.nextBufferSize,\r\n lb);\r\n offset = lb.start;\r\n lb.offset = withIntOffset = offset + expectedSize;\r\n\r\n // fast path\r\n final LinkedBuffer rb = writeUTF8(str, index, len, session, lb);\r\n\r\n int size = session.size - lastSize;\r\n\r\n if (size < lowerLimit)\r\n {\r\n // move one space to the left since the varint is 1-byte smaller\r\n System.arraycopy(lb.buffer, withIntOffset, lb.buffer, withIntOffset - 1,\r\n lb.offset - withIntOffset);\r\n\r\n expectedSize--;\r\n lb.offset--;\r\n }\r\n\r\n // update size\r\n session.size += expectedSize;\r\n\r\n for (; --expectedSize > 0; size >>>= 7)\r\n lb.buffer[offset++] = (byte) ((size & 0x7F) | 0x80);\r\n\r\n lb.buffer[offset] = (byte) (size);\r\n\r\n return rb;\r\n }\r\n\r\n if (withIntOffset + len > lb.buffer.length)\r\n {\r\n // not enough space for the string.\r\n lb.offset = withIntOffset;\r\n\r\n // slow path\r\n final LinkedBuffer rb = writeUTF8(str, index, len,\r\n lb.buffer, withIntOffset, lb.buffer.length, session, lb);\r\n\r\n int size = session.size - lastSize;\r\n\r\n if (size < lowerLimit)\r\n {\r\n // move one space to the left since the varint is 1-byte smaller\r\n System.arraycopy(lb.buffer, withIntOffset, lb.buffer, withIntOffset - 1,\r\n lb.offset - withIntOffset);\r\n\r\n expectedSize--;\r\n lb.offset--;\r\n }\r\n\r\n // update size\r\n session.size += expectedSize;\r\n\r\n for (; --expectedSize > 0; size >>>= 7)\r\n lb.buffer[offset++] = (byte) ((size & 0x7F) | 0x80);\r\n\r\n lb.buffer[offset] = (byte) (size);\r\n\r\n return rb;\r\n }\r\n\r\n // everything fits\r\n lb.offset = withIntOffset;\r\n\r\n final LinkedBuffer rb = writeUTF8(str, index, len, session, lb);\r\n\r\n int size = session.size - lastSize;\r\n\r\n if (size < lowerLimit)\r\n {\r\n // move one space to the left since the varint is 1-byte smaller\r\n System.arraycopy(lb.buffer, withIntOffset, lb.buffer, withIntOffset - 1,\r\n lb.offset - withIntOffset);\r\n\r\n expectedSize--;\r\n lb.offset--;\r\n }\r\n\r\n // update size\r\n session.size += expectedSize;\r\n\r\n for (; --expectedSize > 0; size >>>= 7)\r\n lb.buffer[offset++] = (byte) ((size & 0x7F) | 0x80);\r\n\r\n lb.buffer[offset] = (byte) (size);\r\n\r\n return rb;\r\n }\r\n\r\n /**\r\n * The length of the utf8 bytes is written first before the string - which is a variable int (1 to 5 bytes).\r\n */\r\n public static LinkedBuffer writeUTF8VarDelimited(final CharSequence str, final WriteSession session,\r\n LinkedBuffer lb)\r\n {\r\n final int len = str.length();\r\n if (len == 0)\r\n {\r\n if (lb.offset == lb.buffer.length)\r\n {\r\n // buffer full\r\n lb = new LinkedBuffer(session.nextBufferSize, lb);\r\n }\r\n\r\n // write zero\r\n lb.buffer[lb.offset++] = 0x00;\r\n // update size\r\n session.size++;\r\n return lb;\r\n }\r\n\r\n if (len < ONE_BYTE_EXCLUSIVE)\r\n {\r\n // the varint will be max 1-byte. (even if all chars are non-ascii)\r\n return writeUTF8OneByteDelimited(str, 0, len, session, lb);\r\n }\r\n\r\n if (len < TWO_BYTE_EXCLUSIVE)\r\n {\r\n // the varint will be max 2-bytes and could be 1-byte. (even if all non-ascii)\r\n return writeUTF8VarDelimited(str, 0, len, TWO_BYTE_LOWER_LIMIT, 2,\r\n session, lb);\r\n }\r\n\r\n if (len < THREE_BYTE_EXCLUSIVE)\r\n {\r\n // the varint will be max 3-bytes and could be 2-bytes. (even if all non-ascii)\r\n return writeUTF8VarDelimited(str, 0, len, THREE_BYTE_LOWER_LIMIT, 3,\r\n session, lb);\r\n }\r\n\r\n if (len < FOUR_BYTE_EXCLUSIVE)\r\n {\r\n // the varint will be max 4-bytes and could be 3-bytes. (even if all non-ascii)\r\n return writeUTF8VarDelimited(str, 0, len, FOUR_BYTE_LOWER_LIMIT, 4,\r\n session, lb);\r\n }\r\n\r\n // the varint will be max 5-bytes and could be 4-bytes. (even if all non-ascii)\r\n return writeUTF8VarDelimited(str, 0, len, FIVE_BYTE_LOWER_LIMIT, 5, session, lb);\r\n }\r\n\r\n public static final class STRING\r\n {\r\n static final boolean CESU8_COMPAT = Boolean.getBoolean(\"io.protostuff.cesu8_compat\");\r\n\r\n private STRING()\r\n {\r\n }\r\n\r\n public static String deser(byte[] nonNullValue)\r\n {\r\n return deser(nonNullValue, 0, nonNullValue.length);\r\n }\r\n\r\n public static String deser(byte[] nonNullValue, int offset, int len)\r\n {\r\n final String result;\r\n try\r\n {\r\n // Try to use the built in deserialization first, since we expect\r\n // that the most likely case is a valid UTF-8 encoded byte array.\r\n // Additionally, the built in serialization method has one less\r\n // char[] copy than readUTF.\r\n //\r\n // If, however, there are invalid/malformed characters, i.e. 3-byte\r\n // surrogates / 3-byte surrogate pairs, we should fall back to the\r\n // readUTF method as it should be able to properly handle 3-byte surrogates\r\n // (and therefore 6-byte surrogate pairs) in Java 8+.\r\n //\r\n // While Protostuff and many other applications, still use 3-byte surrogates\r\n // / 6-byte surrogate pairs, the standard 'forbids' their use, and Java 8\r\n // has started to enforce the standard, resulting in 'corrupted' data in\r\n // strings when decoding using new String(nonNullValue, \"UTF-8\");\r\n //\r\n // While the readUTF should be able to handle both Standard Unicode\r\n // (i.e. new String().getBytes(\"UTF-8\") and the Legacy Unicode\r\n // (with 3-byte surrogates, used in CESU-8 and Modified UTF-8),\r\n // we don't want to introduce an unexpected loss of data due to\r\n // some unforseen bug. As a result, a fallback mechanism is in\r\n // place such that the worst case scenario results in the previous\r\n // implementation's behaviour.\r\n //\r\n // For the Java 8 change, see: https://bugs.openjdk.java.net/browse/JDK-7096080\r\n\r\n result = new String(nonNullValue, offset, len, \"UTF-8\");\r\n\r\n // Check if we should scan the string to make sure there were no\r\n // corrupt characters caused by 3-byte / 6-byte surrogate pairs.\r\n //\r\n // In general, this *should* only be required for systems reading\r\n // data stored using legacy protostuff. Moving forward, the data\r\n // should be readable by new String(\"UTF-8\"), so the scan is unnecessary.\r\n if (CESU8_COMPAT && result.indexOf(0xfffd) != -1)\r\n {\r\n // If it contains the REPLACEMENT character, then there's a strong\r\n // possibility of it containing 3-byte surrogates / 6-byte surrogate\r\n // pairs, and we should try decoding using readUTF to handle it.\r\n try\r\n {\r\n return readUTF(nonNullValue, offset, len);\r\n }\r\n catch (UTFDataFormatException e)\r\n {\r\n // Unexpected, but most systems previously using\r\n // Protostuff don't expect error to occur from\r\n // String deserialization, so we use this just in case.\r\n return result;\r\n }\r\n }\r\n }\r\n catch (UnsupportedEncodingException e)\r\n {\r\n throw new RuntimeException(e);\r\n }\r\n\r\n return result;\r\n }\r\n\r\n /**\r\n * Deserialize using readUTF only.\r\n *\r\n * @param nonNullValue\r\n * @return\r\n */\r\n static String deserCustomOnly(byte[] nonNullValue)\r\n {\r\n try\r\n {\r\n // Same behaviour as deser(), but does NOT\r\n // fall back to old implementation.\r\n return readUTF(nonNullValue, 0, nonNullValue.length);\r\n }\r\n catch (UTFDataFormatException e)\r\n {\r\n throw new RuntimeException(e);\r\n }\r\n }\r\n\r\n public static byte[] ser(String nonNullValue)\r\n {\r\n try\r\n {\r\n return nonNullValue.getBytes(\"UTF-8\");\r\n }\r\n catch (UnsupportedEncodingException e)\r\n {\r\n throw new RuntimeException(e);\r\n }\r\n }\r\n\r\n /**\r\n * Reads the string from a byte[] using that was encoded a using Modified UTF-8 format. Additionally supports\r\n * 4-byte surrogates, de-serializing them as surrogate pairs.\r\n *\r\n * See: http://en.wikipedia.org/wiki/UTF-8#Description for encoding details.\r\n */\r\n private static String readUTF(byte[] buffer, int offset, int len) throws UTFDataFormatException\r\n {\r\n char[] charArray = new char[len];\r\n\r\n int i = 0;\r\n int c = 0;\r\n\r\n // Optimizaiton: Assume that the characters are all 7-bits encodable\r\n // (which is most likely the standard case).\r\n // If they're not, break out and take the 'slow' path.\r\n for (; i < len; i++)\r\n {\r\n int ch = (int) buffer[offset + i] & 0xff;\r\n\r\n // If it's not 7-bit character, break out\r\n if (ch > 127)\r\n break;\r\n\r\n charArray[c++] = (char) ch;\r\n }\r\n\r\n // 'Slow' path\r\n while (i < len)\r\n {\r\n int ch = (int) buffer[offset + i] & 0xff;\r\n\r\n // Determine how to decode based on 'bits of code point'\r\n // See: http://en.wikipedia.org/wiki/UTF-8#Description\r\n int upperBits = ch >> 4;\r\n\r\n if (upperBits <= 7)\r\n {\r\n // 1-byte: 0xxxxxxx\r\n charArray[c++] = (char) ch;\r\n i++;\r\n }\r\n else if (upperBits == 0x0C || upperBits == 0x0D)\r\n {\r\n // 2-byte: 110xxxxx 10xxxxxx\r\n i += 2;\r\n\r\n if (i > len)\r\n throw new UTFDataFormatException(\"Malformed input: Partial character at end\");\r\n\r\n int ch2 = (int) buffer[offset + i - 1];\r\n\r\n // Make sure the second byte has the form 10xxxxxx\r\n if ((ch2 & 0xC0) != 0x80)\r\n throw new UTFDataFormatException(\"Malformed input around byte \" + i);\r\n\r\n charArray[c++] = (char) (((ch & 0x1F) << 6) | (ch2 & 0x3F));\r\n }\r\n else if (upperBits == 0xE)\r\n {\r\n // 3-byte: 1110xxxx 10xxxxxx 10xxxxxx\r\n i += 3;\r\n\r\n if (i > len)\r\n throw new UTFDataFormatException(\"Malformed input: Partial character at end\");\r\n\r\n int ch2 = (int) buffer[offset + i - 2];\r\n int ch3 = (int) buffer[offset + i - 1];\r\n\r\n // Check the 10xxxxxx 10xxxxxx of second two bytes\r\n if (((ch2 & 0xC0) != 0x80) || ((ch3 & 0xC0) != 0x80))\r\n throw new UTFDataFormatException(\"Malformed input around byte \" + (i - 1));\r\n\r\n charArray[c++] = (char) (((ch & 0x0F) << 12) | ((ch2 & 0x3F) << 6) | (ch3 & 0x3F));\r\n }\r\n else\r\n {\r\n // 4-byte: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\r\n upperBits = ch >> 3;\r\n if (upperBits == 0x1E)\r\n {\r\n // Because we're now in the UTF-32 bit range, we must\r\n // break it down into the UTF-16 surrogate pairs for\r\n // Java's String class (which is UTF-16).\r\n\r\n i += 4;\r\n if (i > len)\r\n throw new UTFDataFormatException(\"Malformed input: Partial character at end\");\r\n\r\n int ch2 = (int) buffer[offset + i - 3];\r\n int ch3 = (int) buffer[offset + i - 2];\r\n int ch4 = (int) buffer[offset + i - 1];\r\n\r\n int value =\r\n ((ch & 0x07) << 18) |\r\n ((ch2 & 0x3F) << 12) |\r\n ((ch3 & 0x3F) << 6) |\r\n ((ch4 & 0x3F));\r\n\r\n charArray[c++] = highSurrogate(value);\r\n charArray[c++] = lowSurrogate(value);\r\n }\r\n else\r\n {\r\n // Anything above\r\n throw new UTFDataFormatException(\"Malformed input at byte \" + i);\r\n }\r\n }\r\n }\r\n\r\n return new String(charArray, 0, c);\r\n }\r\n }\r\n\r\n\r\n public static char highSurrogate(int codePoint) {\r\n return (char) ((codePoint >>> 10)\r\n + (MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)));\r\n }\r\n\r\n public static char lowSurrogate(int codePoint) {\r\n return (char) ((codePoint & 0x3ff) + MIN_LOW_SURROGATE);\r\n }\r\n\r\n}\r\n", "file_name": "StringSerializer.java", "human_label": "Write the utf8-encoded bytes from the string into the LinkedBuffer.", "level": "project_runnable", "lineno": "727", "name": "writeUTF8", "oracle_context": "{ \"apis\" : \"[length]\", \"classes\" : \"[lb.buffer]\", \"vars\" : \"[offset, length, buffer]\" }", "package": "io.protostuff", "project": "protostuff-master" }, { "_id": "6367675c1a6d9265ec01805b", "all_context": "{ \"class_level\" : \"import org.jheaps.*;\\nimport org.jheaps.tree.*;\\nBlossomVTree[] head;\\nBlossomVTreeEdge[] prev;\\nBlossomVTreeEdge[] next;\\nMergeableAddressableHeap plusPlusEdges;\\nMergeableAddressableHeap plusMinusEdges0;\\nMergeableAddressableHeap plusMinusEdges1;\\nBlossomVTreeEdge();\\ntoString();\\naddToCurrentMinusPlusHeap(BlossomVEdge edge,int direction);\\naddToCurrentPlusMinusHeap(BlossomVEdge edge,int direction);\\naddPlusPlusEdge(BlossomVEdge edge);\\nremoveFromCurrentMinusPlusHeap(BlossomVEdge edge);\\nremoveFromCurrentPlusMinusHeap(BlossomVEdge edge);\\nremoveFromPlusPlusHeap(BlossomVEdge edge);\\ngetCurrentMinusPlusHeap(int currentDir);\\ngetCurrentPlusMinusHeap(int currentDir);\\n\", \"repo_level\" : \"\" }", "class_name": "BlossomVTreeEdge", "code": "public void removeFromTreeEdgeList(){\n for (int dir=0; dir < 2; dir++) {\n if (prev[dir] != null) {\n prev[dir].next[dir]=next[dir];\n }\n else {\n head[1 - dir].first[dir]=next[dir];\n }\n if (next[dir] != null) {\n next[dir].prev[dir]=prev[dir];\n }\n }\n head[0]=head[1]=null;\n}\n", "docstring": "/** \n * Removes this edge from both doubly linked lists of tree edges.\n */\n", "end_lineno": "117", "file_content": "/*\n * (C) Copyright 2018-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.matching.blossom.v5;\n\nimport org.jheaps.*;\nimport org.jheaps.tree.*;\n\n/**\n * This class is a data structure for Kolmogorov's Blossom V algorithm.\n *

\n * Is used to maintain an auxiliary graph whose nodes correspond to alternating trees in the Blossom\n * V algorithm. Let's denote the current tree $T$ and some other tree $T'$. Every tree edge contains\n * three heaps:
\n *

    \n *
  1. a heap of (+, +) cross-tree edges. This heap contains all edges between two \"+\" nodes where\n * one node belongs to tree $T$ and another to $T'$. The (+, +) cross-tree edges are used to augment\n * the matching.
  2. \n *
  3. a heap of (+, -) cross-tree edges
  4. \n *
  5. a heap of (-, +) cross-tree edges
  6. \n *
\n * Note: from the tree edge perspective there is no difference between a heap of (+, -) and\n * (-, +) cross-tree edges. That's why we distinguish these heaps by the direction of the edge. Here\n * the direction is considered with respect to the trees $T$ and $T'$ based upon the notation\n * introduced above.\n *

\n * Every tree edge is directed from one tree to another and every tree edge belongs to the two\n * doubly linked lists of tree edges. The presence of a tree edge in these lists in maintained by\n * the two-element arrays {@link BlossomVTreeEdge#prev} and {@link BlossomVTreeEdge#next}. For one\n * tree the edge is an outgoing tree edge; for the other, an incoming. In the first case it belongs\n * to the {@code tree.first[0]} linked list; in the second, to the {@code tree.first[1]} linked\n * list.\n *

\n * Let {@code tree} be a tail of the edge, and {@code oppositeTree} a head of the edge. Then\n * {@code edge.head[0] == oppositeTree} and {@code edge.head[1] == tree}.\n *\n * @author Timofey Chudakov\n * @see KolmogorovWeightedPerfectMatching\n * @see BlossomVTree\n * @see BlossomVEdge\n */\nclass BlossomVTreeEdge\n{\n /**\n * Two-element array of trees this edge is incident to.\n */\n BlossomVTree[] head;\n /**\n * A two-element array of references to the previous elements in the circular doubly linked\n * lists of tree edges. The lists are circular with one exception: the lastElement.next[dir] ==\n * null. Each list belongs to one of the endpoints of this edge.\n */\n BlossomVTreeEdge[] prev;\n /**\n * A two-element array of references to the next elements in the circular doubly linked lists of\n * tree edges. The lists are circular with one exception: the lastElementInTheList.next[dir] ==\n * null. Each list belongs to one of the endpoints of this edge.\n */\n BlossomVTreeEdge[] next;\n /**\n * A heap of (+, +) cross-tree edges\n */\n MergeableAddressableHeap plusPlusEdges;\n /**\n * A heap of (-, +) cross-tree edges\n */\n MergeableAddressableHeap plusMinusEdges0;\n /**\n * A heap of (+, -) cross-tree edges\n */\n MergeableAddressableHeap plusMinusEdges1;\n\n /**\n * Constructs a new tree edge by initializing arrays and heaps\n */\n public BlossomVTreeEdge()\n {\n this.head = new BlossomVTree[2];\n this.prev = new BlossomVTreeEdge[2];\n this.next = new BlossomVTreeEdge[2];\n this.plusPlusEdges = new PairingHeap<>();\n this.plusMinusEdges0 = new PairingHeap<>();\n this.plusMinusEdges1 = new PairingHeap<>();\n }\n\n /**\n * Removes this edge from both doubly linked lists of tree edges.\n */\n public void removeFromTreeEdgeList()\n {\n for (int dir = 0; dir < 2; dir++) {\n if (prev[dir] != null) {\n prev[dir].next[dir] = next[dir];\n } else {\n // this is the first edge in this direction\n head[1 - dir].first[dir] = next[dir];\n }\n if (next[dir] != null) {\n next[dir].prev[dir] = prev[dir];\n }\n }\n head[0] = head[1] = null;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n return \"BlossomVTreeEdge (\" + head[0].id + \":\" + head[1].id + \")\";\n }\n\n /**\n * Adds {@code edge} to the heap of (-, +) cross-tree edges. As explained in the class\n * description, this method chooses {@link BlossomVTreeEdge#plusMinusEdges0} or\n * {@link BlossomVTreeEdge#plusMinusEdges1} based upon the {@code direction}. The key is\n * edge.slack\n *\n * @param edge an edge to add to the current heap of (-, +) cross-tree edges.\n * @param direction direction of this tree edge wrt. current tree and opposite tree\n */\n public void addToCurrentMinusPlusHeap(BlossomVEdge edge, int direction)\n {\n edge.handle = getCurrentMinusPlusHeap(direction).insert(edge.slack, edge);\n }\n\n /**\n * Adds {@code edge} to the heap of (+, -) cross-tree edges. As explained in the class\n * description, this method chooses {@link BlossomVTreeEdge#plusMinusEdges0} or\n * {@link BlossomVTreeEdge#plusMinusEdges1} based upon the {@code direction}. The key is\n * edge.slack\n *\n * @param edge an edge to add to the current heap of (+, -) cross-tree edges.\n * @param direction direction of this tree edge wrt. current tree and opposite tree\n */\n public void addToCurrentPlusMinusHeap(BlossomVEdge edge, int direction)\n {\n edge.handle = getCurrentPlusMinusHeap(direction).insert(edge.slack, edge);\n }\n\n /**\n * Adds {@code edge} to the heap of (+, +) cross-tree edges. The key is edge.slack\n *\n * @param edge an edge to add to the heap of (+, +) cross-tree edges\n */\n public void addPlusPlusEdge(BlossomVEdge edge)\n {\n edge.handle = plusPlusEdges.insert(edge.slack, edge);\n }\n\n /**\n * Removes {@code edge} from the current heap of (-, +) cross-tree edges. As explained in the\n * class description, this method chooses {@link BlossomVTreeEdge#plusMinusEdges0} or\n * {@link BlossomVTreeEdge#plusMinusEdges1} based upon the {@code direction}.\n *\n * @param edge an edge to remove\n */\n public void removeFromCurrentMinusPlusHeap(BlossomVEdge edge)\n {\n edge.handle.delete();\n edge.handle = null;\n }\n\n /**\n * Removes {@code edge} from the current heap of (+, -) cross-tree edges. As explained in the\n * class description, this method chooses {@link BlossomVTreeEdge#plusMinusEdges0} or\n * {@link BlossomVTreeEdge#plusMinusEdges1} based upon the {@code direction}.\n *\n * @param edge an edge to remove\n */\n public void removeFromCurrentPlusMinusHeap(BlossomVEdge edge)\n {\n edge.handle.delete();\n edge.handle = null;\n }\n\n /**\n * Removes {@code edge} from the heap of (+, +) cross-tree edges.\n *\n * @param edge an edge to remove\n */\n public void removeFromPlusPlusHeap(BlossomVEdge edge)\n {\n edge.handle.delete();\n edge.handle = null;\n }\n\n /**\n * Returns the current heap of (-, +) cross-tree edges. Always returns a heap different from\n * {@code getCurrentPlusMinusHeap(currentDir)}\n *\n * @param currentDir the current direction of this edge\n * @return returns current heap of (-, +) cross-tree edges\n */\n public MergeableAddressableHeap getCurrentMinusPlusHeap(int currentDir)\n {\n return currentDir == 0 ? plusMinusEdges0 : plusMinusEdges1;\n }\n\n /**\n * Returns the current heap of (+, -) cross-tree edges. Always returns a heap different from\n * {@code getCurrentMinusPlusHeap(currentDir)}\n *\n * @param currentDir the current direction of this edge\n * @return returns current heap of (+, -) cross-tree edges\n */\n public MergeableAddressableHeap getCurrentPlusMinusHeap(int currentDir)\n {\n return currentDir == 0 ? plusMinusEdges1 : plusMinusEdges0;\n }\n}\n", "file_name": "BlossomVTreeEdge.java", "human_label": "Remove this edge from both doubly linked lists of the tree edges.", "level": "class_runnable", "lineno": "100", "name": "removeFromTreeEdgeList", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[prev, next, head]\" }", "package": "org.jgrapht.alg.matching.blossom.v5", "project": "jgrapht-master" }, { "_id": "636767791a6d9265ec01826d", "all_context": "{ \"class_level\" : \"import java.io.InputStream;\\nimport java.io.InterruptedIOException;\\nimport java.net.URL;\\nimport java.util.Properties;\\nimport org.apache.log4j.Level;\\nimport org.apache.log4j.PropertyConfigurator;\\nimport org.apache.log4j.spi.Configurator;\\nimport org.apache.log4j.spi.LoggerRepository;\\nString DELIM_START;\\nchar DELIM_STOP;\\nint DELIM_START_LEN;\\nint DELIM_STOP_LEN;\\nOptionConverter();\\nconcatanateArrays(String[] l,String[] r);\\nconvertSpecialChars(String s);\\ngetSystemProperty(String key,String def);\\ninstantiateByKey(Properties props,String key,Class superClass,Object defaultValue);\\ntoInt(String value,int dEfault);\\ntoLevel(String value,Level defaultValue);\\ntoFileSize(String value,long dEfault);\\nfindAndSubst(String key,Properties props);\\ninstantiateByClassName(String className,Class superClass,Object defaultValue);\\nsubstVars(String val,Properties props);\\nselectAndConfigure(InputStream inputStream,String clazz,LoggerRepository hierarchy);\\nselectAndConfigure(URL url,String clazz,LoggerRepository hierarchy);\\ntoBoolean(String value,boolean dEfault);\\n\", \"repo_level\" : \"public interface Level {static Level toLevel(String sArg);\\nstatic Level toLevel(int val);\\nstatic Level toLevel(int val,Level defaultLevel);\\nstatic Level toLevel(String sArg,Level defaultLevel);\\n }\\npublic interface PropertyConfigurator {public void doConfigure(String configFileName,LoggerRepository hierarchy);\\npublic void configure(String configFilename);\\nstatic void configure(URL configURL);\\nstatic void configure(InputStream inputStream);\\npublic void configure(Properties properties);\\npublic void configureAndWatch(String configFilename);\\npublic void configureAndWatch(String configFilename,long delay);\\npublic void doConfigure(Properties properties,LoggerRepository hierarchy);\\npublic void doConfigure(InputStream inputStream,LoggerRepository hierarchy);\\npublic void doConfigure(URL configURL,LoggerRepository hierarchy);\\nprotected void configureLoggerFactory(Properties props);\\n void configureRootCategory(Properties props,LoggerRepository hierarchy);\\nprotected void parseCatsAndRenderers(Properties props,LoggerRepository hierarchy);\\n void parseAdditivityForLogger(Properties props,Logger cat,String loggerName);\\n void parseCategory(Properties props,Logger logger,String optionKey,String loggerName,String value);\\n Appender parseAppender(Properties props,String appenderName);\\n void parseAppenderFilters(Properties props,String appenderName,Appender appender);\\n void registryPut(Appender appender);\\n Appender registryGet(String name);\\n }\\npublic interface Configurator { void doConfigure(InputStream inputStream,LoggerRepository repository);\\n void doConfigure(URL url,LoggerRepository repository);\\n }\\npublic interface LoggerRepository {public void addHierarchyEventListener(HierarchyEventListener listener);\\n boolean isDisabled(int level);\\npublic void setThreshold(Level level);\\npublic void setThreshold(String val);\\npublic void emitNoAppenderWarning(Category cat);\\npublic Level getThreshold();\\npublic Logger getLogger(String name);\\npublic Logger getLogger(String name,LoggerFactory factory);\\npublic Logger getRootLogger();\\nabstract Logger exists(String name);\\nabstract void shutdown();\\npublic Enumeration getCurrentLoggers();\\npublic Enumeration getCurrentCategories();\\nabstract void fireAddAppenderEvent(Category logger,Appender appender);\\nabstract void resetConfiguration();\\n }\\n\" }", "class_name": "OptionConverter", "code": "public static String findAndSubst(String key,Properties props){\n String value=props.getProperty(key);\n if (value == null) return null;\n try {\n return substVars(value,props);\n }\n catch ( IllegalArgumentException e) {\n LogLog.error(\"Bad option value [\" + value + \"].\",e);\n return value;\n }\n}\n", "docstring": "/** \n * Find the value corresponding to key in props. Then perform variable substitution on the found value.\n */\n", "end_lineno": "309", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.log4j.helpers;\n\nimport java.io.InputStream;\nimport java.io.InterruptedIOException;\nimport java.net.URL;\nimport java.util.Properties;\n\nimport org.apache.log4j.Level;\nimport org.apache.log4j.PropertyConfigurator;\nimport org.apache.log4j.spi.Configurator;\nimport org.apache.log4j.spi.LoggerRepository;\n\n// Contributors: Avy Sharell (sharell@online.fr)\n// Matthieu Verbert (mve@zurich.ibm.com)\n// Colin Sampaleanu\n\n/**\n A convenience class to convert property values to specific types.\n\n @author Ceki Gülcü\n @author Simon Kitching;\n @author Anders Kristensen\n*/\npublic class OptionConverter {\n\n static String DELIM_START = \"${\";\n static char DELIM_STOP = '}';\n static int DELIM_START_LEN = 2;\n static int DELIM_STOP_LEN = 1;\n\n /** OptionConverter is a static class. */\n private OptionConverter() {}\n\n public\n static\n String[] concatanateArrays(String[] l, String[] r) {\n int len = l.length + r.length;\n String[] a = new String[len];\n\n System.arraycopy(l, 0, a, 0, l.length);\n System.arraycopy(r, 0, a, l.length, r.length);\n\n return a;\n }\n\n public\n static\n String convertSpecialChars(String s) {\n char c;\n int len = s.length();\n StringBuffer sbuf = new StringBuffer(len);\n\n int i = 0;\n while(i < len) {\n c = s.charAt(i++);\n if (c == '\\\\') {\n\tc = s.charAt(i++);\n\tif(c == 'n') c = '\\n';\n\telse if(c == 'r') c = '\\r';\n\telse if(c == 't') c = '\\t';\n\telse if(c == 'f') c = '\\f';\n\telse if(c == '\\b') c = '\\b';\n\telse if(c == '\\\"') c = '\\\"';\n\telse if(c == '\\'') c = '\\'';\n\telse if(c == '\\\\') c = '\\\\';\n }\n sbuf.append(c);\n }\n return sbuf.toString();\n }\n\n\n /**\n Very similar to System.getProperty except\n that the {@link SecurityException} is hidden.\n\n @param key The key to search for.\n @param def The default value to return.\n @return the string value of the system property, or the default\n value if there is no property with that key.\n\n @since 1.1 */\n public\n static\n String getSystemProperty(String key, String def) {\n try {\n return System.getProperty(key, def);\n } catch(Throwable e) { // MS-Java throws com.ms.security.SecurityExceptionEx\n LogLog.debug(\"Was not allowed to read system property \\\"\"+key+\"\\\".\");\n return def;\n }\n }\n\n\n public\n static\n Object instantiateByKey(Properties props, String key, Class superClass,\n\t\t\t\tObject defaultValue) {\n\n // Get the value of the property in string form\n String className = findAndSubst(key, props);\n if(className == null) {\n LogLog.error(\"Could not find value for key \" + key);\n return defaultValue;\n }\n // Trim className to avoid trailing spaces that cause problems.\n return OptionConverter.instantiateByClassName(className.trim(), superClass,\n\t\t\t\t\t\t defaultValue);\n }\n\n /**\n If value is \"true\", then true is\n returned. If value is \"false\", then\n true is returned. Otherwise, default is\n returned.\n\n

Case of value is unimportant. */\n public\n static\n boolean toBoolean(String value, boolean dEfault) {\n if(value == null)\n return dEfault;\n String trimmedVal = value.trim();\n if(\"true\".equalsIgnoreCase(trimmedVal))\n return true;\n if(\"false\".equalsIgnoreCase(trimmedVal))\n return false;\n return dEfault;\n }\n\n public\n static\n int toInt(String value, int dEfault) {\n if(value != null) {\n String s = value.trim();\n try {\n\treturn Integer.valueOf(s).intValue();\n }\n catch (NumberFormatException e) {\n\t LogLog.error(\"[\" + s + \"] is not in proper int form.\");\n\te.printStackTrace();\n }\n }\n return dEfault;\n }\n\n /**\n Converts a standard or custom priority level to a Level\n object.

If value is of form\n \"level#classname\", then the specified class' toLevel method\n is called to process the specified level string; if no '#'\n character is present, then the default {@link org.apache.log4j.Level}\n class is used to process the level value.\n\n

As a special case, if the value parameter is\n equal to the string \"NULL\", then the value null will\n be returned.\n\n

If any error occurs while converting the value to a level,\n the defaultValue parameter, which may be\n null, is returned.\n\n

Case of value is insignificant for the level level, but is\n significant for the class name part, if present.\n\n @since 1.1 */\n public\n static\n Level toLevel(String value, Level defaultValue) {\n if(value == null)\n return defaultValue;\n \n value = value.trim();\n\n int hashIndex = value.indexOf('#');\n if (hashIndex == -1) {\n if(\"NULL\".equalsIgnoreCase(value)) {\n\treturn null;\n } else {\n\t// no class name specified : use standard Level class\n\treturn(Level) Level.toLevel(value, defaultValue);\n }\n }\n\n Level result = defaultValue;\n\n String clazz = value.substring(hashIndex+1);\n String levelName = value.substring(0, hashIndex);\n\n // This is degenerate case but you never know.\n if(\"NULL\".equalsIgnoreCase(levelName)) {\n\treturn null;\n }\n\n LogLog.debug(\"toLevel\" + \":class=[\" + clazz + \"]\"\n\t\t + \":pri=[\" + levelName + \"]\");\n\n try {\n Class customLevel = Loader.loadClass(clazz);\n\n // get a ref to the specified class' static method\n // toLevel(String, org.apache.log4j.Level)\n Class[] paramTypes = new Class[] { String.class,\n\t\t\t\t\t org.apache.log4j.Level.class\n };\n java.lang.reflect.Method toLevelMethod =\n customLevel.getMethod(\"toLevel\", paramTypes);\n\n // now call the toLevel method, passing level string + default\n Object[] params = new Object[] {levelName, defaultValue};\n Object o = toLevelMethod.invoke(null, params);\n\n result = (Level) o;\n } catch(ClassNotFoundException e) {\n LogLog.warn(\"custom level class [\" + clazz + \"] not found.\");\n } catch(NoSuchMethodException e) {\n LogLog.warn(\"custom level class [\" + clazz + \"]\"\n + \" does not have a class function toLevel(String, Level)\", e);\n } catch(java.lang.reflect.InvocationTargetException e) {\n if (e.getTargetException() instanceof InterruptedException\n || e.getTargetException() instanceof InterruptedIOException) {\n Thread.currentThread().interrupt();\n }\n LogLog.warn(\"custom level class [\" + clazz + \"]\"\n\t\t + \" could not be instantiated\", e);\n } catch(ClassCastException e) {\n LogLog.warn(\"class [\" + clazz\n + \"] is not a subclass of org.apache.log4j.Level\", e);\n } catch(IllegalAccessException e) {\n LogLog.warn(\"class [\"+clazz+\n\t\t \"] cannot be instantiated due to access restrictions\", e);\n } catch(RuntimeException e) {\n LogLog.warn(\"class [\"+clazz+\"], level [\"+levelName+\n\t\t \"] conversion failed.\", e);\n }\n return result;\n }\n\n public\n static\n long toFileSize(String value, long dEfault) {\n if(value == null)\n return dEfault;\n\n String s = value.trim().toUpperCase();\n long multiplier = 1;\n int index;\n\n if((index = s.indexOf(\"KB\")) != -1) {\n multiplier = 1024;\n s = s.substring(0, index);\n }\n else if((index = s.indexOf(\"MB\")) != -1) {\n multiplier = 1024*1024;\n s = s.substring(0, index);\n }\n else if((index = s.indexOf(\"GB\")) != -1) {\n multiplier = 1024*1024*1024;\n s = s.substring(0, index);\n }\n if(s != null) {\n try {\n\treturn Long.valueOf(s).longValue() * multiplier;\n }\n catch (NumberFormatException e) {\n\tLogLog.error(\"[\" + s + \"] is not in proper int form.\");\n\tLogLog.error(\"[\" + value + \"] not in expected format.\", e);\n }\n }\n return dEfault;\n }\n\n /**\n Find the value corresponding to key in\n props. Then perform variable substitution on the\n found value.\n\n */\n public\n static\n String findAndSubst(String key, Properties props) {\n String value = props.getProperty(key);\n if(value == null)\n return null;\n\n try {\n return substVars(value, props);\n } catch(IllegalArgumentException e) {\n LogLog.error(\"Bad option value [\"+value+\"].\", e);\n return value;\n }\n }\n\n /**\n Instantiate an object given a class name. Check that the\n className is a subclass of\n superClass. If that test fails or the object could\n not be instantiated, then defaultValue is returned.\n\n @param className The fully qualified class name of the object to instantiate.\n @param superClass The class to which the new object should belong.\n @param defaultValue The object to return in case of non-fulfillment\n */\n public\n static\n Object instantiateByClassName(String className, Class superClass,\n\t\t\t\tObject defaultValue) {\n if(className != null) {\n try {\n\tClass classObj = Loader.loadClass(className);\n\tif(!superClass.isAssignableFrom(classObj)) {\n\t LogLog.error(\"A \\\"\"+className+\"\\\" object is not assignable to a \\\"\"+\n\t\t superClass.getName() + \"\\\" variable.\");\n\t LogLog.error(\"The class \\\"\"+ superClass.getName()+\"\\\" was loaded by \");\n\t LogLog.error(\"[\"+superClass.getClassLoader()+\"] whereas object of type \");\n\t LogLog.error(\"\\\"\" +classObj.getName()+\"\\\" was loaded by [\"\n\t\t +classObj.getClassLoader()+\"].\");\n\t return defaultValue;\n\t}\n\treturn classObj.newInstance();\n } catch (ClassNotFoundException e) {\n\t LogLog.error(\"Could not instantiate class [\" + className + \"].\", e);\n } catch (IllegalAccessException e) {\n\t LogLog.error(\"Could not instantiate class [\" + className + \"].\", e);\n } catch (InstantiationException e) {\n LogLog.error(\"Could not instantiate class [\" + className + \"].\", e);\n } catch (RuntimeException e) {\n\t LogLog.error(\"Could not instantiate class [\" + className + \"].\", e);\n }\n }\n return defaultValue;\n }\n\n\n /**\n Perform variable substitution in string val from the\n values of keys found in the system propeties.\n\n

The variable substitution delimeters are ${ and }.\n\n

For example, if the System properties contains \"key=value\", then\n the call\n

\n     String s = OptionConverter.substituteVars(\"Value of key is ${key}.\");\n     
\n\n will set the variable s to \"Value of key is value.\".\n\n

If no value could be found for the specified key, then the\n props parameter is searched, if the value could not\n be found there, then substitution defaults to the empty string.\n\n

For example, if system propeties contains no value for the key\n \"inexistentKey\", then the call\n\n

\n     String s = OptionConverter.subsVars(\"Value of inexistentKey is [${inexistentKey}]\");\n     
\n will set s to \"Value of inexistentKey is []\"\n\n

An {@link java.lang.IllegalArgumentException} is thrown if\n val contains a start delimeter \"${\" which is not\n balanced by a stop delimeter \"}\".

\n\n

Author Avy Sharell

\n\n @param val The string on which variable substitution is performed.\n @throws IllegalArgumentException if val is malformed.\n\n */\n public static\n String substVars(String val, Properties props) throws\n IllegalArgumentException {\n\n StringBuffer sbuf = new StringBuffer();\n\n int i = 0;\n int j, k;\n\n while(true) {\n j=val.indexOf(DELIM_START, i);\n if(j == -1) {\n\t// no more variables\n\tif(i==0) { // this is a simple string\n\t return val;\n\t} else { // add the tail string which contails no variables and return the result.\n\t sbuf.append(val.substring(i, val.length()));\n\t return sbuf.toString();\n\t}\n } else {\n\tsbuf.append(val.substring(i, j));\n\tk = val.indexOf(DELIM_STOP, j);\n\tif(k == -1) {\n\t throw new IllegalArgumentException('\"'+val+\n\t\t \"\\\" has no closing brace. Opening brace at position \" + j\n\t\t\t\t\t + '.');\n\t} else {\n\t j += DELIM_START_LEN;\n\t String key = val.substring(j, k);\n\t // first try in System properties\n\t String replacement = getSystemProperty(key, null);\n\t // then try props parameter\n\t if(replacement == null && props != null) {\n\t replacement = props.getProperty(key);\n\t }\n\n\t if(replacement != null) {\n\t // Do variable substitution on the replacement string\n\t // such that we can solve \"Hello ${x2}\" as \"Hello p1\" \n // the where the properties are\n\t // x1=p1\n // x2=${x1}\n\t String recursiveReplacement = substVars(replacement, props);\n\t sbuf.append(recursiveReplacement);\n\t }\n\t i = k + DELIM_STOP_LEN;\n\t}\n }\n }\n }\n\n /**\n * Configure log4j given an {@link InputStream}.\n * \n *

\n * The InputStream will be interpreted by a new instance of a log4j configurator.\n *

\n *

\n * All configurations steps are taken on the hierarchy passed as a parameter.\n *

\n * \n * @param inputStream\n * The configuration input stream.\n * @param clazz\n * The class name, of the log4j configurator which will parse the inputStream. This must be a\n * subclass of {@link Configurator}, or null. If this value is null then a default configurator of\n * {@link PropertyConfigurator} is used.\n * @param hierarchy\n * The {@link org.apache.log4j.Hierarchy} to act on.\n * @since 1.2.17\n */\n\nstatic\npublic\nvoid selectAndConfigure(InputStream inputStream, String clazz, LoggerRepository hierarchy) {\nConfigurator configurator = null;\n\nif(clazz != null) {\n LogLog.debug(\"Preferred configurator class: \" + clazz);\n configurator = (Configurator) instantiateByClassName(clazz,\n Configurator.class,\n null);\n if(configurator == null) {\n LogLog.error(\"Could not instantiate configurator [\"+clazz+\"].\");\n return;\n }\n} else {\n configurator = new PropertyConfigurator();\n}\n\nconfigurator.doConfigure(inputStream, hierarchy);\n}\n\n\n /**\n Configure log4j given a URL.\n\n

The url must point to a file or resource which will be interpreted by\n a new instance of a log4j configurator.\n\n

All configurations steps are taken on the\n hierarchy passed as a parameter.\n\n

\n @param url The location of the configuration file or resource.\n @param clazz The classname, of the log4j configurator which will parse\n the file or resource at url. This must be a subclass of\n {@link Configurator}, or null. If this value is null then a default\n configurator of {@link PropertyConfigurator} is used, unless the\n filename pointed to by url ends in '.xml', in which case\n {@link org.apache.log4j.xml.DOMConfigurator} is used.\n @param hierarchy The {@link org.apache.log4j.Hierarchy} to act on.\n\n @since 1.1.4 */\n\n static\n public\n void selectAndConfigure(URL url, String clazz, LoggerRepository hierarchy) {\n Configurator configurator = null;\n String filename = url.getFile();\n\n if(clazz == null && filename != null && filename.endsWith(\".xml\")) {\n clazz = \"org.apache.log4j.xml.DOMConfigurator\";\n }\n\n if(clazz != null) {\n LogLog.debug(\"Preferred configurator class: \" + clazz);\n configurator = (Configurator) instantiateByClassName(clazz,\n\t\t\t\t\t\t\t Configurator.class,\n\t\t\t\t\t\t\t null);\n if(configurator == null) {\n \t LogLog.error(\"Could not instantiate configurator [\"+clazz+\"].\");\n \t return;\n }\n } else {\n configurator = new PropertyConfigurator();\n }\n\n configurator.doConfigure(url, hierarchy);\n }\n}\n", "file_name": "OptionConverter.java", "human_label": "Find the value corresponding to key in props, then perform variable substitution on the found value. Return the substitution result, or the value in case of exception. ", "level": "project_runnable", "lineno": "290", "name": "findAndSubst", "oracle_context": "{ \"apis\" : \"[getProperty, substVars, error]\", \"classes\" : \"[String]\", \"vars\" : \"[]\" }", "package": "org.apache.log4j.helpers", "project": "logging-log4j1-main" }, { "_id": "636767001a6d9265ec01787f", "all_context": "{ \"class_level\" : \"import net.hasor.utils.ClassUtils;\\nimport net.hasor.utils.ObjectUtils;\\nimport java.io.Serializable;\\nimport java.lang.reflect.Array;\\nimport java.util.Collection;\\nimport java.util.Map;\\nimport java.util.WeakHashMap;\\nToStringStyle DEFAULT_STYLE;\\nToStringStyle MULTI_LINE_STYLE;\\nToStringStyle NO_FIELD_NAMES_STYLE;\\nToStringStyle SHORT_PREFIX_STYLE;\\nToStringStyle SIMPLE_STYLE;\\nThreadLocal REGISTRY;\\nboolean useFieldNames;\\nboolean useClassName;\\nboolean useShortClassName;\\nboolean useIdentityHashCode;\\nString contentStart;\\nString contentEnd;\\nString fieldNameValueSeparator;\\nboolean fieldSeparatorAtStart;\\nboolean fieldSeparatorAtEnd;\\nString fieldSeparator;\\nString arrayStart;\\nString arraySeparator;\\nboolean arrayContentDetail;\\nString arrayEnd;\\nboolean defaultFullDetail;\\nString nullText;\\nString sizeStartText;\\nString sizeEndText;\\nString summaryObjectStartText;\\nString summaryObjectEndText;\\nlong serialVersionUID;\\ngetRegistry();\\nregister(Object value);\\nunregister(Object value);\\nToStringStyle();\\nappendSuper(StringBuffer buffer,String superToString);\\nappendToString(StringBuffer buffer,String toString);\\nappendStart(StringBuffer buffer,Object object);\\nappendEnd(StringBuffer buffer,Object object);\\nremoveLastFieldSeparator(StringBuffer buffer);\\nappend(StringBuffer buffer,String fieldName,Object value,Boolean fullDetail);\\nappendInternal(StringBuffer buffer,String fieldName,Object value,boolean detail);\\nappendCyclicObject(StringBuffer buffer,String fieldName,Object value);\\nappendDetail(StringBuffer buffer,String fieldName,Object value);\\nappendDetail(StringBuffer buffer,String fieldName,Collection coll);\\nappendDetail(StringBuffer buffer,String fieldName,Map map);\\nappendSummary(StringBuffer buffer,String fieldName,Object value);\\nappend(StringBuffer buffer,String fieldName,long value);\\nappendDetail(StringBuffer buffer,String fieldName,long value);\\nappend(StringBuffer buffer,String fieldName,int value);\\nappendDetail(StringBuffer buffer,String fieldName,int value);\\nappend(StringBuffer buffer,String fieldName,short value);\\nappendDetail(StringBuffer buffer,String fieldName,short value);\\nappend(StringBuffer buffer,String fieldName,byte value);\\nappendDetail(StringBuffer buffer,String fieldName,byte value);\\nappend(StringBuffer buffer,String fieldName,char value);\\nappendDetail(StringBuffer buffer,String fieldName,char value);\\nappend(StringBuffer buffer,String fieldName,double value);\\nappendDetail(StringBuffer buffer,String fieldName,double value);\\nappend(StringBuffer buffer,String fieldName,float value);\\nappendDetail(StringBuffer buffer,String fieldName,float value);\\nappend(StringBuffer buffer,String fieldName,boolean value);\\nappendDetail(StringBuffer buffer,String fieldName,boolean value);\\nappend(StringBuffer buffer,String fieldName,Object[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,Object[] array);\\nreflectionAppendArrayDetail(StringBuffer buffer,String fieldName,Object array);\\nappendSummary(StringBuffer buffer,String fieldName,Object[] array);\\nappend(StringBuffer buffer,String fieldName,long[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,long[] array);\\nappendSummary(StringBuffer buffer,String fieldName,long[] array);\\nappend(StringBuffer buffer,String fieldName,int[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,int[] array);\\nappendSummary(StringBuffer buffer,String fieldName,int[] array);\\nappend(StringBuffer buffer,String fieldName,short[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,short[] array);\\nappendSummary(StringBuffer buffer,String fieldName,short[] array);\\nappend(StringBuffer buffer,String fieldName,byte[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,byte[] array);\\nappendSummary(StringBuffer buffer,String fieldName,byte[] array);\\nappend(StringBuffer buffer,String fieldName,char[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,char[] array);\\nappendSummary(StringBuffer buffer,String fieldName,char[] array);\\nappend(StringBuffer buffer,String fieldName,double[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,double[] array);\\nappendSummary(StringBuffer buffer,String fieldName,double[] array);\\nappend(StringBuffer buffer,String fieldName,float[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,float[] array);\\nappendSummary(StringBuffer buffer,String fieldName,float[] array);\\nappend(StringBuffer buffer,String fieldName,boolean[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,boolean[] array);\\nappendSummary(StringBuffer buffer,String fieldName,boolean[] array);\\nappendClassName(StringBuffer buffer,Object object);\\nappendIdentityHashCode(StringBuffer buffer,Object object);\\nappendContentStart(StringBuffer buffer);\\nappendContentEnd(StringBuffer buffer);\\nappendNullText(StringBuffer buffer,String fieldName);\\nappendFieldSeparator(StringBuffer buffer);\\nappendFieldStart(StringBuffer buffer,String fieldName);\\nappendFieldEnd(StringBuffer buffer,String fieldName);\\nappendSummarySize(StringBuffer buffer,String fieldName,int size);\\nisFullDetail(Boolean fullDetailRequest);\\ngetShortClassName(Class cls);\\nisUseClassName();\\nsetUseClassName(boolean useClassName);\\nisUseShortClassName();\\nisShortClassName();\\nsetUseShortClassName(boolean useShortClassName);\\nsetShortClassName(boolean shortClassName);\\nisUseIdentityHashCode();\\nsetUseIdentityHashCode(boolean useIdentityHashCode);\\nisUseFieldNames();\\nsetUseFieldNames(boolean useFieldNames);\\nisDefaultFullDetail();\\nsetDefaultFullDetail(boolean defaultFullDetail);\\nisArrayContentDetail();\\nsetArrayContentDetail(boolean arrayContentDetail);\\ngetArrayStart();\\nsetArrayStart(String arrayStart);\\ngetArrayEnd();\\nsetArrayEnd(String arrayEnd);\\ngetArraySeparator();\\nsetArraySeparator(String arraySeparator);\\ngetContentStart();\\nsetContentStart(String contentStart);\\ngetContentEnd();\\nsetContentEnd(String contentEnd);\\ngetFieldNameValueSeparator();\\nsetFieldNameValueSeparator(String fieldNameValueSeparator);\\ngetFieldSeparator();\\nsetFieldSeparator(String fieldSeparator);\\nisFieldSeparatorAtStart();\\nsetFieldSeparatorAtStart(boolean fieldSeparatorAtStart);\\nisFieldSeparatorAtEnd();\\nsetFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd);\\ngetNullText();\\nsetNullText(String nullText);\\ngetSizeStartText();\\nsetSizeStartText(String sizeStartText);\\ngetSizeEndText();\\nsetSizeEndText(String sizeEndText);\\ngetSummaryObjectStartText();\\nsetSummaryObjectStartText(String summaryObjectStartText);\\ngetSummaryObjectEndText();\\nsetSummaryObjectEndText(String summaryObjectEndText);\\nDefaultToStringStyle();\\nreadResolve();\\nNoFieldNameToStringStyle();\\nShortPrefixToStringStyle();\\nSimpleToStringStyle();\\nMultiLineToStringStyle();\\ngetSystemProperty(String property);\\nisRegistered(Object value);\\n\", \"repo_level\" : \"public interface ClassUtils {static String getShortClassName(Object object,String valueIfNull);\\nstatic String getShortClassName(Class cls);\\nstatic String getShortClassName(String className);\\nstatic String getPackageName(Object object,String valueIfNull);\\nstatic String getPackageName(Class cls);\\nstatic String getPackageName(String className);\\nstatic List> getAllSuperclasses(Class cls);\\nstatic List> getAllInterfaces(Class cls);\\nstatic List> convertClassNamesToClasses(List classNames);\\nstatic List convertClassesToClassNames(List classes);\\nstatic boolean isAssignable(Class[] classArray,Class[] toClassArray);\\nstatic boolean isAssignable(Class[] classArray,Class[] toClassArray,boolean autoboxing);\\nstatic boolean isAssignable(Class cls,Class toClass);\\nstatic boolean isAssignable(Class cls,Class toClass,boolean autoboxing);\\nstatic Class primitiveToWrapper(Class cls);\\nstatic Class[] primitivesToWrappers(Class[] classes);\\nstatic Class wrapperToPrimitive(Class cls);\\nstatic Class[] wrappersToPrimitives(Class[] classes);\\nstatic boolean isInnerClass(Class cls);\\nstatic Class getClass(ClassLoader classLoader,String className,boolean initialize);\\nstatic Class getClass(ClassLoader classLoader,String className);\\nstatic Class getClass(String className);\\nstatic Class getClass(String className,boolean initialize);\\nstatic Method getPublicMethod(Class cls,String methodName,Class parameterTypes);\\nstatic Class[] toClass(Object[] array);\\nstatic String getShortCanonicalName(Object object,String valueIfNull);\\nstatic String getShortCanonicalName(Class cls);\\nstatic String getShortCanonicalName(String canonicalName);\\nstatic String getPackageCanonicalName(Object object,String valueIfNull);\\nstatic String getPackageCanonicalName(Class cls);\\nstatic String getPackageCanonicalName(String canonicalName);\\nstatic ClassLoader getClassLoader(ClassLoader classLoader);\\nstatic boolean isLangClass(Class target);\\nstatic String getDescName(Class type);\\nstatic String getDescNameWithOutModifiers(Method method);\\nstatic String getDescName(Method method);\\nstatic Class getSuperClassGenricType(Class clazz,int index);\\nstatic T newInstance(Class clazz);\\n }\\npublic interface ObjectUtils {static Object defaultIfNull(Object object,Object defaultValue);\\nstatic boolean equals(Object object1,Object object2);\\nstatic boolean notEqual(Object object1,Object object2);\\nstatic int hashCode(Object obj);\\nstatic String identityToString(Object object);\\nstatic void identityToString(StringBuffer buffer,Object object);\\nstatic String toString(Object obj);\\nstatic String toString(Object obj,String nullStr);\\nstatic Object min(Comparable c1,Comparable c2);\\nstatic Object max(Comparable c1,Comparable c2);\\nstatic int compare(Comparable c1,Comparable c2);\\nstatic int compare(Comparable c1,Comparable c2,boolean nullGreater);\\n }\\n\" }", "class_name": "ToStringStyle", "code": "protected void appendDetail(StringBuffer buffer,String fieldName,int[] array){\n buffer.append(arrayStart);\n for (int i=0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer,fieldName,array[i]);\n }\n buffer.append(arrayEnd);\n}\n", "docstring": "/** \n *

Append to the toString the detail of an int array.

\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,not null\n */\n", "end_lineno": "980", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.builder;\nimport net.hasor.utils.ClassUtils;\nimport net.hasor.utils.ObjectUtils;\n\nimport java.io.Serializable;\nimport java.lang.reflect.Array;\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.WeakHashMap;\n\n/**\n *

Controls String formatting for {@link ToStringBuilder}.\n * The main public interface is always via ToStringBuilder.

\n *\n *

These classes are intended to be used as Singletons.\n * There is no need to instantiate a new style each time. A program\n * will generally use one of the predefined constants on this class.\n * Alternatively, the {@link StandardToStringStyle} class can be used\n * to set the individual settings. Thus most styles can be achieved\n * without subclassing.

\n *\n *

If required, a subclass can override as many or as few of the\n * methods as it requires. Each object type (from boolean\n * to long to Object to int[]) has\n * its own methods to output it. Most have two versions, detail and summary.\n *\n *

For example, the detail version of the array based methods will\n * output the whole array, whereas the summary method will just output\n * the array length.

\n *\n *

If you want to format the output of certain objects, such as dates, you\n * must create a subclass and override a method.\n *

\n * public class MyStyle extends ToStringStyle {\n *   protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {\n *     if (value instanceof Date) {\n *       value = new SimpleDateFormat(\"yyyy-MM-dd\").format(value);\n *     }\n *     buffer.append(value);\n *   }\n * }\n * 
\n *

\n *\n * @author Apache Software Foundation\n * @author Gary Gregory\n * @author Pete Gieser\n * @author Masato Tezuka\n * @since 1.0\n * @version $Id: ToStringStyle.java 907168 2010-02-06 03:33:50Z mbenson $\n */\npublic abstract class ToStringStyle implements Serializable {\n /**\n * The default toString style. Using the Using the Person\n * example from {@link ToStringBuilder}, the output would look like this:\n *\n *
\n     * Person@182f0db[name=John Doe,age=33,smoker=false]\n     * 
\n */\n public static final ToStringStyle DEFAULT_STYLE = new DefaultToStringStyle();\n /**\n * The multi line toString style. Using the Using the Person\n * example from {@link ToStringBuilder}, the output would look like this:\n *\n *
\n     * Person@182f0db[\n     *   name=John Doe\n     *   age=33\n     *   smoker=false\n     * ]\n     * 
\n */\n public static final ToStringStyle MULTI_LINE_STYLE = new MultiLineToStringStyle();\n /**\n * The no field names toString style. Using the Using the\n * Person example from {@link ToStringBuilder}, the output\n * would look like this:\n *\n *
\n     * Person@182f0db[John Doe,33,false]\n     * 
\n */\n public static final ToStringStyle NO_FIELD_NAMES_STYLE = new NoFieldNameToStringStyle();\n /**\n * The short prefix toString style. Using the Person example\n * from {@link ToStringBuilder}, the output would look like this:\n *\n *
\n     * Person[name=John Doe,age=33,smoker=false]\n     * 
\n *\n * @since 2.1\n */\n public static final ToStringStyle SHORT_PREFIX_STYLE = new ShortPrefixToStringStyle();\n /**\n * The simple toString style. Using the Using the Person\n * example from {@link ToStringBuilder}, the output would look like this:\n *\n *
\n     * John Doe,33,false\n     * 
\n */\n public static final ToStringStyle SIMPLE_STYLE = new SimpleToStringStyle();\n /**\n *

\n * A registry of objects used by reflectionToString methods\n * to detect cyclical object references and avoid infinite loops.\n *

\n */\n private static final ThreadLocal REGISTRY = new ThreadLocal();\n\n /**\n *

\n * Returns the registry of objects being traversed by the reflectionToString\n * methods in the current thread.\n *

\n *\n * @return Set the registry of objects being traversed\n */\n static Map getRegistry() {\n return (Map) REGISTRY.get();\n }\n\n /**\n *

\n * Returns true if the registry contains the given object.\n * Used by the reflection methods to avoid infinite loops.\n *

\n *\n * @param value\n * The object to lookup in the registry.\n * @return boolean true if the registry contains the given\n * object.\n */\n static boolean isRegistered(Object value) {\n Map m = getRegistry();\n return m != null && m.containsKey(value);\n }\n\n /**\n *

\n * Registers the given object. Used by the reflection methods to avoid\n * infinite loops.\n *

\n *\n * @param value\n * The object to register.\n */\n static void register(Object value) {\n if (value != null) {\n Map m = getRegistry();\n if (m == null) {\n m = new WeakHashMap();\n REGISTRY.set(m);\n }\n m.put(value, null);\n }\n }\n\n /**\n *

\n * Unregisters the given object.\n *

\n *\n *

\n * Used by the reflection methods to avoid infinite loops.\n *

\n *\n * @param value\n * The object to unregister.\n */\n static void unregister(Object value) {\n if (value != null) {\n Map m = getRegistry();\n if (m != null) {\n m.remove(value);\n if (m.isEmpty()) {\n REGISTRY.set(null);\n }\n }\n }\n }\n\n /**\n * Whether to use the field names, the default is true.\n */\n private boolean useFieldNames = true;\n /**\n * Whether to use the class name, the default is true.\n */\n private boolean useClassName = true;\n /**\n * Whether to use short class names, the default is false.\n */\n private boolean useShortClassName = false;\n /**\n * Whether to use the identity hash code, the default is true.\n */\n private boolean useIdentityHashCode = true;\n /**\n * The content start '['.\n */\n private String contentStart = \"[\";\n /**\n * The content end ']'.\n */\n private String contentEnd = \"]\";\n /**\n * The field name value separator '='.\n */\n private String fieldNameValueSeparator = \"=\";\n /**\n * Whether the field separator should be added before any other fields.\n */\n private boolean fieldSeparatorAtStart = false;\n /**\n * Whether the field separator should be added after any other fields.\n */\n private boolean fieldSeparatorAtEnd = false;\n /**\n * The field separator ','.\n */\n private String fieldSeparator = \",\";\n /**\n * The array start '{'.\n */\n private String arrayStart = \"{\";\n /**\n * The array separator ','.\n */\n private String arraySeparator = \",\";\n /**\n * The detail for array content.\n */\n private boolean arrayContentDetail = true;\n /**\n * The array end '}'.\n */\n private String arrayEnd = \"}\";\n /**\n * The value to use when fullDetail is null,\n * the default value is true.\n */\n private boolean defaultFullDetail = true;\n /**\n * The null text '<null>'.\n */\n private String nullText = \"\";\n /**\n * The summary size text start '.\n */\n private String sizeStartText = \"'>'.\n */\n private String sizeEndText = \">\";\n /**\n * The summary object text start '<'.\n */\n private String summaryObjectStartText = \"<\";\n /**\n * The summary object text start '>'.\n */\n private String summaryObjectEndText = \">\";\n //----------------------------------------------------------------------------\n\n /**\n *

Constructor.

\n */\n protected ToStringStyle() {\n super();\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString the superclass toString.

\n *

NOTE: It assumes that the toString has been created from the same ToStringStyle.

\n *\n *

A null superToString is ignored.

\n *\n * @param buffer the StringBuffer to populate\n * @param superToString the super.toString()\n * @since 2.0\n */\n public void appendSuper(StringBuffer buffer, String superToString) {\n appendToString(buffer, superToString);\n }\n\n /**\n *

Append to the toString another toString.

\n *

NOTE: It assumes that the toString has been created from the same ToStringStyle.

\n *\n *

A null toString is ignored.

\n *\n * @param buffer the StringBuffer to populate\n * @param toString the additional toString\n * @since 2.0\n */\n public void appendToString(StringBuffer buffer, String toString) {\n if (toString != null) {\n int pos1 = toString.indexOf(contentStart) + contentStart.length();\n int pos2 = toString.lastIndexOf(contentEnd);\n if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) {\n String data = toString.substring(pos1, pos2);\n if (fieldSeparatorAtStart) {\n removeLastFieldSeparator(buffer);\n }\n buffer.append(data);\n appendFieldSeparator(buffer);\n }\n }\n }\n\n /**\n *

Append to the toString the start of data indicator.

\n *\n * @param buffer the StringBuffer to populate\n * @param object the Object to build a toString for\n */\n public void appendStart(StringBuffer buffer, Object object) {\n if (object != null) {\n appendClassName(buffer, object);\n appendIdentityHashCode(buffer, object);\n appendContentStart(buffer);\n if (fieldSeparatorAtStart) {\n appendFieldSeparator(buffer);\n }\n }\n }\n\n /**\n *

Append to the toString the end of data indicator.

\n *\n * @param buffer the StringBuffer to populate\n * @param object the Object to build a\n * toString for.\n */\n public void appendEnd(StringBuffer buffer, Object object) {\n if (this.fieldSeparatorAtEnd == false) {\n removeLastFieldSeparator(buffer);\n }\n appendContentEnd(buffer);\n unregister(object);\n }\n\n /**\n *

Remove the last field separator from the buffer.

\n *\n * @param buffer the StringBuffer to populate\n * @since 2.0\n */\n protected void removeLastFieldSeparator(StringBuffer buffer) {\n int len = buffer.length();\n int sepLen = fieldSeparator.length();\n if (len > 0 && sepLen > 0 && len >= sepLen) {\n boolean match = true;\n for (int i = 0; i < sepLen; i++) {\n if (buffer.charAt(len - 1 - i) != fieldSeparator.charAt(sepLen - 1 - i)) {\n match = false;\n break;\n }\n }\n if (match) {\n buffer.setLength(len - sepLen);\n }\n }\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString an Object\n * value, printing the full toString of the\n * Object passed in.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (value == null) {\n appendNullText(buffer, fieldName);\n } else {\n appendInternal(buffer, fieldName, value, isFullDetail(fullDetail));\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString an Object,\n * correctly interpreting its type.

\n *\n *

This method performs the main lookup by Class type to correctly\n * route arrays, Collections, Maps and\n * Objects to the appropriate method.

\n *\n *

Either detail or summary views can be specified.

\n *\n *

If a cycle is detected, an object will be appended with the\n * Object.toString() format.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString,\n * not null\n * @param detail output detail or not\n */\n protected void appendInternal(StringBuffer buffer, String fieldName, Object value, boolean detail) {\n if (isRegistered(value) && !(value instanceof Number || value instanceof Boolean || value instanceof Character)) {\n appendCyclicObject(buffer, fieldName, value);\n return;\n }\n register(value);\n try {\n if (value instanceof Collection) {\n if (detail) {\n appendDetail(buffer, fieldName, (Collection) value);\n } else {\n appendSummarySize(buffer, fieldName, ((Collection) value).size());\n }\n } else if (value instanceof Map) {\n if (detail) {\n appendDetail(buffer, fieldName, (Map) value);\n } else {\n appendSummarySize(buffer, fieldName, ((Map) value).size());\n }\n } else if (value instanceof long[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (long[]) value);\n } else {\n appendSummary(buffer, fieldName, (long[]) value);\n }\n } else if (value instanceof int[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (int[]) value);\n } else {\n appendSummary(buffer, fieldName, (int[]) value);\n }\n } else if (value instanceof short[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (short[]) value);\n } else {\n appendSummary(buffer, fieldName, (short[]) value);\n }\n } else if (value instanceof byte[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (byte[]) value);\n } else {\n appendSummary(buffer, fieldName, (byte[]) value);\n }\n } else if (value instanceof char[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (char[]) value);\n } else {\n appendSummary(buffer, fieldName, (char[]) value);\n }\n } else if (value instanceof double[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (double[]) value);\n } else {\n appendSummary(buffer, fieldName, (double[]) value);\n }\n } else if (value instanceof float[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (float[]) value);\n } else {\n appendSummary(buffer, fieldName, (float[]) value);\n }\n } else if (value instanceof boolean[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (boolean[]) value);\n } else {\n appendSummary(buffer, fieldName, (boolean[]) value);\n }\n } else if (value.getClass().isArray()) {\n if (detail) {\n appendDetail(buffer, fieldName, (Object[]) value);\n } else {\n appendSummary(buffer, fieldName, (Object[]) value);\n }\n } else {\n if (detail) {\n appendDetail(buffer, fieldName, value);\n } else {\n appendSummary(buffer, fieldName, value);\n }\n }\n } finally {\n unregister(value);\n }\n }\n\n /**\n *

Append to the toString an Object\n * value that has been detected to participate in a cycle. This\n * implementation will print the standard string value of the value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString,\n * not null\n *\n * @since 2.2\n */\n protected void appendCyclicObject(StringBuffer buffer, String fieldName, Object value) {\n ObjectUtils.identityToString(buffer, value);\n }\n\n /**\n *

Append to the toString an Object\n * value, printing the full detail of the Object.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {\n buffer.append(value);\n }\n\n /**\n *

Append to the toString a Collection.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param coll the Collection to add to the\n * toString, not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, Collection coll) {\n buffer.append(coll);\n }\n\n /**\n *

Append to the toString a Map.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param map the Map to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, Map map) {\n buffer.append(map);\n }\n\n /**\n *

Append to the toString an Object\n * value, printing a summary of the Object.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, Object value) {\n buffer.append(summaryObjectStartText);\n buffer.append(getShortClassName(value.getClass()));\n buffer.append(summaryObjectEndText);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a long\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, long value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString a long\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, long value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString an int\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, int value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString an int\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, int value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a short\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, short value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString a short\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, short value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a byte\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, byte value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString a byte\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, byte value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a char\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, char value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString a char\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, char value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a double\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, double value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString a double\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, double value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a float\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, float value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString a float\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, float value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a boolean\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, boolean value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString a boolean\n * value.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, boolean value) {\n buffer.append(value);\n }\n\n /**\n *

Append to the toString an Object\n * array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, Object[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString the detail of an\n * Object array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, Object[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n Object item = array[i];\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n if (item == null) {\n appendNullText(buffer, fieldName);\n } else {\n appendInternal(buffer, fieldName, item, arrayContentDetail);\n }\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

Append to the toString the detail of an array type.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n * @since 2.0\n */\n protected void reflectionAppendArrayDetail(StringBuffer buffer, String fieldName, Object array) {\n buffer.append(arrayStart);\n int length = Array.getLength(array);\n for (int i = 0; i < length; i++) {\n Object item = Array.get(array, i);\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n if (item == null) {\n appendNullText(buffer, fieldName);\n } else {\n appendInternal(buffer, fieldName, item, arrayContentDetail);\n }\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

Append to the toString a summary of an\n * Object array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, Object[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a long\n * array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, long[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString the detail of a\n * long array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, long[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

Append to the toString a summary of a\n * long array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, long[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString an int\n * array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, int[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString the detail of an\n * int array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, int[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

Append to the toString a summary of an\n * int array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, int[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a short\n * array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, short[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString the detail of a\n * short array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, short[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

Append to the toString a summary of a\n * short array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, short[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a byte\n * array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, byte[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString the detail of a\n * byte array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, byte[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

Append to the toString a summary of a\n * byte array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, byte[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a char\n * array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, char[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString the detail of a\n * char array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, char[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

Append to the toString a summary of a\n * char array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, char[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a double\n * array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString the detail of a\n * double array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, double[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

Append to the toString a summary of a\n * double array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, double[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a float\n * array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, float[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString the detail of a\n * float array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, float[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

Append to the toString a summary of a\n * float array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, float[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString a boolean\n * array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, boolean[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

Append to the toString the detail of a\n * boolean array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, boolean[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

Append to the toString a summary of a\n * boolean array.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, boolean[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Append to the toString the class name.

\n *\n * @param buffer the StringBuffer to populate\n * @param object the Object whose name to output\n */\n protected void appendClassName(StringBuffer buffer, Object object) {\n if (useClassName && object != null) {\n register(object);\n if (useShortClassName) {\n buffer.append(getShortClassName(object.getClass()));\n } else {\n buffer.append(object.getClass().getName());\n }\n }\n }\n\n /**\n *

Append the {@link System#identityHashCode(java.lang.Object)}.

\n *\n * @param buffer the StringBuffer to populate\n * @param object the Object whose id to output\n */\n protected void appendIdentityHashCode(StringBuffer buffer, Object object) {\n if (this.isUseIdentityHashCode() && object != null) {\n register(object);\n buffer.append('@');\n buffer.append(Integer.toHexString(System.identityHashCode(object)));\n }\n }\n\n /**\n *

Append to the toString the content start.

\n *\n * @param buffer the StringBuffer to populate\n */\n protected void appendContentStart(StringBuffer buffer) {\n buffer.append(contentStart);\n }\n\n /**\n *

Append to the toString the content end.

\n *\n * @param buffer the StringBuffer to populate\n */\n protected void appendContentEnd(StringBuffer buffer) {\n buffer.append(contentEnd);\n }\n\n /**\n *

Append to the toString an indicator for null.

\n *\n *

The default indicator is '<null>'.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n */\n protected void appendNullText(StringBuffer buffer, String fieldName) {\n buffer.append(nullText);\n }\n\n /**\n *

Append to the toString the field separator.

\n *\n * @param buffer the StringBuffer to populate\n */\n protected void appendFieldSeparator(StringBuffer buffer) {\n buffer.append(fieldSeparator);\n }\n\n /**\n *

Append to the toString the field start.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n */\n protected void appendFieldStart(StringBuffer buffer, String fieldName) {\n if (useFieldNames && fieldName != null) {\n buffer.append(fieldName);\n buffer.append(fieldNameValueSeparator);\n }\n }\n\n /**\n *

Append to the toString the field end.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n */\n protected void appendFieldEnd(StringBuffer buffer, String fieldName) {\n appendFieldSeparator(buffer);\n }\n\n /**\n *

Append to the toString a size summary.

\n *\n *

The size summary is used to summarize the contents of\n * Collections, Maps and arrays.

\n *\n *

The output consists of a prefix, the passed in size\n * and a suffix.

\n *\n *

The default format is '<size=n>'.

\n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param size the size to append\n */\n protected void appendSummarySize(StringBuffer buffer, String fieldName, int size) {\n buffer.append(sizeStartText);\n buffer.append(size);\n buffer.append(sizeEndText);\n }\n\n /**\n *

Is this field to be output in full detail.

\n *\n *

This method converts a detail request into a detail level.\n * The calling code may request full detail (true),\n * but a subclass might ignore that and always return\n * false. The calling code may pass in\n * null indicating that it doesn't care about\n * the detail level. In this case the default detail level is\n * used.

\n *\n * @param fullDetailRequest the detail level requested\n * @return whether full detail is to be shown\n */\n protected boolean isFullDetail(Boolean fullDetailRequest) {\n if (fullDetailRequest == null) {\n return defaultFullDetail;\n }\n return fullDetailRequest;\n }\n\n /**\n *

Gets the short class name for a class.

\n *\n *

The short class name is the classname excluding\n * the package name.

\n *\n * @param cls the Class to get the short name of\n * @return the short name\n */\n protected String getShortClassName(Class cls) {\n return ClassUtils.getShortClassName(cls);\n }\n // Setters and getters for the customizable parts of the style\n // These methods are not expected to be overridden, except to make public\n // (They are not public so that immutable subclasses can be written)\n //---------------------------------------------------------------------\n\n /**\n *

Gets whether to use the class name.

\n *\n * @return the current useClassName flag\n */\n protected boolean isUseClassName() {\n return useClassName;\n }\n\n /**\n *

Sets whether to use the class name.

\n *\n * @param useClassName the new useClassName flag\n */\n protected void setUseClassName(boolean useClassName) {\n this.useClassName = useClassName;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets whether to output short or long class names.

\n *\n * @return the current useShortClassName flag\n * @since 2.0\n */\n protected boolean isUseShortClassName() {\n return useShortClassName;\n }\n\n /**\n *

Gets whether to output short or long class names.

\n *\n * @return the current shortClassName flag\n * @deprecated Use {@link #isUseShortClassName()}\n * Method will be removed in Commons Lang 3.0.\n */\n protected boolean isShortClassName() {\n return useShortClassName;\n }\n\n /**\n *

Sets whether to output short or long class names.

\n *\n * @param useShortClassName the new useShortClassName flag\n * @since 2.0\n */\n protected void setUseShortClassName(boolean useShortClassName) {\n this.useShortClassName = useShortClassName;\n }\n\n /**\n *

Sets whether to output short or long class names.

\n *\n * @param shortClassName the new shortClassName flag\n * @deprecated Use {@link #setUseShortClassName(boolean)}\n * Method will be removed in Commons Lang 3.0.\n */\n protected void setShortClassName(boolean shortClassName) {\n this.useShortClassName = shortClassName;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets whether to use the identity hash code.

\n *\n * @return the current useIdentityHashCode flag\n */\n protected boolean isUseIdentityHashCode() {\n return useIdentityHashCode;\n }\n\n /**\n *

Sets whether to use the identity hash code.

\n *\n * @param useIdentityHashCode the new useIdentityHashCode flag\n */\n protected void setUseIdentityHashCode(boolean useIdentityHashCode) {\n this.useIdentityHashCode = useIdentityHashCode;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets whether to use the field names passed in.

\n *\n * @return the current useFieldNames flag\n */\n protected boolean isUseFieldNames() {\n return useFieldNames;\n }\n\n /**\n *

Sets whether to use the field names passed in.

\n *\n * @param useFieldNames the new useFieldNames flag\n */\n protected void setUseFieldNames(boolean useFieldNames) {\n this.useFieldNames = useFieldNames;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets whether to use full detail when the caller doesn't\n * specify.

\n *\n * @return the current defaultFullDetail flag\n */\n protected boolean isDefaultFullDetail() {\n return defaultFullDetail;\n }\n\n /**\n *

Sets whether to use full detail when the caller doesn't\n * specify.

\n *\n * @param defaultFullDetail the new defaultFullDetail flag\n */\n protected void setDefaultFullDetail(boolean defaultFullDetail) {\n this.defaultFullDetail = defaultFullDetail;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets whether to output array content detail.

\n *\n * @return the current array content detail setting\n */\n protected boolean isArrayContentDetail() {\n return arrayContentDetail;\n }\n\n /**\n *

Sets whether to output array content detail.

\n *\n * @param arrayContentDetail the new arrayContentDetail flag\n */\n protected void setArrayContentDetail(boolean arrayContentDetail) {\n this.arrayContentDetail = arrayContentDetail;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets the array start text.

\n *\n * @return the current array start text\n */\n protected String getArrayStart() {\n return arrayStart;\n }\n\n /**\n *

Sets the array start text.

\n *\n *

null is accepted, but will be converted to\n * an empty String.

\n *\n * @param arrayStart the new array start text\n */\n protected void setArrayStart(String arrayStart) {\n if (arrayStart == null) {\n arrayStart = \"\";\n }\n this.arrayStart = arrayStart;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets the array end text.

\n *\n * @return the current array end text\n */\n protected String getArrayEnd() {\n return arrayEnd;\n }\n\n /**\n *

Sets the array end text.

\n *\n *

null is accepted, but will be converted to\n * an empty String.

\n *\n * @param arrayEnd the new array end text\n */\n protected void setArrayEnd(String arrayEnd) {\n if (arrayEnd == null) {\n arrayEnd = \"\";\n }\n this.arrayEnd = arrayEnd;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets the array separator text.

\n *\n * @return the current array separator text\n */\n protected String getArraySeparator() {\n return arraySeparator;\n }\n\n /**\n *

Sets the array separator text.

\n *\n *

null is accepted, but will be converted to\n * an empty String.

\n *\n * @param arraySeparator the new array separator text\n */\n protected void setArraySeparator(String arraySeparator) {\n if (arraySeparator == null) {\n arraySeparator = \"\";\n }\n this.arraySeparator = arraySeparator;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets the content start text.

\n *\n * @return the current content start text\n */\n protected String getContentStart() {\n return contentStart;\n }\n\n /**\n *

Sets the content start text.

\n *\n *

null is accepted, but will be converted to\n * an empty String.

\n *\n * @param contentStart the new content start text\n */\n protected void setContentStart(String contentStart) {\n if (contentStart == null) {\n contentStart = \"\";\n }\n this.contentStart = contentStart;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets the content end text.

\n *\n * @return the current content end text\n */\n protected String getContentEnd() {\n return contentEnd;\n }\n\n /**\n *

Sets the content end text.

\n *\n *

null is accepted, but will be converted to\n * an empty String.

\n *\n * @param contentEnd the new content end text\n */\n protected void setContentEnd(String contentEnd) {\n if (contentEnd == null) {\n contentEnd = \"\";\n }\n this.contentEnd = contentEnd;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets the field name value separator text.

\n *\n * @return the current field name value separator text\n */\n protected String getFieldNameValueSeparator() {\n return fieldNameValueSeparator;\n }\n\n /**\n *

Sets the field name value separator text.

\n *\n *

null is accepted, but will be converted to\n * an empty String.

\n *\n * @param fieldNameValueSeparator the new field name value separator text\n */\n protected void setFieldNameValueSeparator(String fieldNameValueSeparator) {\n if (fieldNameValueSeparator == null) {\n fieldNameValueSeparator = \"\";\n }\n this.fieldNameValueSeparator = fieldNameValueSeparator;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets the field separator text.

\n *\n * @return the current field separator text\n */\n protected String getFieldSeparator() {\n return fieldSeparator;\n }\n\n /**\n *

Sets the field separator text.

\n *\n *

null is accepted, but will be converted to\n * an empty String.

\n *\n * @param fieldSeparator the new field separator text\n */\n protected void setFieldSeparator(String fieldSeparator) {\n if (fieldSeparator == null) {\n fieldSeparator = \"\";\n }\n this.fieldSeparator = fieldSeparator;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets whether the field separator should be added at the start\n * of each buffer.

\n *\n * @return the fieldSeparatorAtStart flag\n * @since 2.0\n */\n protected boolean isFieldSeparatorAtStart() {\n return fieldSeparatorAtStart;\n }\n\n /**\n *

Sets whether the field separator should be added at the start\n * of each buffer.

\n *\n * @param fieldSeparatorAtStart the fieldSeparatorAtStart flag\n * @since 2.0\n */\n protected void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) {\n this.fieldSeparatorAtStart = fieldSeparatorAtStart;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets whether the field separator should be added at the end\n * of each buffer.

\n *\n * @return fieldSeparatorAtEnd flag\n * @since 2.0\n */\n protected boolean isFieldSeparatorAtEnd() {\n return fieldSeparatorAtEnd;\n }\n\n /**\n *

Sets whether the field separator should be added at the end\n * of each buffer.

\n *\n * @param fieldSeparatorAtEnd the fieldSeparatorAtEnd flag\n * @since 2.0\n */\n protected void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) {\n this.fieldSeparatorAtEnd = fieldSeparatorAtEnd;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets the text to output when null found.

\n *\n * @return the current text to output when null found\n */\n protected String getNullText() {\n return nullText;\n }\n\n /**\n *

Sets the text to output when null found.

\n *\n *

null is accepted, but will be converted to\n * an empty String.

\n *\n * @param nullText the new text to output when null found\n */\n protected void setNullText(String nullText) {\n if (nullText == null) {\n nullText = \"\";\n }\n this.nullText = nullText;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets the start text to output when a Collection,\n * Map or array size is output.

\n *\n *

This is output before the size value.

\n *\n * @return the current start of size text\n */\n protected String getSizeStartText() {\n return sizeStartText;\n }\n\n /**\n *

Sets the start text to output when a Collection,\n * Map or array size is output.

\n *\n *

This is output before the size value.

\n *\n *

null is accepted, but will be converted to\n * an empty String.

\n *\n * @param sizeStartText the new start of size text\n */\n protected void setSizeStartText(String sizeStartText) {\n if (sizeStartText == null) {\n sizeStartText = \"\";\n }\n this.sizeStartText = sizeStartText;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets the end text to output when a Collection,\n * Map or array size is output.

\n *\n *

This is output after the size value.

\n *\n * @return the current end of size text\n */\n protected String getSizeEndText() {\n return sizeEndText;\n }\n\n /**\n *

Sets the end text to output when a Collection,\n * Map or array size is output.

\n *\n *

This is output after the size value.

\n *\n *

null is accepted, but will be converted to\n * an empty String.

\n *\n * @param sizeEndText the new end of size text\n */\n protected void setSizeEndText(String sizeEndText) {\n if (sizeEndText == null) {\n sizeEndText = \"\";\n }\n this.sizeEndText = sizeEndText;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets the start text to output when an Object is\n * output in summary mode.

\n *\n *

This is output before the size value.

\n *\n * @return the current start of summary text\n */\n protected String getSummaryObjectStartText() {\n return summaryObjectStartText;\n }\n\n /**\n *

Sets the start text to output when an Object is\n * output in summary mode.

\n *\n *

This is output before the size value.

\n *\n *

null is accepted, but will be converted to\n * an empty String.

\n *\n * @param summaryObjectStartText the new start of summary text\n */\n protected void setSummaryObjectStartText(String summaryObjectStartText) {\n if (summaryObjectStartText == null) {\n summaryObjectStartText = \"\";\n }\n this.summaryObjectStartText = summaryObjectStartText;\n }\n //---------------------------------------------------------------------\n\n /**\n *

Gets the end text to output when an Object is\n * output in summary mode.

\n *\n *

This is output after the size value.

\n *\n * @return the current end of summary text\n */\n protected String getSummaryObjectEndText() {\n return summaryObjectEndText;\n }\n\n /**\n *

Sets the end text to output when an Object is\n * output in summary mode.

\n *\n *

This is output after the size value.

\n *\n *

null is accepted, but will be converted to\n * an empty String.

\n *\n * @param summaryObjectEndText the new end of summary text\n */\n protected void setSummaryObjectEndText(String summaryObjectEndText) {\n if (summaryObjectEndText == null) {\n summaryObjectEndText = \"\";\n }\n this.summaryObjectEndText = summaryObjectEndText;\n }\n //----------------------------------------------------------------------------\n\n /**\n *

Default ToStringStyle.

\n *\n *

This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.

\n */\n private static final class DefaultToStringStyle extends ToStringStyle {\n /**\n * Required for serialization support.\n *\n * @see java.io.Serializable\n */\n private static final long serialVersionUID = 1L;\n\n /**\n *

Constructor.

\n *\n *

Use the static constant rather than instantiating.

\n */\n DefaultToStringStyle() {\n super();\n }\n\n /**\n *

Ensure Singleton after serialization.

\n *\n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.DEFAULT_STYLE;\n }\n }\n //----------------------------------------------------------------------------\n\n /**\n *

ToStringStyle that does not print out\n * the field names.

\n *\n *

This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.\n */\n private static final class NoFieldNameToStringStyle extends ToStringStyle {\n private static final long serialVersionUID = 1L;\n\n /**\n *

Constructor.

\n *\n *

Use the static constant rather than instantiating.

\n */\n NoFieldNameToStringStyle() {\n super();\n this.setUseFieldNames(false);\n }\n\n /**\n *

Ensure Singleton after serialization.

\n *\n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.NO_FIELD_NAMES_STYLE;\n }\n }\n //----------------------------------------------------------------------------\n\n /**\n *

ToStringStyle that prints out the short\n * class name and no identity hashcode.

\n *\n *

This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.

\n */\n private static final class ShortPrefixToStringStyle extends ToStringStyle {\n private static final long serialVersionUID = 1L;\n\n /**\n *

Constructor.

\n *\n *

Use the static constant rather than instantiating.

\n */\n ShortPrefixToStringStyle() {\n super();\n this.setUseShortClassName(true);\n this.setUseIdentityHashCode(false);\n }\n\n /**\n *

Ensure Singleton after serialization.

\n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.SHORT_PREFIX_STYLE;\n }\n }\n\n /**\n *

ToStringStyle that does not print out the\n * classname, identity hashcode, content start or field name.

\n *\n *

This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.

\n */\n private static final class SimpleToStringStyle extends ToStringStyle {\n private static final long serialVersionUID = 1L;\n\n /**\n *

Constructor.

\n *\n *

Use the static constant rather than instantiating.

\n */\n SimpleToStringStyle() {\n super();\n this.setUseClassName(false);\n this.setUseIdentityHashCode(false);\n this.setUseFieldNames(false);\n this.setContentStart(\"\");\n this.setContentEnd(\"\");\n }\n\n /**\n *

Ensure Singleton after serialization.

\n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.SIMPLE_STYLE;\n }\n }\n //----------------------------------------------------------------------------\n\n /**\n *

ToStringStyle that outputs on multiple lines.

\n *\n *

This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.

\n */\n private static final class MultiLineToStringStyle extends ToStringStyle {\n private static final long serialVersionUID = 1L;\n\n /**\n *

Constructor.

\n *\n *

Use the static constant rather than instantiating.

\n */\n MultiLineToStringStyle() {\n super();\n String separator = getSystemProperty(\"line.separator\");\n this.setContentStart(\"[\");\n this.setFieldSeparator(separator + \" \");\n this.setFieldSeparatorAtStart(true);\n this.setContentEnd(separator + \"]\");\n }\n\n private String getSystemProperty(final String property) {\n try {\n return System.getProperty(property);\n } catch (SecurityException ex) {\n // we are not allowed to look at this property\n System.err.println(\"Caught a SecurityException reading the system property '\" + property + \"'; the SystemUtils property value will default to null.\");\n return null;\n }\n }\n\n /**\n *

Ensure Singleton after serialization.

\n *\n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.MULTI_LINE_STYLE;\n }\n }\n}", "file_name": "ToStringStyle.java", "human_label": "Append the detail of an int array to the buffer, starting with arrayStart and ending with arrayEnd, and separating with arraySeparator.", "level": "class_runnable", "lineno": "962", "name": "appendDetail", "oracle_context": "{ \"apis\" : \"[append]\", \"classes\" : \"[]\", \"vars\" : \"[length, arrayStart, arraySeparator, arrayEnd]\" }", "package": "net.hasor.utils.builder", "project": "hasor-master" }, { "_id": "636766fe1a6d9265ec017834", "all_context": "{ \"class_level\" : \"import com.alibaba.fastjson.JSON;\\nimport net.hasor.core.Singleton;\\nimport net.hasor.dataql.UdfSourceAssembly;\\nimport net.hasor.utils.StringUtils;\\nimport net.hasor.web.Invoker;\\nimport net.hasor.web.invoker.HttpParameters;\\nimport javax.servlet.http.Cookie;\\nimport javax.servlet.http.HttpServletResponse;\\nimport javax.servlet.http.HttpSession;\\nimport java.util.*;\\ncookieMap();\\ncookieArrayMap();\\ngetCookie(String cookieName);\\ngetCookieArray(String cookieName);\\ntempCookie(String cookieName,String value);\\ntempCookieAll(Map cookieMap);\\nstoreCookie(String cookieName,String value,int maxAge);\\nstoreCookieAll(Map cookieMap,int maxAge);\\nremoveCookie(String cookieName);\\nheaderMap();\\nheaderArrayMap();\\ngetHeader(String headerName);\\ngetHeaderArray(String headerName);\\nsetHeader(String headerName,String value);\\nsetHeaderAll(Map headerMap);\\naddHeader(String headerName,String value);\\naddHeaderAll(Map headerMap);\\nservletSession();\\nsessionKeys();\\ngetSession(String key);\\nsetSession(String key,Object newValue);\\nremoveSession(String key);\\ncleanSession();\\nsessionInvalidate();\\nsessionId();\\nsessionLastAccessedTime();\\njsonBody();\\n\", \"repo_level\" : \"public interface UdfSourceAssembly {default Supplier getSupplier(Class targetType,Finder finder);\\ndefault Predicate getPredicate(Class targetType);\\npublic Object[] allParams();\\ndefault Supplier> getUdfResource(Finder finder);\\npublic Class annotationType();\\npublic String value();\\npublic Object call(Hints readOnly,Object values);\\npublic Object call(Hints readOnly,Object values);\\n }\\npublic interface StringUtils {static boolean isEmpty(String str);\\nstatic boolean isNotEmpty(String str);\\nstatic boolean isBlank(String str);\\nstatic boolean isNotBlank(String str);\\nstatic String trim(String str);\\nstatic String trimToNull(String str);\\nstatic String trimToEmpty(String str);\\nstatic String strip(String str);\\nstatic String stripToNull(String str);\\nstatic String stripToEmpty(String str);\\nstatic String strip(String str,String stripChars);\\nstatic String stripStart(String str,String stripChars);\\nstatic String stripEnd(String str,String stripChars);\\nstatic String[] stripAll(String[] strs);\\nstatic String[] stripAll(String[] strs,String stripChars);\\nstatic boolean equals(String str1,String str2);\\nstatic boolean equalsIgnoreCase(String str1,String str2);\\nstatic int indexOf(String str,char searchChar);\\nstatic int indexOf(String str,char searchChar,int startPos);\\nstatic int indexOf(String str,String searchStr);\\nstatic int ordinalIndexOf(String str,String searchStr,int ordinal);\\nstatic int indexOf(String str,String searchStr,int startPos);\\nstatic int indexOfIgnoreCase(String str,String searchStr);\\nstatic int indexOfIgnoreCase(String str,String searchStr,int startPos);\\nstatic int lastIndexOf(String str,char searchChar);\\nstatic int lastIndexOf(String str,char searchChar,int startPos);\\nstatic int lastIndexOf(String str,String searchStr);\\nstatic int lastOrdinalIndexOf(String str,String searchStr,int ordinal);\\nstatic int lastIndexOf(String str,String searchStr,int startPos);\\nstatic int lastIndexOfIgnoreCase(String str,String searchStr);\\nstatic int lastIndexOfIgnoreCase(String str,String searchStr,int startPos);\\nstatic boolean contains(String str,char searchChar);\\nstatic boolean contains(String str,String searchStr);\\nstatic boolean containsIgnoreCase(String str,String searchStr);\\nstatic int indexOfAny(String str,char[] searchChars);\\nstatic int indexOfAny(String str,String searchChars);\\nstatic boolean containsAny(String str,char[] searchChars);\\nstatic boolean containsAny(String str,String searchChars);\\nstatic int indexOfAnyBut(String str,char[] searchChars);\\nstatic int indexOfAnyBut(String str,String searchChars);\\nstatic boolean containsOnly(String str,char[] valid);\\nstatic boolean containsOnly(String str,String validChars);\\nstatic boolean containsNone(String str,char[] searchChars);\\nstatic boolean containsNone(String str,String invalidChars);\\nstatic int indexOfAny(String str,String[] searchStrs);\\nstatic int lastIndexOfAny(String str,String[] searchStrs);\\nstatic String substring(String str,int start);\\nstatic String substring(String str,int start,int end);\\nstatic String left(String str,int len);\\nstatic String right(String str,int len);\\nstatic String mid(String str,int pos,int len);\\nstatic String substringBefore(String str,String separator);\\nstatic String substringAfter(String str,String separator);\\nstatic String substringBeforeLast(String str,String separator);\\nstatic String substringAfterLast(String str,String separator);\\nstatic String substringBetween(String str,String tag);\\nstatic String substringBetween(String str,String open,String close);\\nstatic String[] substringsBetween(String str,String open,String close);\\nstatic String[] splitKeep(String str,char separatorChar);\\nstatic String[] splitKeep(String str,String separatorStr);\\nstatic String[] split(String str);\\nstatic String[] split(String str,char separatorChar);\\nstatic String[] split(String str,String separatorChars);\\nstatic String[] split(String str,String separatorChars,int max);\\nstatic String[] splitByWholeSeparator(String str,String separator);\\nstatic String[] splitByWholeSeparator(String str,String separator,int max);\\nstatic String[] splitByWholeSeparatorPreserveAllTokens(String str,String separator);\\nstatic String[] splitByWholeSeparatorPreserveAllTokens(String str,String separator,int max);\\nstatic String[] splitPreserveAllTokens(String str);\\nstatic String[] splitPreserveAllTokens(String str,char separatorChar);\\nstatic String[] splitPreserveAllTokens(String str,String separatorChars);\\nstatic String[] splitPreserveAllTokens(String str,String separatorChars,int max);\\nstatic String[] splitByCharacterType(String str);\\nstatic String[] splitByCharacterTypeCamelCase(String str);\\nstatic String join(Object[] array);\\nstatic String join(Object[] array,char separator);\\nstatic String join(Object[] array,char separator,int startIndex,int endIndex);\\nstatic String join(Object[] array,String separator);\\nstatic String join(Object[] array,String separator,int startIndex,int endIndex);\\nstatic String deleteWhitespace(String str);\\nstatic String removeStart(String str,String remove);\\nstatic String removeStartIgnoreCase(String str,String remove);\\nstatic String removeEnd(String str,String remove);\\nstatic String removeEndIgnoreCase(String str,String remove);\\nstatic String remove(String str,String remove);\\nstatic String remove(String str,char remove);\\nstatic String replaceOnce(String text,String searchString,String replacement);\\nstatic String replace(String text,String searchString,String replacement);\\nstatic String replace(String text,String searchString,String replacement,int max);\\nstatic String replaceEach(String text,String[] searchList,String[] replacementList);\\nstatic String replaceEachRepeatedly(String text,String[] searchList,String[] replacementList);\\nstatic String replaceChars(String str,char searchChar,char replaceChar);\\nstatic String replaceChars(String str,String searchChars,String replaceChars);\\nstatic String overlay(String str,String overlay,int start,int end);\\nstatic String chomp(String str);\\nstatic String chomp(String str,String separator);\\nstatic String chop(String str);\\nstatic String repeat(char character,int repeat);\\nstatic String repeat(String str,int repeat);\\nstatic String repeat(String str,String separator,int repeat);\\nstatic String rightPad(String str,int size);\\nstatic String rightPad(String str,int size,char padChar);\\nstatic String rightPad(String str,int size,String padStr);\\nstatic String leftPad(String str,int size);\\nstatic String leftPad(String str,int size,char padChar);\\nstatic String leftPad(String str,int size,String padStr);\\nstatic int length(String str);\\nstatic String center(String str,int size);\\nstatic String center(String str,int size,char padChar);\\nstatic String center(String str,int size,String padStr);\\nstatic String upperCase(String str);\\nstatic String upperCase(String str,Locale locale);\\nstatic String lowerCase(String str);\\nstatic String lowerCase(String str,Locale locale);\\nstatic String capitalize(String str);\\nstatic String uncapitalize(String str);\\nstatic String swapCase(String str);\\nstatic int countMatches(String str,String sub);\\nstatic boolean isAlpha(String str);\\nstatic boolean isAlphaSpace(String str);\\nstatic boolean isAlphanumeric(String str);\\nstatic boolean isAlphanumericSpace(String str);\\nstatic boolean isAsciiPrintable(String str);\\nstatic boolean isNumeric(String str);\\nstatic boolean isNumericSpace(String str);\\nstatic boolean isWhitespace(String str);\\nstatic boolean isAllLowerCase(String str);\\nstatic boolean isAllUpperCase(String str);\\nstatic String defaultString(String str);\\nstatic String defaultString(String str,String defaultStr);\\nstatic String defaultIfBlank(String str,String defaultStr);\\nstatic String defaultIfEmpty(String str,String defaultStr);\\nstatic String reverse(String str);\\nstatic String reverseDelimited(String str,char separatorChar);\\nstatic String abbreviate(String str,int maxWidth);\\nstatic String abbreviate(String str,int offset,int maxWidth);\\nstatic String abbreviateMiddle(String str,String middle,int length);\\nstatic String difference(String str1,String str2);\\nstatic int indexOfDifference(String str1,String str2);\\nstatic int indexOfDifference(String[] strs);\\nstatic String getCommonPrefix(String[] strs);\\nstatic int getLevenshteinDistance(String s,String t);\\nstatic boolean startsWith(String str,String prefix);\\nstatic boolean startsWithIgnoreCase(String str,String prefix);\\nstatic boolean startsWithAny(String string,String[] searchStrings);\\nstatic boolean endsWith(String str,String suffix);\\nstatic boolean endsWithIgnoreCase(String str,String suffix);\\nstatic String normalizeSpace(String str);\\nstatic boolean endsWithAny(String string,String[] searchStrings);\\nstatic String firstCharToUpperCase(String value);\\nstatic String firstCharToLowerCase(String value);\\nstatic boolean equalsBlankIgnoreCase(String str1,String str2);\\nstatic String quote(String input);\\nstatic void quote(Appendable buffer,String input);\\nstatic String toString(Object object);\\n }\\npublic interface Invoker {public AppContext getAppContext();\\npublic HttpServletRequest getHttpRequest();\\npublic HttpServletResponse getHttpResponse();\\npublic Future asyncExecute(EFunction consumer,Executor executor);\\ndefault Future asyncExecute(EFunction consumer);\\npublic String contentType();\\npublic void contentType(String contentType);\\npublic Mapping ownerMapping();\\npublic String getJsonBodyString();\\ndefault Set keySet();\\ndefault T fillForm(Class formType);\\npublic T fillForm(Class formType,T bean);\\ndefault Object get(String key);\\ndefault void remove(String key);\\ndefault void put(String key,Object value);\\npublic boolean isLockKey(String key);\\npublic void lockKey(String key);\\ndefault String getRequestPath();\\ndefault void forEach(BiConsumer action);\\ndefault void putIfAbsent(String key,Object value);\\ndefault Object getOrDefault(String key,Object defaultValue);\\ndefault V getOrMap(String key,Function defaultValue);\\ndefault void computeIfAbsent(String key,Function mappingFunction);\\n }\\npublic interface HttpParameters {static T executeWorker(Invoker invoker,ESupplier worker);\\nstatic Map cookieMap();\\nstatic Map> cookieArrayMap();\\nstatic boolean clearReplaceCookieArrayMap(Map newCookie);\\nstatic boolean mergeReplaceCookieArrayMap(Map newCookie);\\nstatic boolean appendCookieArrayMap(Map newCookie);\\nstatic Invoker localInvoker();\\nstatic Map headerMap();\\nstatic Map> headerArrayMap();\\nstatic boolean clearReplaceHeaderArrayMap(Map newHeader);\\nstatic boolean mergeReplaceHeaderArrayMap(Map newHeader);\\nstatic boolean appendHeaderArrayMap(Map newHeader);\\nstatic Map queryMap();\\nstatic Map> queryArrayMap();\\nstatic boolean clearReplaceQueryArrayMap(Map newQuery);\\nstatic boolean mergeReplaceQueryArrayMap(Map newQuery);\\nstatic boolean appendQueryArrayMap(Map newQuery);\\nstatic Map pathMap();\\nstatic Map> pathArrayMap();\\nstatic boolean clearReplacePathArrayMap(Map newPath);\\nstatic boolean mergeReplacePathArrayMap(Map newPath);\\nstatic boolean appendPathArrayMap(Map newPath);\\nstatic Map requestMap();\\nstatic Map> requestArrayMap();\\nstatic boolean clearReplaceRequestArrayMap(Map newRequestParam);\\nstatic boolean mergeReplaceRequestArrayMap(Map newRequestParam);\\nstatic boolean appendRequestArrayMap(Map newRequestParam);\\n }\\n\" }", "class_name": "WebUdfSource", "code": "public static String sessionId(){\n HttpSession httpSession=servletSession();\n if (httpSession == null) {\n return null;\n }\n return httpSession.getId();\n}\n", "docstring": "/** \n * Session ID. \n */\n", "end_lineno": "280", "file_content": "/*\n * Copyright 2008-2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.dataql.fx.web;\nimport com.alibaba.fastjson.JSON;\nimport net.hasor.core.Singleton;\nimport net.hasor.dataql.UdfSourceAssembly;\nimport net.hasor.utils.StringUtils;\nimport net.hasor.web.Invoker;\nimport net.hasor.web.invoker.HttpParameters;\n\nimport javax.servlet.http.Cookie;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\nimport java.util.*;\n\n/**\n * Web 函数库。函数库引入 import 'net.hasor.dataql.fx.web.WebUdfSource' as webData;\n * @author 赵永春 (zyc@hasor.net)\n * @version : 2020-03-29\n */\n@Singleton\npublic class WebUdfSource implements UdfSourceAssembly {\n /** jsonBody */\n public static Object jsonBody() {\n Invoker invoker = HttpParameters.localInvoker();\n if (invoker == null) {\n return null;\n }\n return JSON.parse(invoker.getJsonBodyString());\n }\n // --------------------------------------------------------------------------------------------\n\n /** cookieMap */\n public static Map cookieMap() {\n return HttpParameters.cookieMap();\n }\n\n /** cookieMap,Value是数组 */\n public static Map> cookieArrayMap() {\n return HttpParameters.cookieArrayMap();\n }\n\n /** 获取Cookie */\n public static String getCookie(String cookieName) {\n if (StringUtils.isBlank(cookieName)) {\n return null;\n }\n return cookieMap().get(cookieName);\n }\n\n /** 获取Cookie数组形态 */\n public static List getCookieArray(String cookieName) {\n if (StringUtils.isBlank(cookieName)) {\n return null;\n }\n return cookieArrayMap().get(cookieName);\n }\n\n /** 临时 Cookie。临时 Cookie 的 MaxAge = -1 */\n public static boolean tempCookie(String cookieName, String value) {\n HttpServletResponse httpResponse = HttpParameters.localInvoker().getHttpResponse();\n Cookie cookie = new Cookie(cookieName, value);\n cookie.setMaxAge(-1);\n httpResponse.addCookie(cookie);\n return true;\n }\n\n /** 批量设置临时 Cookie。临时 Cookie 的 MaxAge = -1 */\n public static boolean tempCookieAll(Map cookieMap) {\n if (cookieMap != null) {\n cookieMap.forEach(WebUdfSource::tempCookie);\n return true;\n }\n return false;\n }\n\n /** 存储 Cookie */\n public static boolean storeCookie(String cookieName, String value, int maxAge) {\n HttpServletResponse httpResponse = HttpParameters.localInvoker().getHttpResponse();\n Cookie cookie = new Cookie(cookieName, value);\n if (maxAge <= 0) {\n maxAge = -1;\n }\n cookie.setMaxAge(maxAge);\n httpResponse.addCookie(cookie);\n return true;\n }\n\n /** 批量设置 Cookie */\n public static boolean storeCookieAll(Map cookieMap, int maxAge) {\n if (cookieMap != null) {\n cookieMap.forEach((cookieName, value) -> {\n storeCookie(cookieName, value, maxAge);\n });\n return true;\n }\n return false;\n }\n\n /** 删除 Cookie */\n public static boolean removeCookie(String cookieName) {\n HttpServletResponse httpResponse = HttpParameters.localInvoker().getHttpResponse();\n Cookie cookie = new Cookie(cookieName, \"\");\n cookie.setMaxAge(0);\n httpResponse.addCookie(cookie);\n return true;\n }\n // --------------------------------------------------------------------------------------------\n\n /** headerMap */\n public static Map headerMap() {\n return HttpParameters.headerMap();\n }\n\n /** headerMap,Value是数组 */\n public static Map> headerArrayMap() {\n return HttpParameters.headerArrayMap();\n }\n\n /** 获取 Header */\n public static String getHeader(String headerName) {\n if (StringUtils.isBlank(headerName)) {\n return null;\n }\n return headerMap().get(headerName);\n }\n\n /** 获取所有名字相同的 Header */\n public static List getHeaderArray(String headerName) {\n if (StringUtils.isBlank(headerName)) {\n return null;\n }\n return headerArrayMap().get(headerName);\n }\n\n /** 设置 Header */\n public static boolean setHeader(String headerName, String value) {\n if (StringUtils.isBlank(headerName)) {\n return false;\n }\n HttpParameters.localInvoker().getHttpResponse().setHeader(headerName, value);\n return true;\n }\n\n /** 批量设置 HeaderMap */\n public static boolean setHeaderAll(Map headerMap) {\n if (headerMap != null) {\n HttpServletResponse httpResponse = HttpParameters.localInvoker().getHttpResponse();\n headerMap.forEach(httpResponse::setHeader);\n return true;\n }\n return false;\n }\n\n /** 添加 Header */\n public static boolean addHeader(String headerName, String value) {\n if (StringUtils.isBlank(headerName)) {\n return false;\n }\n HttpParameters.localInvoker().getHttpResponse().addHeader(headerName, value);\n return true;\n }\n\n /** 批量添加 HeaderMap */\n public static boolean addHeaderAll(Map headerMap) {\n if (headerMap != null) {\n HttpServletResponse httpResponse = HttpParameters.localInvoker().getHttpResponse();\n headerMap.forEach(httpResponse::addHeader);\n return true;\n }\n return false;\n }\n // --------------------------------------------------------------------------------------------\n\n /** session */\n private static HttpSession servletSession() {\n Invoker invoker = HttpParameters.localInvoker();\n if (invoker == null) {\n return null;\n }\n return invoker.getHttpRequest().getSession();\n }\n\n /** sessionKeys */\n public static List sessionKeys() {\n HttpSession httpSession = servletSession();\n if (httpSession == null) {\n return Collections.emptyList();\n }\n Enumeration attributeNames = httpSession.getAttributeNames();\n List names = new ArrayList<>();\n while (attributeNames.hasMoreElements()) {\n names.add(attributeNames.nextElement());\n }\n return names;\n }\n\n /** 获取Session */\n public static Object getSession(String key) {\n if (StringUtils.isBlank(key)) {\n return null;\n }\n HttpSession httpSession = servletSession();\n if (httpSession == null) {\n return null;\n }\n return httpSession.getAttribute(key);\n }\n\n /** 设置Session */\n public static Object setSession(String key, Object newValue) {\n if (StringUtils.isBlank(key)) {\n return null;\n }\n HttpSession httpSession = servletSession();\n if (httpSession == null) {\n httpSession = HttpParameters.localInvoker().getHttpRequest().getSession(true);\n }\n Object oldValue = httpSession.getAttribute(key);\n httpSession.setAttribute(key, newValue);\n return oldValue;\n }\n\n /** 删除Session */\n public static boolean removeSession(String key) {\n if (StringUtils.isBlank(key)) {\n return false;\n }\n HttpSession httpSession = servletSession();\n if (httpSession == null) {\n return false;\n }\n httpSession.removeAttribute(key);\n return true;\n }\n\n /** 删除所有Key */\n public static boolean cleanSession() {\n HttpSession httpSession = servletSession();\n if (httpSession == null) {\n return false;\n }\n Enumeration attributeNames = httpSession.getAttributeNames();\n while (attributeNames.hasMoreElements()) {\n httpSession.removeAttribute(attributeNames.nextElement());\n }\n return true;\n }\n\n /** Invalidates this session then unbinds any objects bound to it. */\n public static boolean sessionInvalidate() {\n HttpSession httpSession = servletSession();\n if (httpSession == null) {\n return false;\n }\n httpSession.invalidate();\n return true;\n }\n\n /** Session ID. */\n public static String sessionId() {\n HttpSession httpSession = servletSession();\n if (httpSession == null) {\n return null;\n }\n return httpSession.getId();\n }\n\n /** 返回客户端发送与之关联的请求的最后一次时间. */\n public static long sessionLastAccessedTime() {\n HttpSession httpSession = servletSession();\n if (httpSession == null) {\n return 0;\n }\n return httpSession.getLastAccessedTime();\n }\n}\n", "file_name": "WebUdfSource.java", "human_label": "Return the servlet session id", "level": "plib_runnable", "lineno": "273", "name": "sessionId", "oracle_context": "{ \"apis\" : \"[servletSession, getId]\", \"classes\" : \"[HttpSession]\", \"vars\" : \"[]\" }", "package": "net.hasor.dataql.fx.web", "project": "hasor-master" }, { "_id": "636766ff1a6d9265ec01784b", "all_context": "{ \"class_level\" : \"import java.math.BigDecimal;\\nimport java.math.BigInteger;\\nNumberUtils();\\nstringToInt(String str,int defaultValue);\\ncreateNumber(String val);\\nisAllZeros(String s);\\ncreateFloat(String val);\\ncreateDouble(String val);\\ncreateInteger(String val);\\ncreateLong(String val);\\ncreateBigInteger(String val);\\ncreateBigDecimal(String val);\\nminimum(long a,long b,long c);\\nminimum(int a,int b,int c);\\nmaximum(long a,long b,long c);\\nmaximum(int a,int b,int c);\\ncompare(double lhs,double rhs);\\ncompare(float lhs,float rhs);\\nisDigits(String str);\\nisNumber(String str);\\nisByteType(Class targetType);\\nisShortType(Class targetType);\\nisIntType(Class targetType);\\nisLongType(Class targetType);\\nisFloatType(Class targetType);\\nisDoubleType(Class targetType);\\nstringToInt(String str);\\n\", \"repo_level\" : \"\" }", "class_name": "NumberUtils", "code": "public static boolean isDigits(String str){\n if ((str == null) || (str.length() == 0)) {\n return false;\n }\n for (int i=0; i < str.length(); i++) {\n if (!Character.isDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n}\n", "docstring": "/** \n *

Checks whether the String contains only digit characters.

Null and empty String will return false.

\n * @param str the String to check\n * @return true if str contains only unicode numeric\n */\n", "end_lineno": "581", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\n\n/**\n *

Provides extra functionality for Java Number classes.

\n *\n * @author Apache Software Foundation\n * @author Rand McNeely\n * @author Steve Downey\n * @author Eric Pugh\n * @author Phil Steitz\n * @since 1.0\n * @version $Id: NumberUtils.java 905636 2010-02-02 14:03:32Z niallp $\n */\npublic final class NumberUtils {\n // DEPRECATED CLASS !!!\n\n /**\n *

NumberUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as NumberUtils.stringToInt(\"6\");.

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public NumberUtils() {\n super();\n }\n //--------------------------------------------------------------------\n\n /**\n *

Convert a String to an int, returning\n * zero if the conversion fails.

\n *\n * @param str the string to convert\n * @return the int represented by the string, or zero if\n * conversion fails\n */\n public static int stringToInt(String str) {\n return stringToInt(str, 0);\n }\n\n /**\n *

Convert a String to an int, returning a\n * default value if the conversion fails.

\n *\n * @param str the string to convert\n * @param defaultValue the default value\n * @return the int represented by the string, or the default if conversion fails\n */\n public static int stringToInt(String str, int defaultValue) {\n try {\n return Integer.parseInt(str);\n } catch (NumberFormatException nfe) {\n return defaultValue;\n }\n }\n //--------------------------------------------------------------------\n // must handle Long, Float, Integer, Float, Short,\n // BigDecimal, BigInteger and Byte\n // useful methods:\n // Byte.decode(String)\n // Byte.valueOf(String,int radix)\n // Byte.valueOf(String)\n // Double.valueOf(String)\n // Float.valueOf(String)\n // new Float(String)\n // Integer.valueOf(String,int radix)\n // Integer.valueOf(String)\n // Integer.decode(String)\n // Integer.getInteger(String)\n // Integer.getInteger(String,int val)\n // Integer.getInteger(String,Integer val)\n // new Integer(String)\n // new Double(String)\n // new Byte(String)\n // new Long(String)\n // Long.getLong(String)\n // Long.getLong(String,int)\n // Long.getLong(String,Integer)\n // Long.valueOf(String,int)\n // Long.valueOf(String)\n // new Short(String)\n // Short.decode(String)\n // Short.valueOf(String,int)\n // Short.valueOf(String)\n // new BigDecimal(String)\n // new BigInteger(String)\n // new BigInteger(String,int radix)\n // Possible inputs:\n // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd\n // plus minus everything. Prolly more. A lot are not separable.\n\n /**\n *

Turns a string value into a java.lang.Number.

\n *\n *

First, the value is examined for a type qualifier on the end\n * ('f','F','d','D','l','L'). If it is found, it starts \n * trying to create successively larger types from the type specified\n * until one is found that can hold the value.

\n *\n *

If a type specifier is not found, it will check for a decimal point\n * and then try successively larger types from Integer to\n * BigInteger and from Float to\n * BigDecimal.

\n *\n *

If the string starts with 0x or -0x, it\n * will be interpreted as a hexadecimal integer. Values with leading\n * 0's will not be interpreted as octal.

\n *\n * @param val String containing a number\n * @return Number created from the string\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Number createNumber(String val) throws NumberFormatException {\n if (val == null) {\n return null;\n }\n if (val.length() == 0) {\n throw new NumberFormatException(\"\\\"\\\" is not a valid number.\");\n }\n if (val.length() == 1 && !Character.isDigit(val.charAt(0))) {\n throw new NumberFormatException(val + \" is not a valid number.\");\n }\n if (val.startsWith(\"--\")) {\n // this is protection for poorness in java.lang.BigDecimal.\n // it accepts this as a legal value, but it does not appear \n // to be in specification of class. OS X Java parses it to \n // a wrong value.\n return null;\n }\n if (val.startsWith(\"0x\") || val.startsWith(\"-0x\")) {\n return createInteger(val);\n }\n char lastChar = val.charAt(val.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = val.indexOf('.');\n int expPos = val.indexOf('e') + val.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos) {\n throw new NumberFormatException(val + \" is not a valid number.\");\n }\n dec = val.substring(decPos + 1, expPos);\n } else {\n dec = val.substring(decPos + 1);\n }\n mant = val.substring(0, decPos);\n } else {\n if (expPos > -1) {\n mant = val.substring(0, expPos);\n } else {\n mant = val;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar)) {\n if (expPos > -1 && expPos < val.length() - 1) {\n exp = val.substring(expPos + 1, val.length() - 1);\n } else {\n exp = null;\n }\n //Requesting a specific type..\n String numeric = val.substring(0, val.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l':\n case 'L':\n if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) {\n //Too big for a long\n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(val + \" is not a valid number.\");\n case 'f':\n case 'F':\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f == 0.0F && !allZeros))) {\n //If it's too big for a float or the float value = 0 and the string\n //has non-zeros in it, then float does not have the precision we want\n return f;\n }\n } catch (NumberFormatException e) {\n // ignore the bad number\n }\n //$FALL-THROUGH$\n case 'd':\n case 'D':\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n // empty catch\n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) {\n // empty catch\n }\n //$FALL-THROUGH$\n default:\n throw new NumberFormatException(val + \" is not a valid number.\");\n }\n } else {\n //User doesn't have a preference on the return type, so let's start\n //small and go from there...\n if (expPos > -1 && expPos < val.length() - 1) {\n exp = val.substring(expPos + 1);\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n //Must be an int,long,bigint\n try {\n return createInteger(val);\n } catch (NumberFormatException nfe) {\n // empty catch\n }\n try {\n return createLong(val);\n } catch (NumberFormatException nfe) {\n // empty catch\n }\n return createBigInteger(val);\n } else {\n //Must be a float,double,BigDec\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(val);\n if (!(f.isInfinite() || (f == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n // empty catch\n }\n try {\n Double d = createDouble(val);\n if (!(d.isInfinite() || (d == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n // empty catch\n }\n return createBigDecimal(val);\n }\n }\n }\n\n /**\n *

Utility method for {@link #createNumber(String)}.

\n *\n *

Returns true if s is null.

\n *\n * @param s the String to check\n * @return if it is all zeros or null\n */\n private static boolean isAllZeros(String s) {\n if (s == null) {\n return true;\n }\n for (int i = s.length() - 1; i >= 0; i--) {\n if (s.charAt(i) != '0') {\n return false;\n }\n }\n return s.length() > 0;\n }\n //--------------------------------------------------------------------\n\n /**\n *

Convert a String to a Float.

\n *\n * @param val a String to convert\n * @return converted Float\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Float createFloat(String val) {\n return Float.valueOf(val);\n }\n\n /**\n *

Convert a String to a Double.

\n *\n * @param val a String to convert\n * @return converted Double\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Double createDouble(String val) {\n return Double.valueOf(val);\n }\n\n /**\n *

Convert a String to a Integer, handling\n * hex and octal notations.

\n *\n * @param val a String to convert\n * @return converted Integer\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Integer createInteger(String val) {\n // decode() handles 0xAABD and 0777 (hex and octal) as well.\n return Integer.decode(val);\n }\n\n /**\n *

Convert a String to a Long.

\n *\n * @param val a String to convert\n * @return converted Long\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Long createLong(String val) {\n return Long.valueOf(val);\n }\n\n /**\n *

Convert a String to a BigInteger.

\n *\n * @param val a String to convert\n * @return converted BigInteger\n * @throws NumberFormatException if the value cannot be converted\n */\n public static BigInteger createBigInteger(String val) {\n return new BigInteger(val);\n }\n\n /**\n *

Convert a String to a BigDecimal.

\n *\n * @param val a String to convert\n * @return converted BigDecimal\n * @throws NumberFormatException if the value cannot be converted\n */\n public static BigDecimal createBigDecimal(String val) {\n return new BigDecimal(val);\n }\n //--------------------------------------------------------------------\n\n /**\n *

Gets the minimum of three long values.

\n *\n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the smallest of the values\n */\n public static long minimum(long a, long b, long c) {\n if (b < a) {\n a = b;\n }\n if (c < a) {\n a = c;\n }\n return a;\n }\n\n /**\n *

Gets the minimum of three int values.

\n *\n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the smallest of the values\n */\n public static int minimum(int a, int b, int c) {\n if (b < a) {\n a = b;\n }\n if (c < a) {\n a = c;\n }\n return a;\n }\n\n /**\n *

Gets the maximum of three long values.

\n *\n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the largest of the values\n */\n public static long maximum(long a, long b, long c) {\n if (b > a) {\n a = b;\n }\n if (c > a) {\n a = c;\n }\n return a;\n }\n\n /**\n *

Gets the maximum of three int values.

\n *\n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the largest of the values\n */\n public static int maximum(int a, int b, int c) {\n if (b > a) {\n a = b;\n }\n if (c > a) {\n a = c;\n }\n return a;\n }\n //--------------------------------------------------------------------\n\n /**\n *

Compares two doubles for order.

\n *\n *

This method is more comprehensive than the standard Java greater\n * than, less than and equals operators.

\n *
    \n *
  • It returns -1 if the first value is less than the second.\n *
  • It returns +1 if the first value is greater than the second.\n *
  • It returns 0 if the values are equal.\n *
\n *\n *

\n * The ordering is as follows, largest to smallest:\n *

    \n *
  • NaN\n *
  • Positive infinity\n *
  • Maximum double\n *
  • Normal positive numbers\n *
  • +0.0\n *
  • -0.0\n *
  • Normal negative numbers\n *
  • Minimum double (-Double.MAX_VALUE)\n *
  • Negative infinity\n *
\n *

\n *\n *

Comparing NaN with NaN will\n * return 0.

\n *\n * @param lhs the first double\n * @param rhs the second double\n * @return -1 if lhs is less, +1 if greater,\n * 0 if equal to rhs\n */\n public static int compare(double lhs, double rhs) {\n if (lhs < rhs) {\n return -1;\n }\n if (lhs > rhs) {\n return +1;\n }\n // Need to compare bits to handle 0.0 == -0.0 being true\n // compare should put -0.0 < +0.0\n // Two NaNs are also == for compare purposes\n // where NaN == NaN is false\n long lhsBits = Double.doubleToLongBits(lhs);\n long rhsBits = Double.doubleToLongBits(rhs);\n if (lhsBits == rhsBits) {\n return 0;\n }\n // Something exotic! A comparison to NaN or 0.0 vs -0.0\n // Fortunately NaN's long is > than everything else\n // Also negzeros bits < poszero\n // NAN: 9221120237041090560\n // MAX: 9218868437227405311\n // NEGZERO: -9223372036854775808\n if (lhsBits < rhsBits) {\n return -1;\n } else {\n return +1;\n }\n }\n\n /**\n *

Compares two floats for order.

\n *\n *

This method is more comprehensive than the standard Java greater than,\n * less than and equals operators.

\n *
    \n *
  • It returns -1 if the first value is less than the second.\n *
  • It returns +1 if the first value is greater than the second.\n *
  • It returns 0 if the values are equal.\n *
\n *\n *

The ordering is as follows, largest to smallest:\n *

    \n *
  • NaN\n *
  • Positive infinity\n *
  • Maximum float\n *
  • Normal positive numbers\n *
  • +0.0\n *
  • -0.0\n *
  • Normal negative numbers\n *
  • Minimum float (-Float.MAX_VALUE)\n *
  • Negative infinity\n *
\n *\n *

Comparing NaN with NaN will return\n * 0.

\n *\n * @param lhs the first float\n * @param rhs the second float\n * @return -1 if lhs is less, +1 if greater,\n * 0 if equal to rhs\n */\n public static int compare(float lhs, float rhs) {\n if (lhs < rhs) {\n return -1;\n }\n if (lhs > rhs) {\n return +1;\n }\n //Need to compare bits to handle 0.0 == -0.0 being true\n // compare should put -0.0 < +0.0\n // Two NaNs are also == for compare purposes\n // where NaN == NaN is false\n int lhsBits = Float.floatToIntBits(lhs);\n int rhsBits = Float.floatToIntBits(rhs);\n if (lhsBits == rhsBits) {\n return 0;\n }\n //Something exotic! A comparison to NaN or 0.0 vs -0.0\n //Fortunately NaN's int is > than everything else\n //Also negzeros bits < poszero\n //NAN: 2143289344\n //MAX: 2139095039\n //NEGZERO: -2147483648\n if (lhsBits < rhsBits) {\n return -1;\n } else {\n return +1;\n }\n }\n //--------------------------------------------------------------------\n\n /**\n *

Checks whether the String contains only\n * digit characters.

\n *\n *

Null and empty String will return\n * false.

\n *\n * @param str the String to check\n * @return true if str contains only unicode numeric\n */\n public static boolean isDigits(String str) {\n if ((str == null) || (str.length() == 0)) {\n return false;\n }\n for (int i = 0; i < str.length(); i++) {\n if (!Character.isDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks whether the String a valid Java number.

\n *\n *

Valid numbers include hexadecimal marked with the 0x\n * qualifier, scientific notation and numbers marked with a type\n * qualifier (e.g. 123L).

\n *\n *

Null and empty String will return\n * false.

\n *\n * @param str the String to check\n * @return true if the string is a correctly formatted number\n */\n public static boolean isNumber(String str) {\n if (StringUtils.isEmpty(str)) {\n return false;\n }\n char[] chars = str.toCharArray();\n int sz = chars.length;\n boolean hasExp = false;\n boolean hasDecPoint = false;\n boolean allowSigns = false;\n boolean foundDigit = false;\n // deal with any possible sign up front\n int start = (chars[0] == '-') ? 1 : 0;\n if (sz > start + 1) {\n if (chars[start] == '0' && chars[start + 1] == 'x') {\n int i = start + 2;\n if (i == sz) {\n return false; // str == \"0x\"\n }\n // checking hex (it can't be anything else)\n for (; i < chars.length; i++) {\n if ((chars[i] < '0' || chars[i] > '9') && (chars[i] < 'a' || chars[i] > 'f') && (chars[i] < 'A' || chars[i] > 'F')) {\n return false;\n }\n }\n return true;\n }\n }\n sz--; // don't want to loop to the last char, check it afterwords\n // for type qualifiers\n int i = start;\n // loop to the next to last char or to the last char if we need another digit to\n // make a valid number (e.g. chars[0..5] = \"1234E\")\n while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {\n if (chars[i] >= '0' && chars[i] <= '9') {\n foundDigit = true;\n allowSigns = false;\n } else if (chars[i] == '.') {\n if (hasDecPoint || hasExp) {\n // two decimal points or dec in exponent \n return false;\n }\n hasDecPoint = true;\n } else if (chars[i] == 'e' || chars[i] == 'E') {\n // we've already taken care of hex.\n if (hasExp) {\n // two E's\n return false;\n }\n if (!foundDigit) {\n return false;\n }\n hasExp = true;\n allowSigns = true;\n } else if (chars[i] == '+' || chars[i] == '-') {\n if (!allowSigns) {\n return false;\n }\n allowSigns = false;\n foundDigit = false; // we need a digit after the E\n } else {\n return false;\n }\n i++;\n }\n if (i < chars.length) {\n if (chars[i] >= '0' && chars[i] <= '9') {\n // no type qualifier, OK\n return true;\n }\n if (chars[i] == 'e' || chars[i] == 'E') {\n // can't have an E at the last byte\n return false;\n }\n if (!allowSigns && (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F')) {\n return foundDigit;\n }\n if (chars[i] == 'l' || chars[i] == 'L') {\n // not allowing L with an exponent\n return foundDigit && !hasExp;\n }\n // last character is illegal\n return false;\n }\n // allowSigns is true iff the val ends in 'E'\n // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass\n return !allowSigns && foundDigit;\n }\n\n public static boolean isByteType(Class targetType) {\n return targetType.equals(Byte.class) || targetType.equals(Byte.TYPE);\n }\n\n public static boolean isShortType(Class targetType) {\n return targetType.equals(Short.class) || targetType.equals(Short.TYPE);\n }\n\n public static boolean isIntType(Class targetType) {\n return targetType.equals(Integer.class) || targetType.equals(Integer.TYPE);\n }\n\n public static boolean isLongType(Class targetType) {\n return targetType.equals(Long.class) || targetType.equals(Long.TYPE);\n }\n\n public static boolean isFloatType(Class targetType) {\n return targetType.equals(Float.class) || targetType.equals(Float.TYPE);\n }\n\n public static boolean isDoubleType(Class targetType) {\n return targetType.equals(Double.class) || targetType.equals(Double.TYPE);\n }\n}\n", "file_name": "NumberUtils.java", "human_label": "Check whether a character string is a dight. If yes, true is returned. Otherwise, false is returned.", "level": "slib_runnable", "lineno": "561", "name": "isDigits", "oracle_context": "{ \"apis\" : \"[length, isDigit, charAt]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636766fc1a6d9265ec0177da", "all_context": "{ \"class_level\" : \"import net.hasor.db.jdbc.SqlParameterSource;\\nimport java.sql.SQLException;\\nimport java.util.*;\\nString originalSql;\\nint namedParameterCount;\\nint unnamedParameterCount;\\nint totalParameterCount;\\nList parameterNames;\\nList parameterIndexes;\\nchar[] PARAMETER_SEPARATORS;\\nString[] START_SKIP;\\nString[] STOP_SKIP;\\nParsedSql(String originalSql);\\ngetOriginalSql();\\ngetNamedParameterCount();\\ngetUnnamedParameterCount();\\ngetTotalParameterCount();\\ngetParameterNames();\\ngetParameterIndexes();\\nbuildValues(SqlParameterSource paramSource);\\ngetParsedSql(String originalSql);\\nskipCommentsAndQuotes(char[] statement,int position);\\nisParameterSeparator(char c);\\nbuildSql();\\n\", \"repo_level\" : \"public interface SqlParameterSource {public boolean hasValue(String paramName);\\npublic Object getValue(String paramName);\\npublic String[] getParameterNames();\\n }\\n\" }", "class_name": "ParsedSql", "code": "private static boolean isParameterSeparator(final char c){\n if (Character.isWhitespace(c)) {\n return true;\n }\n for ( char separator : PARAMETER_SEPARATORS) {\n if (c == separator) {\n return true;\n }\n }\n return false;\n}\n", "docstring": "/** \n * Determine whether a parameter name ends at the current position, that is, whether the given character qualifies as a separator. \n */\n", "end_lineno": "224", "file_content": "/*\n * Copyright 2002-2008 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.db.jdbc.core;\nimport net.hasor.db.jdbc.SqlParameterSource;\n\nimport java.sql.SQLException;\nimport java.util.*;\n\n/**\n * Holds information about a parsed SQL statement.\n *\n * @author Thomas Risberg\n * @author Juergen Hoeller\n * @author 赵永春 (zyc@hasor.net)\n * @since 2.0\n */\npublic class ParsedSql {\n private final String originalSql;\n private int namedParameterCount;\n private int unnamedParameterCount;\n private int totalParameterCount;\n private List parameterNames;\n private List parameterIndexes;\n\n private ParsedSql(String originalSql) {\n this.originalSql = originalSql;\n }\n\n public String getOriginalSql() {\n return this.originalSql;\n }\n\n public int getNamedParameterCount() {\n return this.namedParameterCount;\n }\n\n public int getUnnamedParameterCount() {\n return this.unnamedParameterCount;\n }\n\n public int getTotalParameterCount() {\n return this.totalParameterCount;\n }\n\n public List getParameterNames() {\n return this.parameterNames;\n }\n\n public List getParameterIndexes() {\n return this.parameterIndexes;\n }\n\n /**生成SQL*/\n public String buildSql() {\n String originalSql = this.getOriginalSql();\n List parameterNames = this.getParameterNames();\n List parameterIndexes = this.getParameterIndexes();\n //\n StringBuilder sqlToUse = new StringBuilder();\n int lastIndex = 0;\n for (int i = 0; i < parameterNames.size(); i++) {\n int[] indexes = parameterIndexes.get(i);\n int startIndex = indexes[0];\n int endIndex = indexes[1];\n sqlToUse.append(originalSql, lastIndex, startIndex);\n sqlToUse.append(\"?\");\n lastIndex = endIndex;\n }\n sqlToUse.append(originalSql.substring(lastIndex));\n return sqlToUse.toString();\n }\n\n /**生成Values*/\n public Object[] buildValues(final SqlParameterSource paramSource) throws SQLException {\n String originalSql = this.getOriginalSql();\n List parameterNames = this.getParameterNames();\n int namedParameterCount = this.getNamedParameterCount();//带有名字参数的总数\n int unnamedParameterCount = this.getUnnamedParameterCount();//无名字参数总数\n int totalParameterCount = this.getTotalParameterCount();//参数总数\n //\n Object[] paramArray = new Object[totalParameterCount];\n if (namedParameterCount > 0 && unnamedParameterCount > 0) {\n throw new SQLException(\"You can't mix named and traditional ? placeholders. You have \" + namedParameterCount + \" named parameter(s) and \" + unnamedParameterCount + \" traditonal placeholder(s) in [\" + originalSql + \"]\");\n }\n for (int i = 0; i < parameterNames.size(); i++) {\n String paramName = parameterNames.get(i);\n paramArray[i] = paramSource.getValue(paramName);\n }\n return paramArray;\n }\n\n /**Set of characters that qualify as parameter separators, indicating that a parameter name in a SQL String has ended. */\n private static final char[] PARAMETER_SEPARATORS = new char[] { '\"', '\\'', ':', '&', ',', ';', '(', ')', '|', '=', '+', '-', '*', '%', '/', '\\\\', '<', '>', '^' };\n /** Set of characters that qualify as comment or quotes starting characters.*/\n private static final String[] START_SKIP = new String[] { \"'\", \"\\\"\", \"--\", \"/*\" };\n /**Set of characters that at are the corresponding comment or quotes ending characters. */\n private static final String[] STOP_SKIP = new String[] { \"'\", \"\\\"\", \"\\n\", \"*/\" };\n\n //-------------------------------------------------------------------------\n // Core methods used by NamedParameterJdbcTemplate and SqlQuery/SqlUpdate\n //-------------------------------------------------------------------------\n public static ParsedSql getParsedSql(final String originalSql) {\n ParsedSql parSQL = new ParsedSql(originalSql);\n //\n //1.关键参数定义\n List parameterNames = new ArrayList<>();\n List parameterIndexes = new ArrayList<>();\n int namedParameterCount = 0;//带有名字参数的总数\n int unnamedParameterCount = 0;//无名字参数总数\n int totalParameterCount = 0;//参数总数\n //\n //2.分析SQL,提取出SQL中参数信息\n Objects.requireNonNull(originalSql, \"SQL must not be null\");\n Set namedParameters = new HashSet<>();\n char[] statement = originalSql.toCharArray();\n int i = 0;\n while (i < statement.length) {\n int skipToPosition = skipCommentsAndQuotes(statement, i);//从当前为止掠过的长度\n if (i != skipToPosition) {\n if (skipToPosition >= statement.length) {\n break;\n }\n i = skipToPosition;\n }\n char c = statement[i];\n if (c == ':' || c == '&') {\n int j = i + 1;\n if (j < statement.length && statement[j] == ':' && c == ':') {\n i = i + 2;// Postgres-style \"::\" casting operator - to be skipped.\n continue;\n }\n while (j < statement.length && !isParameterSeparator(statement[j])) {\n j++;\n }\n if (j - i > 1) {\n String parameter = originalSql.substring(i + 1, j);\n if (!namedParameters.contains(parameter)) {\n namedParameters.add(parameter);\n namedParameterCount++;\n }\n parameterNames.add(parameter);\n parameterIndexes.add(new int[] { i, j });//startIndex, endIndex\n totalParameterCount++;\n }\n i = j - 1;\n } else if (c == '?') {\n unnamedParameterCount++;\n totalParameterCount++;\n }\n i++;\n }\n parSQL.namedParameterCount = namedParameterCount;/*带有名字参数的总数*/\n parSQL.unnamedParameterCount = unnamedParameterCount;/*匿名参数的总数*/\n parSQL.totalParameterCount = totalParameterCount;/*总共参数个数*/\n parSQL.parameterIndexes = parameterIndexes;\n parSQL.parameterNames = parameterNames;\n return parSQL;\n }\n\n /** Skip over comments and quoted names present in an SQL statement */\n private static int skipCommentsAndQuotes(final char[] statement, final int position) {\n for (int i = 0; i < START_SKIP.length; i++) {\n if (statement[position] == START_SKIP[i].charAt(0)) {\n boolean match = true;\n for (int j = 1; j < START_SKIP[i].length(); j++) {\n if (!(statement[position + j] == START_SKIP[i].charAt(j))) {\n match = false;\n break;\n }\n }\n if (match) {\n int offset = START_SKIP[i].length();\n for (int m = position + offset; m < statement.length; m++) {\n if (statement[m] == STOP_SKIP[i].charAt(0)) {\n boolean endMatch = true;\n int endPos = m;\n for (int n = 1; n < STOP_SKIP[i].length(); n++) {\n if (m + n >= statement.length) {\n return statement.length;// last comment not closed properly\n }\n if (!(statement[m + n] == STOP_SKIP[i].charAt(n))) {\n endMatch = false;\n break;\n }\n endPos = m + n;\n }\n if (endMatch) {\n return endPos + 1;// found character sequence ending comment or quote\n }\n }\n }\n // character sequence ending comment or quote not found\n return statement.length;\n }\n }\n }\n return position;\n }\n\n /** Determine whether a parameter name ends at the current position, that is, whether the given character qualifies as a separator. */\n private static boolean isParameterSeparator(final char c) {\n if (Character.isWhitespace(c)) {\n return true;\n }\n for (char separator : PARAMETER_SEPARATORS) {\n if (c == separator) {\n return true;\n }\n }\n return false;\n }\n}", "file_name": "ParsedSql.java", "human_label": "Check whether a character is a parameter separator. If yes, true is returned. Otherwise, false is returned.", "level": "class_runnable", "lineno": "213", "name": "isParameterSeparator", "oracle_context": "{ \"apis\" : \"[isWhitespace]\", \"classes\" : \"[]\", \"vars\" : \"[PARAMETER_SEPARATORS]\" }", "package": "net.hasor.db.jdbc.core", "project": "hasor-master" }, { "_id": "6367670c1a6d9265ec017a35", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.List;\\nimport java.util.Locale;\\nString EMPTY;\\nint INDEX_NOT_FOUND;\\nint PAD_LIMIT;\\nchar[] escapes;\\nStringUtils();\\nisNotEmpty(String str);\\nisBlank(String str);\\nisNotBlank(String str);\\ntrim(String str);\\ntrimToNull(String str);\\ntrimToEmpty(String str);\\nstrip(String str);\\nstripToNull(String str);\\nstripToEmpty(String str);\\nstrip(String str,String stripChars);\\nstripStart(String str,String stripChars);\\nstripEnd(String str,String stripChars);\\nstripAll(String[] strs);\\nstripAll(String[] strs,String stripChars);\\nequals(String str1,String str2);\\nequalsIgnoreCase(String str1,String str2);\\nindexOf(String str,char searchChar);\\nindexOf(String str,char searchChar,int startPos);\\nindexOf(String str,String searchStr);\\nordinalIndexOf(String str,String searchStr,int ordinal);\\nordinalIndexOf(String str,String searchStr,int ordinal,boolean lastIndex);\\nindexOf(String str,String searchStr,int startPos);\\nindexOfIgnoreCase(String str,String searchStr);\\nindexOfIgnoreCase(String str,String searchStr,int startPos);\\nlastIndexOf(String str,char searchChar);\\nlastIndexOf(String str,char searchChar,int startPos);\\nlastIndexOf(String str,String searchStr);\\nlastOrdinalIndexOf(String str,String searchStr,int ordinal);\\nlastIndexOf(String str,String searchStr,int startPos);\\nlastIndexOfIgnoreCase(String str,String searchStr);\\nlastIndexOfIgnoreCase(String str,String searchStr,int startPos);\\ncontains(String str,char searchChar);\\ncontains(String str,String searchStr);\\ncontainsIgnoreCase(String str,String searchStr);\\nindexOfAny(String str,char[] searchChars);\\nindexOfAny(String str,String searchChars);\\ncontainsAny(String str,char[] searchChars);\\ncontainsAny(String str,String searchChars);\\nindexOfAnyBut(String str,char[] searchChars);\\nindexOfAnyBut(String str,String searchChars);\\ncontainsOnly(String str,char[] valid);\\ncontainsOnly(String str,String validChars);\\ncontainsNone(String str,char[] searchChars);\\ncontainsNone(String str,String invalidChars);\\nindexOfAny(String str,String[] searchStrs);\\nlastIndexOfAny(String str,String[] searchStrs);\\nsubstring(String str,int start);\\nsubstring(String str,int start,int end);\\nleft(String str,int len);\\nright(String str,int len);\\nmid(String str,int pos,int len);\\nsubstringBefore(String str,String separator);\\nsubstringAfter(String str,String separator);\\nsubstringBeforeLast(String str,String separator);\\nsubstringAfterLast(String str,String separator);\\nsubstringBetween(String str,String tag);\\nsubstringBetween(String str,String open,String close);\\nsubstringsBetween(String str,String open,String close);\\nsplitKeep(String str,char separatorChar);\\nsplitKeep(String str,String separatorStr);\\nsplit(String str);\\nsplit(String str,char separatorChar);\\nsplit(String str,String separatorChars);\\nsplit(String str,String separatorChars,int max);\\nsplitByWholeSeparator(String str,String separator);\\nsplitByWholeSeparator(String str,String separator,int max);\\nsplitByWholeSeparatorPreserveAllTokens(String str,String separator);\\nsplitByWholeSeparatorPreserveAllTokens(String str,String separator,int max);\\nsplitByWholeSeparatorWorker(String str,String separator,int max,boolean preserveAllTokens);\\nsplitPreserveAllTokens(String str);\\nsplitPreserveAllTokens(String str,char separatorChar);\\nsplitWorker(String str,char separatorChar,boolean preserveAllTokens);\\nsplitPreserveAllTokens(String str,String separatorChars);\\nsplitPreserveAllTokens(String str,String separatorChars,int max);\\nsplitWorker(String str,String separatorChars,int max,boolean preserveAllTokens);\\nsplitByCharacterType(String str);\\nsplitByCharacterTypeCamelCase(String str);\\nsplitByCharacterType(String str,boolean camelCase);\\njoin(Object[] array);\\njoin(Object[] array,char separator);\\njoin(Object[] array,char separator,int startIndex,int endIndex);\\njoin(Object[] array,String separator);\\njoin(Object[] array,String separator,int startIndex,int endIndex);\\ndeleteWhitespace(String str);\\nremoveStart(String str,String remove);\\nremoveStartIgnoreCase(String str,String remove);\\nremoveEnd(String str,String remove);\\nremoveEndIgnoreCase(String str,String remove);\\nremove(String str,String remove);\\nremove(String str,char remove);\\nreplaceOnce(String text,String searchString,String replacement);\\nreplace(String text,String searchString,String replacement);\\nreplace(String text,String searchString,String replacement,int max);\\nreplaceEach(String text,String[] searchList,String[] replacementList);\\nreplaceEachRepeatedly(String text,String[] searchList,String[] replacementList);\\nreplaceEach(String text,String[] searchList,String[] replacementList,boolean repeat,int timeToLive);\\nreplaceChars(String str,char searchChar,char replaceChar);\\nreplaceChars(String str,String searchChars,String replaceChars);\\noverlay(String str,String overlay,int start,int end);\\nchomp(String str);\\nchomp(String str,String separator);\\nchop(String str);\\nrepeat(char character,int repeat);\\nrepeat(String str,int repeat);\\nrepeat(String str,String separator,int repeat);\\npadding(int repeat,char padChar);\\nrightPad(String str,int size);\\nrightPad(String str,int size,char padChar);\\nrightPad(String str,int size,String padStr);\\nleftPad(String str,int size);\\nleftPad(String str,int size,char padChar);\\nleftPad(String str,int size,String padStr);\\nlength(String str);\\ncenter(String str,int size);\\ncenter(String str,int size,char padChar);\\ncenter(String str,int size,String padStr);\\nupperCase(String str);\\nupperCase(String str,Locale locale);\\nlowerCase(String str);\\nlowerCase(String str,Locale locale);\\ncapitalize(String str);\\nuncapitalize(String str);\\nswapCase(String str);\\ncountMatches(String str,String sub);\\nisAlpha(String str);\\nisAlphaSpace(String str);\\nisAlphanumeric(String str);\\nisAlphanumericSpace(String str);\\nisAsciiPrintable(String str);\\nisNumeric(String str);\\nisNumericSpace(String str);\\nisWhitespace(String str);\\nisAllLowerCase(String str);\\nisAllUpperCase(String str);\\ndefaultString(String str);\\ndefaultString(String str,String defaultStr);\\ndefaultIfBlank(String str,String defaultStr);\\ndefaultIfEmpty(String str,String defaultStr);\\nreverse(String str);\\nreverseDelimited(String str,char separatorChar);\\nabbreviate(String str,int maxWidth);\\nabbreviate(String str,int offset,int maxWidth);\\nabbreviateMiddle(String str,String middle,int length);\\ndifference(String str1,String str2);\\nindexOfDifference(String str1,String str2);\\nindexOfDifference(String[] strs);\\ngetCommonPrefix(String[] strs);\\ngetLevenshteinDistance(String s,String t);\\nstartsWith(String str,String prefix);\\nstartsWithIgnoreCase(String str,String prefix);\\nstartsWith(String str,String prefix,boolean ignoreCase);\\nstartsWithAny(String string,String[] searchStrings);\\nendsWith(String str,String suffix);\\nendsWithIgnoreCase(String str,String suffix);\\nendsWith(String str,String suffix,boolean ignoreCase);\\nnormalizeSpace(String str);\\nendsWithAny(String string,String[] searchStrings);\\nfirstCharToUpperCase(String value);\\nfirstCharToLowerCase(String value);\\nequalsBlankIgnoreCase(String str1,String str2);\\nquote(String input);\\nquote(Appendable buffer,String input);\\ntoString(Object object);\\nisEmpty(String str);\\n\", \"repo_level\" : \"\" }", "class_name": "StringUtils", "code": "private static boolean endsWith(final String str,final String suffix,final boolean ignoreCase){\n if (str == null || suffix == null) {\n return str == null && suffix == null;\n }\n if (suffix.length() > str.length()) {\n return false;\n }\n int strOffset=str.length() - suffix.length();\n return str.regionMatches(ignoreCase,strOffset,suffix,0,suffix.length());\n}\n", "docstring": "/** \n *

Check if a String ends with a specified suffix (optionally case insensitive).

\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @param ignoreCase inidicates whether the compare should ignore case(case insensitive) or not.\n * @return true if the String starts with the prefix orboth null\n */\n", "end_lineno": "5945", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Locale;\n\n/**\n *

Operations on {@link String} that are\n * null safe.

\n *\n *
    \n *
  • IsEmpty/IsBlank\n * - checks if a String contains text
  • \n *
  • Trim/Strip\n * - removes leading and trailing whitespace
  • \n *
  • Equals\n * - compares two strings null-safe
  • \n *
  • startsWith\n * - check if a String starts with a prefix null-safe
  • \n *
  • endsWith\n * - check if a String ends with a suffix null-safe
  • \n *
  • IndexOf/LastIndexOf/Contains\n * - null-safe index-of checks\n *
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut\n * - index-of any of a set of Strings
  • \n *
  • ContainsOnly/ContainsNone/ContainsAny\n * - does String contains only/none/any of these characters
  • \n *
  • Substring/Left/Right/Mid\n * - null-safe substring extractions
  • \n *
  • SubstringBefore/SubstringAfter/SubstringBetween\n * - substring extraction relative to other strings
  • \n *
  • Split/Join\n * - splits a String into an array of substrings and vice versa
  • \n *
  • Remove/Delete\n * - removes part of a String
  • \n *
  • Replace/Overlay\n * - Searches a String and replaces one String with another
  • \n *
  • Chomp/Chop\n * - removes the last part of a String
  • \n *
  • LeftPad/RightPad/Center/Repeat\n * - pads a String
  • \n *
  • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize\n * - changes the case of a String
  • \n *
  • CountMatches\n * - counts the number of occurrences of one String in another
  • \n *
  • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable\n * - checks the characters in a String
  • \n *
  • DefaultString\n * - protects against a null input String
  • \n *
  • Reverse/ReverseDelimited\n * - reverses a String
  • \n *
  • Abbreviate\n * - abbreviates a string using ellipsis
  • \n *
  • Difference\n * - compares Strings and reports on their differences
  • \n *
  • LevensteinDistance\n * - the number of changes needed to change one String into another
  • \n *
\n *\n *

The StringUtils class defines certain words related to\n * String handling.

\n *\n *
    \n *
  • null - null
  • \n *
  • empty - a zero-length string (\"\")
  • \n *
  • space - the space character (' ', char 32)
  • \n *
  • whitespace - the characters defined by {@link Character#isWhitespace(char)}
  • \n *
  • trim - the characters <= 32 as in {@link String#trim()}
  • \n *
\n *\n *

StringUtils handles null input Strings quietly.\n * That is to say that a null input will return null.\n * Where a boolean or int is being returned\n * details vary by method.

\n *\n *

A side effect of the null handling is that a\n * NullPointerException should be considered a bug in\n * StringUtils (except for deprecated methods).

\n *\n *

Methods in this class give sample code to explain their operation.\n * The symbol * is used to indicate any input including null.

\n *\n *

#ThreadSafe#

\n * @see String\n * @author Apache Software Foundation\n * @author Apache Jakarta Turbine\n * @author Jon S. Stevens\n * @author Daniel L. Rall\n * @author Greg Coladonato\n * @author Ed Korthof\n * @author Rand McNeely\n * @author Fredrik Westermarck\n * @author Holger Krauth\n * @author Alexander Day Chaffee\n * @author Henning P. Schmiedehausen\n * @author Arun Mammen Thomas\n * @author Gary Gregory\n * @author Phil Steitz\n * @author Al Chou\n * @author Michael Davey\n * @author Reuben Sivan\n * @author Chris Hyzer\n * @author Scott Johnson\n * @since 1.0\n * @version $Id: StringUtils.java 1058365 2011-01-13 00:04:49Z niallp $\n */\n//@Immutable\npublic class StringUtils {\n // Performance testing notes (JDK 1.4, Jul03, scolebourne)\n // Whitespace:\n // Character.isWhitespace() is faster than WHITESPACE.indexOf()\n // where WHITESPACE is a string of all whitespace characters\n //\n // Character access:\n // String.charAt(n) versus toCharArray(), then array[n]\n // String.charAt(n) is about 15% worse for a 10K string\n // They are about equal for a length 50 string\n // String.charAt(n) is about 4 times better for a length 3 string\n // String.charAt(n) is best bet overall\n //\n // Append:\n // String.concat about twice as fast as StringBuffer.append\n // (not sure who tested this)\n /**\n * The empty String \"\".\n * @since 2.0\n */\n public static final String EMPTY = \"\";\n /**\n * Represents a failed index search.\n * @since 2.1\n */\n public static final int INDEX_NOT_FOUND = -1;\n /**\n *

The maximum size to which the padding constant(s) can expand.

\n */\n private static final int PAD_LIMIT = 8192;\n\n /**\n *

StringUtils instances should NOT be constructed in\n * standard programming. Instead, the class should be used as\n * StringUtils.trim(\" foo \");.

\n *\n *

This constructor is public to permit tools that require a JavaBean\n * instance to operate.

\n */\n public StringUtils() {\n super();\n }\n // Empty checks\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if a String is empty (\"\") or null.

\n *\n *
\n     * StringUtils.isEmpty(null)      = true\n     * StringUtils.isEmpty(\"\")        = true\n     * StringUtils.isEmpty(\" \")       = false\n     * StringUtils.isEmpty(\"bob\")     = false\n     * StringUtils.isEmpty(\"  bob  \") = false\n     * 
\n *\n *

NOTE: This method changed in Lang version 2.0.\n * It no longer trims the String.\n * That functionality is available in isBlank().

\n *\n * @param str the String to check, may be null\n * @return true if the String is empty or null\n */\n public static boolean isEmpty(final String str) {\n return str == null || str.length() == 0;\n }\n\n /**\n *

Checks if a String is not empty (\"\") and not null.

\n *\n *
\n     * StringUtils.isNotEmpty(null)      = false\n     * StringUtils.isNotEmpty(\"\")        = false\n     * StringUtils.isNotEmpty(\" \")       = true\n     * StringUtils.isNotEmpty(\"bob\")     = true\n     * StringUtils.isNotEmpty(\"  bob  \") = true\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if the String is not empty and not null\n */\n public static boolean isNotEmpty(final String str) {\n return !StringUtils.isEmpty(str);\n }\n\n /**\n *

Checks if a String is whitespace, empty (\"\") or null.

\n *\n *
\n     * StringUtils.isBlank(null)      = true\n     * StringUtils.isBlank(\"\")        = true\n     * StringUtils.isBlank(\" \")       = true\n     * StringUtils.isBlank(\"bob\")     = false\n     * StringUtils.isBlank(\"  bob  \") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if the String is null, empty or whitespace\n * @since 2.0\n */\n public static boolean isBlank(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return true;\n }\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i)) == false) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if a String is not empty (\"\"), not null and not whitespace only.

\n *\n *
\n     * StringUtils.isNotBlank(null)      = false\n     * StringUtils.isNotBlank(\"\")        = false\n     * StringUtils.isNotBlank(\" \")       = false\n     * StringUtils.isNotBlank(\"bob\")     = true\n     * StringUtils.isNotBlank(\"  bob  \") = true\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if the String is\n * not empty and not null and not whitespace\n * @since 2.0\n */\n public static boolean isNotBlank(final String str) {\n return !StringUtils.isBlank(str);\n }\n // Trim\n //-----------------------------------------------------------------------\n\n /**\n *

Removes control characters (char <= 32) from both\n * ends of this String, handling null by returning\n * null.

\n *\n *

The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #strip(String)}.

\n *\n *

To trim your choice of characters, use the\n * {@link #strip(String, String)} methods.

\n *\n *
\n     * StringUtils.trim(null)          = null\n     * StringUtils.trim(\"\")            = \"\"\n     * StringUtils.trim(\"     \")       = \"\"\n     * StringUtils.trim(\"abc\")         = \"abc\"\n     * StringUtils.trim(\"    abc    \") = \"abc\"\n     * 
\n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed string, null if null String input\n */\n public static String trim(final String str) {\n return str == null ? null : str.trim();\n }\n\n /**\n *

Removes control characters (char <= 32) from both\n * ends of this String returning null if the String is\n * empty (\"\") after the trim or if it is null.\n *\n *

The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #stripToNull(String)}.

\n *\n *
\n     * StringUtils.trimToNull(null)          = null\n     * StringUtils.trimToNull(\"\")            = null\n     * StringUtils.trimToNull(\"     \")       = null\n     * StringUtils.trimToNull(\"abc\")         = \"abc\"\n     * StringUtils.trimToNull(\"    abc    \") = \"abc\"\n     * 
\n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed String,\n * null if only chars <= 32, empty or null String input\n * @since 2.0\n */\n public static String trimToNull(final String str) {\n String ts = StringUtils.trim(str);\n return StringUtils.isEmpty(ts) ? null : ts;\n }\n\n /**\n *

Removes control characters (char <= 32) from both\n * ends of this String returning an empty String (\"\") if the String\n * is empty (\"\") after the trim or if it is null.\n *\n *

The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #stripToEmpty(String)}.

\n *\n *
\n     * StringUtils.trimToEmpty(null)          = \"\"\n     * StringUtils.trimToEmpty(\"\")            = \"\"\n     * StringUtils.trimToEmpty(\"     \")       = \"\"\n     * StringUtils.trimToEmpty(\"abc\")         = \"abc\"\n     * StringUtils.trimToEmpty(\"    abc    \") = \"abc\"\n     * 
\n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed String, or an empty String if null input\n * @since 2.0\n */\n public static String trimToEmpty(final String str) {\n return str == null ? StringUtils.EMPTY : str.trim();\n }\n // Stripping\n //-----------------------------------------------------------------------\n\n /**\n *

Strips whitespace from the start and end of a String.

\n *\n *

This is similar to {@link #trim(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.strip(null)     = null\n     * StringUtils.strip(\"\")       = \"\"\n     * StringUtils.strip(\"   \")    = \"\"\n     * StringUtils.strip(\"abc\")    = \"abc\"\n     * StringUtils.strip(\"  abc\")  = \"abc\"\n     * StringUtils.strip(\"abc  \")  = \"abc\"\n     * StringUtils.strip(\" abc \")  = \"abc\"\n     * StringUtils.strip(\" ab c \") = \"ab c\"\n     * 
\n *\n * @param str the String to remove whitespace from, may be null\n * @return the stripped String, null if null String input\n */\n public static String strip(final String str) {\n return StringUtils.strip(str, null);\n }\n\n /**\n *

Strips whitespace from the start and end of a String returning\n * null if the String is empty (\"\") after the strip.

\n *\n *

This is similar to {@link #trimToNull(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripToNull(null)     = null\n     * StringUtils.stripToNull(\"\")       = null\n     * StringUtils.stripToNull(\"   \")    = null\n     * StringUtils.stripToNull(\"abc\")    = \"abc\"\n     * StringUtils.stripToNull(\"  abc\")  = \"abc\"\n     * StringUtils.stripToNull(\"abc  \")  = \"abc\"\n     * StringUtils.stripToNull(\" abc \")  = \"abc\"\n     * StringUtils.stripToNull(\" ab c \") = \"ab c\"\n     * 
\n *\n * @param str the String to be stripped, may be null\n * @return the stripped String,\n * null if whitespace, empty or null String input\n * @since 2.0\n */\n public static String stripToNull(String str) {\n if (str == null) {\n return null;\n }\n str = StringUtils.strip(str, null);\n return str.length() == 0 ? null : str;\n }\n\n /**\n *

Strips whitespace from the start and end of a String returning\n * an empty String if null input.

\n *\n *

This is similar to {@link #trimToEmpty(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripToEmpty(null)     = \"\"\n     * StringUtils.stripToEmpty(\"\")       = \"\"\n     * StringUtils.stripToEmpty(\"   \")    = \"\"\n     * StringUtils.stripToEmpty(\"abc\")    = \"abc\"\n     * StringUtils.stripToEmpty(\"  abc\")  = \"abc\"\n     * StringUtils.stripToEmpty(\"abc  \")  = \"abc\"\n     * StringUtils.stripToEmpty(\" abc \")  = \"abc\"\n     * StringUtils.stripToEmpty(\" ab c \") = \"ab c\"\n     * 
\n *\n * @param str the String to be stripped, may be null\n * @return the trimmed String, or an empty String if null input\n * @since 2.0\n */\n public static String stripToEmpty(final String str) {\n return str == null ? StringUtils.EMPTY : StringUtils.strip(str, null);\n }\n\n /**\n *

Strips any of a set of characters from the start and end of a String.\n * This is similar to {@link String#trim()} but allows the characters\n * to be stripped to be controlled.

\n *\n *

A null input String returns null.\n * An empty string (\"\") input returns the empty string.

\n *\n *

If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.\n * Alternatively use {@link #strip(String)}.

\n *\n *
\n     * StringUtils.strip(null, *)          = null\n     * StringUtils.strip(\"\", *)            = \"\"\n     * StringUtils.strip(\"abc\", null)      = \"abc\"\n     * StringUtils.strip(\"  abc\", null)    = \"abc\"\n     * StringUtils.strip(\"abc  \", null)    = \"abc\"\n     * StringUtils.strip(\" abc \", null)    = \"abc\"\n     * StringUtils.strip(\"  abcyx\", \"xyz\") = \"  abc\"\n     * 
\n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String strip(String str, final String stripChars) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n str = StringUtils.stripStart(str, stripChars);\n return StringUtils.stripEnd(str, stripChars);\n }\n\n /**\n *

Strips any of a set of characters from the start of a String.

\n *\n *

A null input String returns null.\n * An empty string (\"\") input returns the empty string.

\n *\n *

If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripStart(null, *)          = null\n     * StringUtils.stripStart(\"\", *)            = \"\"\n     * StringUtils.stripStart(\"abc\", \"\")        = \"abc\"\n     * StringUtils.stripStart(\"abc\", null)      = \"abc\"\n     * StringUtils.stripStart(\"  abc\", null)    = \"abc\"\n     * StringUtils.stripStart(\"abc  \", null)    = \"abc  \"\n     * StringUtils.stripStart(\" abc \", null)    = \"abc \"\n     * StringUtils.stripStart(\"yxabc  \", \"xyz\") = \"abc  \"\n     * 
\n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String stripStart(final String str, final String stripChars) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n int start = 0;\n if (stripChars == null) {\n while (start != strLen && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n } else if (stripChars.length() == 0) {\n return str;\n } else {\n while (start != strLen && stripChars.indexOf(str.charAt(start)) != StringUtils.INDEX_NOT_FOUND) {\n start++;\n }\n }\n return str.substring(start);\n }\n\n /**\n *

Strips any of a set of characters from the end of a String.

\n *\n *

A null input String returns null.\n * An empty string (\"\") input returns the empty string.

\n *\n *

If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripEnd(null, *)          = null\n     * StringUtils.stripEnd(\"\", *)            = \"\"\n     * StringUtils.stripEnd(\"abc\", \"\")        = \"abc\"\n     * StringUtils.stripEnd(\"abc\", null)      = \"abc\"\n     * StringUtils.stripEnd(\"  abc\", null)    = \"  abc\"\n     * StringUtils.stripEnd(\"abc  \", null)    = \"abc\"\n     * StringUtils.stripEnd(\" abc \", null)    = \" abc\"\n     * StringUtils.stripEnd(\"  abcyx\", \"xyz\") = \"  abc\"\n     * StringUtils.stripEnd(\"120.00\", \".0\")   = \"12\"\n     * 
\n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the set of characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String stripEnd(final String str, final String stripChars) {\n int end;\n if (str == null || (end = str.length()) == 0) {\n return str;\n }\n if (stripChars == null) {\n while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n } else if (stripChars.length() == 0) {\n return str;\n } else {\n while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != StringUtils.INDEX_NOT_FOUND) {\n end--;\n }\n }\n return str.substring(0, end);\n }\n // StripAll\n //-----------------------------------------------------------------------\n\n /**\n *

Strips whitespace from the start and end of every String in an array.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

A new array is returned each time, except for length zero.\n * A null array will return null.\n * An empty array will return itself.\n * A null array entry will be ignored.

\n *\n *
\n     * StringUtils.stripAll(null)             = null\n     * StringUtils.stripAll([])               = []\n     * StringUtils.stripAll([\"abc\", \"  abc\"]) = [\"abc\", \"abc\"]\n     * StringUtils.stripAll([\"abc  \", null])  = [\"abc\", null]\n     * 
\n *\n * @param strs the array to remove whitespace from, may be null\n * @return the stripped Strings, null if null array input\n */\n public static String[] stripAll(final String[] strs) {\n return StringUtils.stripAll(strs, null);\n }\n\n /**\n *

Strips any of a set of characters from the start and end of every\n * String in an array.

\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

A new array is returned each time, except for length zero.\n * A null array will return null.\n * An empty array will return itself.\n * A null array entry will be ignored.\n * A null stripChars will strip whitespace as defined by\n * {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripAll(null, *)                = null\n     * StringUtils.stripAll([], *)                  = []\n     * StringUtils.stripAll([\"abc\", \"  abc\"], null) = [\"abc\", \"abc\"]\n     * StringUtils.stripAll([\"abc  \", null], null)  = [\"abc\", null]\n     * StringUtils.stripAll([\"abc  \", null], \"yz\")  = [\"abc  \", null]\n     * StringUtils.stripAll([\"yabcz\", null], \"yz\")  = [\"abc\", null]\n     * 
\n *\n * @param strs the array to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped Strings, null if null array input\n */\n public static String[] stripAll(final String[] strs, final String stripChars) {\n int strsLen;\n if (strs == null || (strsLen = strs.length) == 0) {\n return strs;\n }\n String[] newArr = new String[strsLen];\n for (int i = 0; i < strsLen; i++) {\n newArr[i] = StringUtils.strip(strs[i], stripChars);\n }\n return newArr;\n }\n // Equals\n //-----------------------------------------------------------------------\n\n /**\n *

Compares two Strings, returning true if they are equal.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

\n *\n *
\n     * StringUtils.equals(null, null)   = true\n     * StringUtils.equals(null, \"abc\")  = false\n     * StringUtils.equals(\"abc\", null)  = false\n     * StringUtils.equals(\"abc\", \"abc\") = true\n     * StringUtils.equals(\"abc\", \"ABC\") = false\n     * 
\n *\n * @see String#equals(Object)\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return true if the Strings are equal, case sensitive, or\n * both null\n */\n public static boolean equals(final String str1, final String str2) {\n return str1 == null ? str2 == null : str1.equals(str2);\n }\n\n /**\n *

Compares two Strings, returning true if they are equal ignoring\n * the case.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered equal. Comparison is case insensitive.

\n *\n *
\n     * StringUtils.equalsIgnoreCase(null, null)   = true\n     * StringUtils.equalsIgnoreCase(null, \"abc\")  = false\n     * StringUtils.equalsIgnoreCase(\"abc\", null)  = false\n     * StringUtils.equalsIgnoreCase(\"abc\", \"abc\") = true\n     * StringUtils.equalsIgnoreCase(\"abc\", \"ABC\") = true\n     * 
\n *\n * @see String#equalsIgnoreCase(String)\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return true if the Strings are equal, case insensitive, or\n * both null\n */\n public static boolean equalsIgnoreCase(final String str1, final String str2) {\n return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);\n }\n // IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(int)}.

\n *\n *

A null or empty (\"\") String will return INDEX_NOT_FOUND (-1).

\n *\n *
\n     * StringUtils.indexOf(null, *)         = -1\n     * StringUtils.indexOf(\"\", *)           = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'a') = 0\n     * StringUtils.indexOf(\"aabaabaa\", 'b') = 2\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return the first index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchChar);\n }\n\n /**\n *

Finds the first index within a String from a start position,\n * handling null.\n * This method uses {@link String#indexOf(int, int)}.

\n *\n *

A null or empty (\"\") String will return (INDEX_NOT_FOUND) -1.\n * A negative start position is treated as zero.\n * A start position greater than the string length returns -1.

\n *\n *
\n     * StringUtils.indexOf(null, *, *)          = -1\n     * StringUtils.indexOf(\"\", *, *)            = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 0)  = 2\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 3)  = 5\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 9)  = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'b', -1) = 2\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final char searchChar, final int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchChar, startPos);\n }\n\n /**\n *

Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n *
\n     * StringUtils.indexOf(null, *)          = -1\n     * StringUtils.indexOf(*, null)          = -1\n     * StringUtils.indexOf(\"\", \"\")           = 0\n     * StringUtils.indexOf(\"\", *)            = -1 (except when * = \"\")\n     * StringUtils.indexOf(\"aabaabaa\", \"a\")  = 0\n     * StringUtils.indexOf(\"aabaabaa\", \"b\")  = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"ab\") = 1\n     * StringUtils.indexOf(\"aabaabaa\", \"\")   = 0\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr);\n }\n\n /**\n *

Finds the n-th index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n *
\n     * StringUtils.ordinalIndexOf(null, *, *)          = -1\n     * StringUtils.ordinalIndexOf(*, null, *)          = -1\n     * StringUtils.ordinalIndexOf(\"\", \"\", *)           = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"a\", 1)  = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"a\", 2)  = 1\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"b\", 1)  = 2\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"b\", 2)  = 5\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"ab\", 1) = 1\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"ab\", 2) = 4\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"\", 1)   = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"\", 2)   = 0\n     * 
\n *\n *

Note that 'head(String str, int n)' may be implemented as:

\n *\n *
\n     *   str.substring(0, lastOrdinalIndexOf(str, \"\\n\", n))\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th searchStr to find\n * @return the n-th index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n * @since 2.1\n */\n public static int ordinalIndexOf(final String str, final String searchStr, final int ordinal) {\n return StringUtils.ordinalIndexOf(str, searchStr, ordinal, false);\n }\n\n /**\n *

Finds the n-th index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th searchStr to find\n * @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf()\n * @return the n-th index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n */\n // Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int)\n private static int ordinalIndexOf(final String str, final String searchStr, final int ordinal, final boolean lastIndex) {\n if (str == null || searchStr == null || ordinal <= 0) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return lastIndex ? str.length() : 0;\n }\n int found = 0;\n int index = lastIndex ? str.length() : StringUtils.INDEX_NOT_FOUND;\n do {\n if (lastIndex) {\n index = str.lastIndexOf(searchStr, index - 1);\n } else {\n index = str.indexOf(searchStr, index + 1);\n }\n if (index < 0) {\n return index;\n }\n found++;\n } while (found < ordinal);\n return index;\n }\n\n /**\n *

Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(String, int)}.

\n *\n *

A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

\n *\n *
\n     * StringUtils.indexOf(null, *, *)          = -1\n     * StringUtils.indexOf(*, null, *)          = -1\n     * StringUtils.indexOf(\"\", \"\", 0)           = 0\n     * StringUtils.indexOf(\"\", *, 0)            = -1 (except when * = \"\")\n     * StringUtils.indexOf(\"aabaabaa\", \"a\", 0)  = 0\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 0)  = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"ab\", 0) = 1\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 3)  = 5\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 9)  = -1\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", -1) = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"\", 2)   = 2\n     * StringUtils.indexOf(\"abc\", \"\", 9)        = 3\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final String searchStr, final int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n // JDK1.2/JDK1.3 have a bug, when startPos > str.length for \"\", hence\n if (searchStr.length() == 0 && startPos >= str.length()) {\n return str.length();\n }\n return str.indexOf(searchStr, startPos);\n }\n\n /**\n *

Case in-sensitive find of the first index within a String.

\n *\n *

A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

\n *\n *
\n     * StringUtils.indexOfIgnoreCase(null, *)          = -1\n     * StringUtils.indexOfIgnoreCase(*, null)          = -1\n     * StringUtils.indexOfIgnoreCase(\"\", \"\")           = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"a\")  = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"b\")  = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"ab\") = 1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int indexOfIgnoreCase(final String str, final String searchStr) {\n return StringUtils.indexOfIgnoreCase(str, searchStr, 0);\n }\n\n /**\n *

Case in-sensitive find of the first index within a String\n * from the specified position.

\n *\n *

A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

\n *\n *
\n     * StringUtils.indexOfIgnoreCase(null, *, *)          = -1\n     * StringUtils.indexOfIgnoreCase(*, null, *)          = -1\n     * StringUtils.indexOfIgnoreCase(\"\", \"\", 0)           = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"A\", 0)  = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 0)  = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"AB\", 0) = 1\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 3)  = 5\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 9)  = -1\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", -1) = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"\", 2)   = 2\n     * StringUtils.indexOfIgnoreCase(\"abc\", \"\", 9)        = 3\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int indexOfIgnoreCase(final String str, final String searchStr, int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (startPos < 0) {\n startPos = 0;\n }\n int endLimit = str.length() - searchStr.length() + 1;\n if (startPos > endLimit) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return startPos;\n }\n for (int i = startPos; i < endLimit; i++) {\n if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {\n return i;\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // LastIndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(int)}.

\n *\n *

A null or empty (\"\") String will return -1.

\n *\n *
\n     * StringUtils.lastIndexOf(null, *)         = -1\n     * StringUtils.lastIndexOf(\"\", *)           = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'a') = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b') = 5\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return the last index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar);\n }\n\n /**\n *

Finds the last index within a String from a start position,\n * handling null.\n * This method uses {@link String#lastIndexOf(int, int)}.

\n *\n *

A null or empty (\"\") String will return -1.\n * A negative start position returns -1.\n * A start position greater than the string length searches the whole string.

\n *\n *
\n     * StringUtils.lastIndexOf(null, *, *)          = -1\n     * StringUtils.lastIndexOf(\"\", *,  *)           = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 8)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 4)  = 2\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 0)  = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 9)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', -1) = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'a', 0)  = 0\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @param startPos the start position\n * @return the last index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final char searchChar, final int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar, startPos);\n }\n\n /**\n *

Finds the last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n *
\n     * StringUtils.lastIndexOf(null, *)          = -1\n     * StringUtils.lastIndexOf(*, null)          = -1\n     * StringUtils.lastIndexOf(\"\", \"\")           = 0\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\")  = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\")  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"ab\") = 4\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"\")   = 8\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the last index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr);\n }\n\n /**\n *

Finds the n-th last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n *
\n     * StringUtils.lastOrdinalIndexOf(null, *, *)          = -1\n     * StringUtils.lastOrdinalIndexOf(*, null, *)          = -1\n     * StringUtils.lastOrdinalIndexOf(\"\", \"\", *)           = 0\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"a\", 1)  = 7\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"a\", 2)  = 6\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"b\", 1)  = 5\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"b\", 2)  = 2\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"ab\", 1) = 4\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"ab\", 2) = 1\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"\", 1)   = 8\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"\", 2)   = 8\n     * 
\n *\n *

Note that 'tail(String str, int n)' may be implemented as:

\n *\n *
\n     *   str.substring(lastOrdinalIndexOf(str, \"\\n\", n) + 1)\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th last searchStr to find\n * @return the n-th last index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n * @since 2.5\n */\n public static int lastOrdinalIndexOf(final String str, final String searchStr, final int ordinal) {\n return StringUtils.ordinalIndexOf(str, searchStr, ordinal, true);\n }\n\n /**\n *

Finds the first index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String, int)}.

\n *\n *

A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

\n *\n *
\n     * StringUtils.lastIndexOf(null, *, *)          = -1\n     * StringUtils.lastIndexOf(*, null, *)          = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\", 8)  = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 8)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"ab\", 8) = 4\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 9)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", -1) = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\", 0)  = 0\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 0)  = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final String searchStr, final int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr, startPos);\n }\n\n /**\n *

Case in-sensitive find of the last index within a String.

\n *\n *

A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

\n *\n *
\n     * StringUtils.lastIndexOfIgnoreCase(null, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(*, null)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\")  = 7\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\")  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"AB\") = 4\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int lastIndexOfIgnoreCase(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return StringUtils.lastIndexOfIgnoreCase(str, searchStr, str.length());\n }\n\n /**\n *

Case in-sensitive find of the last index within a String\n * from the specified position.

\n *\n *

A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

\n *\n *
\n     * StringUtils.lastIndexOfIgnoreCase(null, *, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(*, null, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\", 8)  = 7\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 8)  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"AB\", 8) = 4\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 9)  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", -1) = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\", 0)  = 0\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 0)  = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int lastIndexOfIgnoreCase(final String str, final String searchStr, int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (startPos > str.length() - searchStr.length()) {\n startPos = str.length() - searchStr.length();\n }\n if (startPos < 0) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return startPos;\n }\n for (int i = startPos; i >= 0; i--) {\n if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {\n return i;\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // Contains\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if String contains a search character, handling null.\n * This method uses {@link String#indexOf(int)}.

\n *\n *

A null or empty (\"\") String will return false.

\n *\n *
\n     * StringUtils.contains(null, *)    = false\n     * StringUtils.contains(\"\", *)      = false\n     * StringUtils.contains(\"abc\", 'a') = true\n     * StringUtils.contains(\"abc\", 'z') = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return true if the String contains the search character,\n * false if not or null string input\n * @since 2.0\n */\n public static boolean contains(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return false;\n }\n return str.indexOf(searchChar) >= 0;\n }\n\n /**\n *

Checks if String contains a search String, handling null.\n * This method uses {@link String#indexOf(String)}.

\n *\n *

A null String will return false.

\n *\n *
\n     * StringUtils.contains(null, *)     = false\n     * StringUtils.contains(*, null)     = false\n     * StringUtils.contains(\"\", \"\")      = true\n     * StringUtils.contains(\"abc\", \"\")   = true\n     * StringUtils.contains(\"abc\", \"a\")  = true\n     * StringUtils.contains(\"abc\", \"z\")  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return true if the String contains the search String,\n * false if not or null string input\n * @since 2.0\n */\n public static boolean contains(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n return str.contains(searchStr);\n }\n\n /**\n *

Checks if String contains a search String irrespective of case,\n * handling null. Case-insensitivity is defined as by\n * {@link String#equalsIgnoreCase(String)}.\n *\n *

A null String will return false.

\n *\n *
\n     * StringUtils.contains(null, *) = false\n     * StringUtils.contains(*, null) = false\n     * StringUtils.contains(\"\", \"\") = true\n     * StringUtils.contains(\"abc\", \"\") = true\n     * StringUtils.contains(\"abc\", \"a\") = true\n     * StringUtils.contains(\"abc\", \"z\") = false\n     * StringUtils.contains(\"abc\", \"A\") = true\n     * StringUtils.contains(\"abc\", \"Z\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return true if the String contains the search String irrespective of\n * case or false if not or null string input\n */\n public static boolean containsIgnoreCase(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n int len = searchStr.length();\n int max = str.length() - len;\n for (int i = 0; i <= max; i++) {\n if (str.regionMatches(true, i, searchStr, 0, len)) {\n return true;\n }\n }\n return false;\n }\n // IndexOfAny chars\n //-----------------------------------------------------------------------\n\n /**\n *

Search a String to find the first index of any\n * character in the given set of characters.

\n *\n *

A null String will return -1.\n * A null or zero length search array will return -1.

\n *\n *
\n     * StringUtils.indexOfAny(null, *)                = -1\n     * StringUtils.indexOfAny(\"\", *)                  = -1\n     * StringUtils.indexOfAny(*, null)                = -1\n     * StringUtils.indexOfAny(*, [])                  = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\",['z','a']) = 0\n     * StringUtils.indexOfAny(\"zzabyycdxx\",['b','y']) = 3\n     * StringUtils.indexOfAny(\"aba\", ['z'])           = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAny(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) {\n // ch is a supplementary character\n if (searchChars[j + 1] == str.charAt(i + 1)) {\n return i;\n }\n } else {\n return i;\n }\n }\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Search a String to find the first index of any\n * character in the given set of characters.

\n *\n *

A null String will return -1.\n * A null search string will return -1.

\n *\n *
\n     * StringUtils.indexOfAny(null, *)            = -1\n     * StringUtils.indexOfAny(\"\", *)              = -1\n     * StringUtils.indexOfAny(*, null)            = -1\n     * StringUtils.indexOfAny(*, \"\")              = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", \"za\") = 0\n     * StringUtils.indexOfAny(\"zzabyycdxx\", \"by\") = 3\n     * StringUtils.indexOfAny(\"aba\",\"z\")          = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAny(final String str, final String searchChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return StringUtils.indexOfAny(str, searchChars.toCharArray());\n }\n // ContainsAny\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if the String contains any character in the given\n * set of characters.

\n *\n *

A null String will return false.\n * A null or zero length search array will return false.

\n *\n *
\n     * StringUtils.containsAny(null, *)                = false\n     * StringUtils.containsAny(\"\", *)                  = false\n     * StringUtils.containsAny(*, null)                = false\n     * StringUtils.containsAny(*, [])                  = false\n     * StringUtils.containsAny(\"zzabyycdxx\",['z','a']) = true\n     * StringUtils.containsAny(\"zzabyycdxx\",['b','y']) = true\n     * StringUtils.containsAny(\"aba\", ['z'])           = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the true if any of the chars are found,\n * false if no match or null input\n * @since 2.4\n */\n public static boolean containsAny(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return false;\n }\n int csLength = str.length();\n int searchLength = searchChars.length;\n int csLast = csLength - 1;\n int searchLast = searchLength - 1;\n for (int i = 0; i < csLength; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLength; j++) {\n if (searchChars[j] == ch) {\n if (CharUtils.isHighSurrogate(ch)) {\n if (j == searchLast) {\n // missing low surrogate, fine, like String.indexOf(String)\n return true;\n }\n if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) {\n return true;\n }\n } else {\n // ch is in the Basic Multilingual Plane\n return true;\n }\n }\n }\n }\n return false;\n }\n\n /**\n *

\n * Checks if the String contains any character in the given set of characters.\n *

\n *\n *

\n * A null String will return false. A null search string will return\n * false.\n *

\n *\n *
\n     * StringUtils.containsAny(null, *)            = false\n     * StringUtils.containsAny(\"\", *)              = false\n     * StringUtils.containsAny(*, null)            = false\n     * StringUtils.containsAny(*, \"\")              = false\n     * StringUtils.containsAny(\"zzabyycdxx\", \"za\") = true\n     * StringUtils.containsAny(\"zzabyycdxx\", \"by\") = true\n     * StringUtils.containsAny(\"aba\",\"z\")          = false\n     * 
\n *\n * @param str\n * the String to check, may be null\n * @param searchChars\n * the chars to search for, may be null\n * @return the true if any of the chars are found, false if no match or null input\n * @since 2.4\n */\n public static boolean containsAny(final String str, final String searchChars) {\n if (searchChars == null) {\n return false;\n }\n return StringUtils.containsAny(str, searchChars.toCharArray());\n }\n // IndexOfAnyBut chars\n //-----------------------------------------------------------------------\n\n /**\n *

Search a String to find the first index of any\n * character not in the given set of characters.

\n *\n *

A null String will return -1.\n * A null or zero length search array will return -1.

\n *\n *
\n     * StringUtils.indexOfAnyBut(null, *)                              = -1\n     * StringUtils.indexOfAnyBut(\"\", *)                                = -1\n     * StringUtils.indexOfAnyBut(*, null)                              = -1\n     * StringUtils.indexOfAnyBut(*, [])                                = -1\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", new char[] {'z', 'a'} ) = 3\n     * StringUtils.indexOfAnyBut(\"aba\", new char[] {'z'} )             = 0\n     * StringUtils.indexOfAnyBut(\"aba\", new char[] {'a', 'b'} )        = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAnyBut(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n outer:\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) {\n if (searchChars[j + 1] == str.charAt(i + 1)) {\n continue outer;\n }\n } else {\n continue outer;\n }\n }\n }\n return i;\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Search a String to find the first index of any\n * character not in the given set of characters.

\n *\n *

A null String will return -1.\n * A null or empty search string will return -1.

\n *\n *
\n     * StringUtils.indexOfAnyBut(null, *)            = -1\n     * StringUtils.indexOfAnyBut(\"\", *)              = -1\n     * StringUtils.indexOfAnyBut(*, null)            = -1\n     * StringUtils.indexOfAnyBut(*, \"\")              = -1\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", \"za\") = 3\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", \"\")   = -1\n     * StringUtils.indexOfAnyBut(\"aba\",\"ab\")         = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAnyBut(final String str, final String searchChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n char ch = str.charAt(i);\n boolean chFound = searchChars.indexOf(ch) >= 0;\n if (i + 1 < strLen && CharUtils.isHighSurrogate(ch)) {\n char ch2 = str.charAt(i + 1);\n if (chFound && searchChars.indexOf(ch2) < 0) {\n return i;\n }\n } else {\n if (!chFound) {\n return i;\n }\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // ContainsOnly\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if the String contains only certain characters.

\n *\n *

A null String will return false.\n * A null valid character array will return false.\n * An empty String (length()=0) always returns true.

\n *\n *
\n     * StringUtils.containsOnly(null, *)       = false\n     * StringUtils.containsOnly(*, null)       = false\n     * StringUtils.containsOnly(\"\", *)         = true\n     * StringUtils.containsOnly(\"ab\", '')      = false\n     * StringUtils.containsOnly(\"abab\", 'abc') = true\n     * StringUtils.containsOnly(\"ab1\", 'abc')  = false\n     * StringUtils.containsOnly(\"abz\", 'abc')  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param valid an array of valid chars, may be null\n * @return true if it only contains valid chars and is non-null\n */\n public static boolean containsOnly(final String str, final char[] valid) {\n // All these pre-checks are to maintain API with an older version\n if (valid == null || str == null) {\n return false;\n }\n if (str.length() == 0) {\n return true;\n }\n if (valid.length == 0) {\n return false;\n }\n return StringUtils.indexOfAnyBut(str, valid) == StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the String contains only certain characters.

\n *\n *

A null String will return false.\n * A null valid character String will return false.\n * An empty String (length()=0) always returns true.

\n *\n *
\n     * StringUtils.containsOnly(null, *)       = false\n     * StringUtils.containsOnly(*, null)       = false\n     * StringUtils.containsOnly(\"\", *)         = true\n     * StringUtils.containsOnly(\"ab\", \"\")      = false\n     * StringUtils.containsOnly(\"abab\", \"abc\") = true\n     * StringUtils.containsOnly(\"ab1\", \"abc\")  = false\n     * StringUtils.containsOnly(\"abz\", \"abc\")  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param validChars a String of valid chars, may be null\n * @return true if it only contains valid chars and is non-null\n * @since 2.0\n */\n public static boolean containsOnly(final String str, final String validChars) {\n if (str == null || validChars == null) {\n return false;\n }\n return StringUtils.containsOnly(str, validChars.toCharArray());\n }\n // ContainsNone\n //-----------------------------------------------------------------------\n\n /**\n *

Checks that the String does not contain certain characters.

\n *\n *

A null String will return true.\n * A null invalid character array will return true.\n * An empty String (length()=0) always returns true.

\n *\n *
\n     * StringUtils.containsNone(null, *)       = true\n     * StringUtils.containsNone(*, null)       = true\n     * StringUtils.containsNone(\"\", *)         = true\n     * StringUtils.containsNone(\"ab\", '')      = true\n     * StringUtils.containsNone(\"abab\", 'xyz') = true\n     * StringUtils.containsNone(\"ab1\", 'xyz')  = true\n     * StringUtils.containsNone(\"abz\", 'xyz')  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars an array of invalid chars, may be null\n * @return true if it contains none of the invalid chars, or is null\n * @since 2.0\n */\n public static boolean containsNone(final String str, final char[] searchChars) {\n if (str == null || searchChars == null) {\n return true;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (CharUtils.isHighSurrogate(ch)) {\n if (j == searchLast) {\n // missing low surrogate, fine, like String.indexOf(String)\n return false;\n }\n if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) {\n return false;\n }\n } else {\n // ch is in the Basic Multilingual Plane\n return false;\n }\n }\n }\n }\n return true;\n }\n\n /**\n *

Checks that the String does not contain certain characters.

\n *\n *

A null String will return true.\n * A null invalid character array will return true.\n * An empty String (\"\") always returns true.

\n *\n *
\n     * StringUtils.containsNone(null, *)       = true\n     * StringUtils.containsNone(*, null)       = true\n     * StringUtils.containsNone(\"\", *)         = true\n     * StringUtils.containsNone(\"ab\", \"\")      = true\n     * StringUtils.containsNone(\"abab\", \"xyz\") = true\n     * StringUtils.containsNone(\"ab1\", \"xyz\")  = true\n     * StringUtils.containsNone(\"abz\", \"xyz\")  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param invalidChars a String of invalid chars, may be null\n * @return true if it contains none of the invalid chars, or is null\n * @since 2.0\n */\n public static boolean containsNone(final String str, final String invalidChars) {\n if (str == null || invalidChars == null) {\n return true;\n }\n return StringUtils.containsNone(str, invalidChars.toCharArray());\n }\n // IndexOfAny strings\n //-----------------------------------------------------------------------\n\n /**\n *

Find the first index of any of a set of potential substrings.

\n *\n *

A null String will return -1.\n * A null or zero length search array will return -1.\n * A null search array entry will be ignored, but a search\n * array containing \"\" will return 0 if str is not\n * null. This method uses {@link String#indexOf(String)}.

\n *\n *
\n     * StringUtils.indexOfAny(null, *)                     = -1\n     * StringUtils.indexOfAny(*, null)                     = -1\n     * StringUtils.indexOfAny(*, [])                       = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"ab\",\"cd\"])   = 2\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"cd\",\"ab\"])   = 2\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"])   = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"zab\",\"aby\"]) = 1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"\"])          = 0\n     * StringUtils.indexOfAny(\"\", [\"\"])                    = 0\n     * StringUtils.indexOfAny(\"\", [\"a\"])                   = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStrs the Strings to search for, may be null\n * @return the first index of any of the searchStrs in str, -1 if no match\n */\n public static int indexOfAny(final String str, final String[] searchStrs) {\n if (str == null || searchStrs == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int sz = searchStrs.length;\n // String's can't have a MAX_VALUEth index.\n int ret = Integer.MAX_VALUE;\n int tmp = 0;\n for (int i = 0; i < sz; i++) {\n String search = searchStrs[i];\n if (search == null) {\n continue;\n }\n tmp = str.indexOf(search);\n if (tmp == StringUtils.INDEX_NOT_FOUND) {\n continue;\n }\n if (tmp < ret) {\n ret = tmp;\n }\n }\n return ret == Integer.MAX_VALUE ? StringUtils.INDEX_NOT_FOUND : ret;\n }\n\n /**\n *

Find the latest index of any of a set of potential substrings.

\n *\n *

A null String will return -1.\n * A null search array will return -1.\n * A null or zero length search array entry will be ignored,\n * but a search array containing \"\" will return the length of str\n * if str is not null. This method uses {@link String#indexOf(String)}

\n *\n *
\n     * StringUtils.lastIndexOfAny(null, *)                   = -1\n     * StringUtils.lastIndexOfAny(*, null)                   = -1\n     * StringUtils.lastIndexOfAny(*, [])                     = -1\n     * StringUtils.lastIndexOfAny(*, [null])                 = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"ab\",\"cd\"]) = 6\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"cd\",\"ab\"]) = 6\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"]) = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"]) = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"\"])   = 10\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStrs the Strings to search for, may be null\n * @return the last index of any of the Strings, -1 if no match\n */\n public static int lastIndexOfAny(final String str, final String[] searchStrs) {\n if (str == null || searchStrs == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int sz = searchStrs.length;\n int ret = StringUtils.INDEX_NOT_FOUND;\n int tmp = 0;\n for (int i = 0; i < sz; i++) {\n String search = searchStrs[i];\n if (search == null) {\n continue;\n }\n tmp = str.lastIndexOf(search);\n if (tmp > ret) {\n ret = tmp;\n }\n }\n return ret;\n }\n // Substring\n //-----------------------------------------------------------------------\n\n /**\n *

Gets a substring from the specified String avoiding exceptions.

\n *\n *

A negative start position can be used to start n\n * characters from the end of the String.

\n *\n *

A null String will return null.\n * An empty (\"\") String will return \"\".

\n *\n *
\n     * StringUtils.substring(null, *)   = null\n     * StringUtils.substring(\"\", *)     = \"\"\n     * StringUtils.substring(\"abc\", 0)  = \"abc\"\n     * StringUtils.substring(\"abc\", 2)  = \"c\"\n     * StringUtils.substring(\"abc\", 4)  = \"\"\n     * StringUtils.substring(\"abc\", -2) = \"bc\"\n     * StringUtils.substring(\"abc\", -4) = \"abc\"\n     * 
\n *\n * @param str the String to get the substring from, may be null\n * @param start the position to start from, negative means\n * count back from the end of the String by this many characters\n * @return substring from start position, null if null String input\n */\n public static String substring(final String str, int start) {\n if (str == null) {\n return null;\n }\n // handle negatives, which means last n characters\n if (start < 0) {\n start = str.length() + start; // remember start is negative\n }\n if (start < 0) {\n start = 0;\n }\n if (start > str.length()) {\n return StringUtils.EMPTY;\n }\n return str.substring(start);\n }\n\n /**\n *

Gets a substring from the specified String avoiding exceptions.

\n *\n *

A negative start position can be used to start/end n\n * characters from the end of the String.

\n *\n *

The returned substring starts with the character in the start\n * position and ends before the end position. All position counting is\n * zero-based -- i.e., to start at the beginning of the string use\n * start = 0. Negative start and end positions can be used to\n * specify offsets relative to the end of the String.

\n *\n *

If start is not strictly to the left of end, \"\"\n * is returned.

\n *\n *
\n     * StringUtils.substring(null, *, *)    = null\n     * StringUtils.substring(\"\", * ,  *)    = \"\";\n     * StringUtils.substring(\"abc\", 0, 2)   = \"ab\"\n     * StringUtils.substring(\"abc\", 2, 0)   = \"\"\n     * StringUtils.substring(\"abc\", 2, 4)   = \"c\"\n     * StringUtils.substring(\"abc\", 4, 6)   = \"\"\n     * StringUtils.substring(\"abc\", 2, 2)   = \"\"\n     * StringUtils.substring(\"abc\", -2, -1) = \"b\"\n     * StringUtils.substring(\"abc\", -4, 2)  = \"ab\"\n     * 
\n *\n * @param str the String to get the substring from, may be null\n * @param start the position to start from, negative means\n * count back from the end of the String by this many characters\n * @param end the position to end at (exclusive), negative means\n * count back from the end of the String by this many characters\n * @return substring from start position to end positon,\n * null if null String input\n */\n public static String substring(final String str, int start, int end) {\n if (str == null) {\n return null;\n }\n // handle negatives\n if (end < 0) {\n end = str.length() + end; // remember end is negative\n }\n if (start < 0) {\n start = str.length() + start; // remember start is negative\n }\n // check length next\n if (end > str.length()) {\n end = str.length();\n }\n // if start is greater than end, return \"\"\n if (start > end) {\n return StringUtils.EMPTY;\n }\n if (start < 0) {\n start = 0;\n }\n if (end < 0) {\n end = 0;\n }\n return str.substring(start, end);\n }\n // Left/Right/Mid\n //-----------------------------------------------------------------------\n\n /**\n *

Gets the leftmost len characters of a String.

\n *\n *

If len characters are not available, or the\n * String is null, the String will be returned without\n * an exception. An empty String is returned if len is negative.

\n *\n *
\n     * StringUtils.left(null, *)    = null\n     * StringUtils.left(*, -ve)     = \"\"\n     * StringUtils.left(\"\", *)      = \"\"\n     * StringUtils.left(\"abc\", 0)   = \"\"\n     * StringUtils.left(\"abc\", 2)   = \"ab\"\n     * StringUtils.left(\"abc\", 4)   = \"abc\"\n     * 
\n *\n * @param str the String to get the leftmost characters from, may be null\n * @param len the length of the required String\n * @return the leftmost characters, null if null String input\n */\n public static String left(final String str, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0) {\n return StringUtils.EMPTY;\n }\n if (str.length() <= len) {\n return str;\n }\n return str.substring(0, len);\n }\n\n /**\n *

Gets the rightmost len characters of a String.

\n *\n *

If len characters are not available, or the String\n * is null, the String will be returned without an\n * an exception. An empty String is returned if len is negative.

\n *\n *
\n     * StringUtils.right(null, *)    = null\n     * StringUtils.right(*, -ve)     = \"\"\n     * StringUtils.right(\"\", *)      = \"\"\n     * StringUtils.right(\"abc\", 0)   = \"\"\n     * StringUtils.right(\"abc\", 2)   = \"bc\"\n     * StringUtils.right(\"abc\", 4)   = \"abc\"\n     * 
\n *\n * @param str the String to get the rightmost characters from, may be null\n * @param len the length of the required String\n * @return the rightmost characters, null if null String input\n */\n public static String right(final String str, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0) {\n return StringUtils.EMPTY;\n }\n if (str.length() <= len) {\n return str;\n }\n return str.substring(str.length() - len);\n }\n\n /**\n *

Gets len characters from the middle of a String.

\n *\n *

If len characters are not available, the remainder\n * of the String will be returned without an exception. If the\n * String is null, null will be returned.\n * An empty String is returned if len is negative or exceeds the\n * length of str.

\n *\n *
\n     * StringUtils.mid(null, *, *)    = null\n     * StringUtils.mid(*, *, -ve)     = \"\"\n     * StringUtils.mid(\"\", 0, *)      = \"\"\n     * StringUtils.mid(\"abc\", 0, 2)   = \"ab\"\n     * StringUtils.mid(\"abc\", 0, 4)   = \"abc\"\n     * StringUtils.mid(\"abc\", 2, 4)   = \"c\"\n     * StringUtils.mid(\"abc\", 4, 2)   = \"\"\n     * StringUtils.mid(\"abc\", -2, 2)  = \"ab\"\n     * 
\n *\n * @param str the String to get the characters from, may be null\n * @param pos the position to start from, negative treated as zero\n * @param len the length of the required String\n * @return the middle characters, null if null String input\n */\n public static String mid(final String str, int pos, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0 || pos > str.length()) {\n return StringUtils.EMPTY;\n }\n if (pos < 0) {\n pos = 0;\n }\n if (str.length() <= pos + len) {\n return str.substring(pos);\n }\n return str.substring(pos, pos + len);\n }\n // SubStringAfter/SubStringBefore\n //-----------------------------------------------------------------------\n\n /**\n *

Gets the substring before the first occurrence of a separator.\n * The separator is not returned.

\n *\n *

A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * A null separator will return the input string.

\n *\n *

If nothing is found, the string input is returned.

\n *\n *
\n     * StringUtils.substringBefore(null, *)      = null\n     * StringUtils.substringBefore(\"\", *)        = \"\"\n     * StringUtils.substringBefore(\"abc\", \"a\")   = \"\"\n     * StringUtils.substringBefore(\"abcba\", \"b\") = \"a\"\n     * StringUtils.substringBefore(\"abc\", \"c\")   = \"ab\"\n     * StringUtils.substringBefore(\"abc\", \"d\")   = \"abc\"\n     * StringUtils.substringBefore(\"abc\", \"\")    = \"\"\n     * StringUtils.substringBefore(\"abc\", null)  = \"abc\"\n     * 
\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring before the first occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringBefore(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || separator == null) {\n return str;\n }\n if (separator.length() == 0) {\n return StringUtils.EMPTY;\n }\n int pos = str.indexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n return str.substring(0, pos);\n }\n\n /**\n *

Gets the substring after the first occurrence of a separator.\n * The separator is not returned.

\n *\n *

A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * A null separator will return the empty string if the\n * input string is not null.

\n *\n *

If nothing is found, the empty string is returned.

\n *\n *
\n     * StringUtils.substringAfter(null, *)      = null\n     * StringUtils.substringAfter(\"\", *)        = \"\"\n     * StringUtils.substringAfter(*, null)      = \"\"\n     * StringUtils.substringAfter(\"abc\", \"a\")   = \"bc\"\n     * StringUtils.substringAfter(\"abcba\", \"b\") = \"cba\"\n     * StringUtils.substringAfter(\"abc\", \"c\")   = \"\"\n     * StringUtils.substringAfter(\"abc\", \"d\")   = \"\"\n     * StringUtils.substringAfter(\"abc\", \"\")    = \"abc\"\n     * 
\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring after the first occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringAfter(final String str, final String separator) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (separator == null) {\n return StringUtils.EMPTY;\n }\n int pos = str.indexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return StringUtils.EMPTY;\n }\n return str.substring(pos + separator.length());\n }\n\n /**\n *

Gets the substring before the last occurrence of a separator.\n * The separator is not returned.

\n *\n *

A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * An empty or null separator will return the input string.

\n *\n *

If nothing is found, the string input is returned.

\n *\n *
\n     * StringUtils.substringBeforeLast(null, *)      = null\n     * StringUtils.substringBeforeLast(\"\", *)        = \"\"\n     * StringUtils.substringBeforeLast(\"abcba\", \"b\") = \"abc\"\n     * StringUtils.substringBeforeLast(\"abc\", \"c\")   = \"ab\"\n     * StringUtils.substringBeforeLast(\"a\", \"a\")     = \"\"\n     * StringUtils.substringBeforeLast(\"a\", \"z\")     = \"a\"\n     * StringUtils.substringBeforeLast(\"a\", null)    = \"a\"\n     * StringUtils.substringBeforeLast(\"a\", \"\")      = \"a\"\n     * 
\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring before the last occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringBeforeLast(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(separator)) {\n return str;\n }\n int pos = str.lastIndexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n return str.substring(0, pos);\n }\n\n /**\n *

Gets the substring after the last occurrence of a separator.\n * The separator is not returned.

\n *\n *

A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * An empty or null separator will return the empty string if\n * the input string is not null.

\n *\n *

If nothing is found, the empty string is returned.

\n *\n *
\n     * StringUtils.substringAfterLast(null, *)      = null\n     * StringUtils.substringAfterLast(\"\", *)        = \"\"\n     * StringUtils.substringAfterLast(*, \"\")        = \"\"\n     * StringUtils.substringAfterLast(*, null)      = \"\"\n     * StringUtils.substringAfterLast(\"abc\", \"a\")   = \"bc\"\n     * StringUtils.substringAfterLast(\"abcba\", \"b\") = \"a\"\n     * StringUtils.substringAfterLast(\"abc\", \"c\")   = \"\"\n     * StringUtils.substringAfterLast(\"a\", \"a\")     = \"\"\n     * StringUtils.substringAfterLast(\"a\", \"z\")     = \"\"\n     * 
\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring after the last occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringAfterLast(final String str, final String separator) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (StringUtils.isEmpty(separator)) {\n return StringUtils.EMPTY;\n }\n int pos = str.lastIndexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND || pos == str.length() - separator.length()) {\n return StringUtils.EMPTY;\n }\n return str.substring(pos + separator.length());\n }\n // Substring between\n //-----------------------------------------------------------------------\n\n /**\n *

Gets the String that is nested in between two instances of the\n * same String.

\n *\n *

A null input String returns null.\n * A null tag returns null.

\n *\n *
\n     * StringUtils.substringBetween(null, *)            = null\n     * StringUtils.substringBetween(\"\", \"\")             = \"\"\n     * StringUtils.substringBetween(\"\", \"tag\")          = null\n     * StringUtils.substringBetween(\"tagabctag\", null)  = null\n     * StringUtils.substringBetween(\"tagabctag\", \"\")    = \"\"\n     * StringUtils.substringBetween(\"tagabctag\", \"tag\") = \"abc\"\n     * 
\n *\n * @param str the String containing the substring, may be null\n * @param tag the String before and after the substring, may be null\n * @return the substring, null if no match\n * @since 2.0\n */\n public static String substringBetween(final String str, final String tag) {\n return StringUtils.substringBetween(str, tag, tag);\n }\n\n /**\n *

Gets the String that is nested in between two Strings.\n * Only the first match is returned.

\n *\n *

A null input String returns null.\n * A null open/close returns null (no match).\n * An empty (\"\") open and close returns an empty string.

\n *\n *
\n     * StringUtils.substringBetween(\"wx[b]yz\", \"[\", \"]\") = \"b\"\n     * StringUtils.substringBetween(null, *, *)          = null\n     * StringUtils.substringBetween(*, null, *)          = null\n     * StringUtils.substringBetween(*, *, null)          = null\n     * StringUtils.substringBetween(\"\", \"\", \"\")          = \"\"\n     * StringUtils.substringBetween(\"\", \"\", \"]\")         = null\n     * StringUtils.substringBetween(\"\", \"[\", \"]\")        = null\n     * StringUtils.substringBetween(\"yabcz\", \"\", \"\")     = \"\"\n     * StringUtils.substringBetween(\"yabcz\", \"y\", \"z\")   = \"abc\"\n     * StringUtils.substringBetween(\"yabczyabcz\", \"y\", \"z\")   = \"abc\"\n     * 
\n *\n * @param str the String containing the substring, may be null\n * @param open the String before the substring, may be null\n * @param close the String after the substring, may be null\n * @return the substring, null if no match\n * @since 2.0\n */\n public static String substringBetween(final String str, final String open, final String close) {\n if (str == null || open == null || close == null) {\n return null;\n }\n int start = str.indexOf(open);\n if (start != StringUtils.INDEX_NOT_FOUND) {\n int end = str.indexOf(close, start + open.length());\n if (end != StringUtils.INDEX_NOT_FOUND) {\n return str.substring(start + open.length(), end);\n }\n }\n return null;\n }\n\n /**\n *

Searches a String for substrings delimited by a start and end tag,\n * returning all matching substrings in an array.

\n *\n *

A null input String returns null.\n * A null open/close returns null (no match).\n * An empty (\"\") open/close returns null (no match).

\n *\n *
\n     * StringUtils.substringsBetween(\"[a][b][c]\", \"[\", \"]\") = [\"a\",\"b\",\"c\"]\n     * StringUtils.substringsBetween(null, *, *)            = null\n     * StringUtils.substringsBetween(*, null, *)            = null\n     * StringUtils.substringsBetween(*, *, null)            = null\n     * StringUtils.substringsBetween(\"\", \"[\", \"]\")          = []\n     * 
\n *\n * @param str the String containing the substrings, null returns null, empty returns empty\n * @param open the String identifying the start of the substring, empty returns null\n * @param close the String identifying the end of the substring, empty returns null\n * @return a String Array of substrings, or null if no match\n * @since 2.3\n */\n public static String[] substringsBetween(final String str, final String open, final String close) {\n if (str == null || StringUtils.isEmpty(open) || StringUtils.isEmpty(close)) {\n return null;\n }\n int strLen = str.length();\n if (strLen == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n int closeLen = close.length();\n int openLen = open.length();\n List list = new ArrayList();\n int pos = 0;\n while (pos < strLen - closeLen) {\n int start = str.indexOf(open, pos);\n if (start < 0) {\n break;\n }\n start += openLen;\n int end = str.indexOf(close, start);\n if (end < 0) {\n break;\n }\n list.add(str.substring(start, end));\n pos = end + closeLen;\n }\n if (list.isEmpty()) {\n return null;\n }\n return list.toArray(new String[list.size()]);\n }\n // Splitting\n //-----------------------------------------------------------------------\n\n /**\n *

Splits the provided text into an array, using whitespace as the separator. but keep separator.

\n *\n *
\n     * StringUtils.splitKeep(null)          = null\n     * StringUtils.splitKeep(\"\")            = []\n     * StringUtils.splitKeep(\"a b c\", \" \")  = [\"a\", \" \", \"b\", \" \", \"c\"]\n     * StringUtils.splitKeep(\"abc def\", \" \")= [\"abc\", \" \", \"def\"]\n     * StringUtils.splitKeep(\" abc \", \" \")  = [\" \", \"abc\", \" \"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] splitKeep(String str, char separatorChar) {\n return splitKeep(str, String.valueOf(separatorChar));\n }\n\n /**\n *

Splits the provided text into an array, using whitespace as the separator. but keep separator.

\n *\n *
\n     * StringUtils.splitKeep(null)          = null\n     * StringUtils.splitKeep(\"\")            = []\n     * StringUtils.splitKeep(\"a b c\", \" \")  = [\"a\", \" \", \"b\", \" \", \"c\"]\n     * StringUtils.splitKeep(\"abc def\", \" \")= [\"abc\", \" \", \"def\"]\n     * StringUtils.splitKeep(\" abc \", \" \")  = [\" \", \"abc\", \" \"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] splitKeep(String str, String separatorStr) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n int CHARS = separatorStr.length();\n if (CHARS == 0) {\n throw new IllegalArgumentException(\"chars must be > 0\");\n }\n int lastIndex = 0;\n ArrayList dat = new ArrayList<>();\n while (true) {\n int lookIndex = str.indexOf(separatorStr, lastIndex);\n if (lookIndex == -1) {\n String substring = str.substring(lastIndex);\n if (substring.length() > 0) {\n dat.add(substring);\n }\n break;\n } else {\n if (lastIndex != lookIndex) {\n String term = str.substring(lastIndex, lookIndex);\n dat.add(term);\n }\n dat.add(separatorStr);\n lastIndex = lookIndex + CHARS;\n }\n }\n return dat.toArray(new String[0]);\n }\n\n /**\n *

Splits the provided text into an array, using whitespace as the\n * separator.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.split(null)       = null\n     * StringUtils.split(\"\")         = []\n     * StringUtils.split(\"abc def\")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\") = [\"abc\", \"def\"]\n     * StringUtils.split(\" abc \")    = [\"abc\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str) {\n return StringUtils.split(str, null, -1);\n }\n\n /**\n *

Splits the provided text into an array, separator specified.\n * This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"a.b.c\", '.')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.split(\"a..b.c\", '.')   = [\"a\", \"b\", \"c\"]\n     * StringUtils.split(\"a:b:c\", '.')    = [\"a:b:c\"]\n     * StringUtils.split(\"a b c\", ' ')    = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChar the character used as the delimiter\n * @return an array of parsed Strings, null if null String input\n * @since 2.0\n */\n public static String[] split(final String str, final char separatorChar) {\n return StringUtils.splitWorker(str, separatorChar, false);\n }\n\n /**\n *

Splits the provided text into an array, separators specified.\n * This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *
\n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"abc def\", null) = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc def\", \" \")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\", \" \") = [\"abc\", \"def\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\") = [\"ab\", \"cd\", \"ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str, final String separatorChars) {\n return StringUtils.splitWorker(str, separatorChars, -1, false);\n }\n\n /**\n *

Splits the provided text into an array with a maximum length,\n * separators specified.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *

If more than max delimited substrings are found, the last\n * returned string includes all characters after the first max - 1\n * returned strings (including separator characters).

\n *\n *
\n     * StringUtils.split(null, *, *)            = null\n     * StringUtils.split(\"\", *, *)              = []\n     * StringUtils.split(\"ab de fg\", null, 0)   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab   de fg\", null, 0) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\", 0)    = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\", 2)    = [\"ab\", \"cd:ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str, final String separatorChars, final int max) {\n return StringUtils.splitWorker(str, separatorChars, max, false);\n }\n\n /**\n *

Splits the provided text into an array, separator string specified.

\n *\n *

The separator(s) will not be included in the returned String array.\n * Adjacent separators are treated as one separator.

\n *\n *

A null input String returns null.\n * A null separator splits on whitespace.

\n *\n *
\n     * StringUtils.splitByWholeSeparator(null, *)               = null\n     * StringUtils.splitByWholeSeparator(\"\", *)                 = []\n     * StringUtils.splitByWholeSeparator(\"ab de fg\", null)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab   de fg\", null)    = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab:cd:ef\", \":\")       = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\") = [\"ab\", \"cd\", \"ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String was input\n */\n public static String[] splitByWholeSeparator(final String str, final String separator) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, -1, false);\n }\n\n /**\n *

Splits the provided text into an array, separator string specified.\n * Returns a maximum of max substrings.

\n *\n *

The separator(s) will not be included in the returned String array.\n * Adjacent separators are treated as one separator.

\n *\n *

A null input String returns null.\n * A null separator splits on whitespace.

\n *\n *
\n     * StringUtils.splitByWholeSeparator(null, *, *)               = null\n     * StringUtils.splitByWholeSeparator(\"\", *, *)                 = []\n     * StringUtils.splitByWholeSeparator(\"ab de fg\", null, 0)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab   de fg\", null, 0)    = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab:cd:ef\", \":\", 2)       = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\", 5) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\", 2) = [\"ab\", \"cd-!-ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @return an array of parsed Strings, null if null String was input\n */\n public static String[] splitByWholeSeparator(final String str, final String separator, final int max) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, max, false);\n }\n\n /**\n *

Splits the provided text into an array, separator string specified.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separator splits on whitespace.

\n *\n *
\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *)               = null\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"\", *)                 = []\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab de fg\", null)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab   de fg\", null)    = [\"ab\", \"\", \"\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab:cd:ef\", \":\")       = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\") = [\"ab\", \"cd\", \"ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String was input\n * @since 2.4\n */\n public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, -1, true);\n }\n\n /**\n *

Splits the provided text into an array, separator string specified.\n * Returns a maximum of max substrings.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separator splits on whitespace.

\n *\n *
\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *)               = null\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"\", *, *)                 = []\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab de fg\", null, 0)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab   de fg\", null, 0)    = [\"ab\", \"\", \"\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab:cd:ef\", \":\", 2)       = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\", 5) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\", 2) = [\"ab\", \"cd-!-ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @return an array of parsed Strings, null if null String was input\n * @since 2.4\n */\n public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator, final int max) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, max, true);\n }\n\n /**\n * Performs the logic for the splitByWholeSeparatorPreserveAllTokens methods.\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n private static String[] splitByWholeSeparatorWorker(final String str, final String separator, final int max, final boolean preserveAllTokens) {\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n if (separator == null || StringUtils.EMPTY.equals(separator)) {\n // Split on whitespace.\n return StringUtils.splitWorker(str, null, max, preserveAllTokens);\n }\n int separatorLength = separator.length();\n ArrayList substrings = new ArrayList<>();\n int numberOfSubstrings = 0;\n int beg = 0;\n int end = 0;\n while (end < len) {\n end = str.indexOf(separator, beg);\n if (end > -1) {\n if (end > beg) {\n numberOfSubstrings += 1;\n if (numberOfSubstrings == max) {\n end = len;\n substrings.add(str.substring(beg));\n } else {\n // The following is OK, because String.substring( beg, end ) excludes\n // the character at the position 'end'.\n substrings.add(str.substring(beg, end));\n // Set the starting point for the next search.\n // The following is equivalent to beg = end + (separatorLength - 1) + 1,\n // which is the right calculation:\n beg = end + separatorLength;\n }\n } else {\n // We found a consecutive occurrence of the separator, so skip it.\n if (preserveAllTokens) {\n numberOfSubstrings += 1;\n if (numberOfSubstrings == max) {\n end = len;\n substrings.add(str.substring(beg));\n } else {\n substrings.add(StringUtils.EMPTY);\n }\n }\n beg = end + separatorLength;\n }\n } else {\n // String.substring( beg ) goes from 'beg' to the end of the String.\n substrings.add(str.substring(beg));\n end = len;\n }\n }\n return substrings.toArray(new String[0]);\n }\n // -----------------------------------------------------------------------\n\n /**\n *

Splits the provided text into an array, using whitespace as the\n * separator, preserving all tokens, including empty tokens created by\n * adjacent separators. This is an alternative to using StringTokenizer.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.splitPreserveAllTokens(null)       = null\n     * StringUtils.splitPreserveAllTokens(\"\")         = []\n     * StringUtils.splitPreserveAllTokens(\"abc def\")  = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc  def\") = [\"abc\", \"\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\" abc \")    = [\"\", \"abc\", \"\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str) {\n return StringUtils.splitWorker(str, null, -1, true);\n }\n\n /**\n *

Splits the provided text into an array, separator specified,\n * preserving all tokens, including empty tokens created by adjacent\n * separators. This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.splitPreserveAllTokens(null, *)         = null\n     * StringUtils.splitPreserveAllTokens(\"\", *)           = []\n     * StringUtils.splitPreserveAllTokens(\"a.b.c\", '.')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a..b.c\", '.')   = [\"a\", \"\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a:b:c\", '.')    = [\"a:b:c\"]\n     * StringUtils.splitPreserveAllTokens(\"a\\tb\\nc\", null) = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c\", ' ')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c \", ' ')   = [\"a\", \"b\", \"c\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c  \", ' ')   = [\"a\", \"b\", \"c\", \"\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\" a b c\", ' ')   = [\"\", a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"  a b c\", ' ')  = [\"\", \"\", a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\" a b c \", ' ')  = [\"\", a\", \"b\", \"c\", \"\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChar the character used as the delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final char separatorChar) {\n return StringUtils.splitWorker(str, separatorChar, true);\n }\n\n /**\n * Performs the logic for the split and\n * splitPreserveAllTokens methods that do not return a\n * maximum array length.\n *\n * @param str the String to parse, may be null\n * @param separatorChar the separate character\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n */\n private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n List list = new ArrayList<>();\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n while (i < len) {\n if (str.charAt(i) == separatorChar) {\n if (match || preserveAllTokens) {\n list.add(str.substring(start, i));\n match = false;\n lastMatch = true;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[0]);\n }\n\n /**\n *

Splits the provided text into an array, separators specified,\n * preserving all tokens, including empty tokens created by adjacent\n * separators. This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *
\n     * StringUtils.splitPreserveAllTokens(null, *)           = null\n     * StringUtils.splitPreserveAllTokens(\"\", *)             = []\n     * StringUtils.splitPreserveAllTokens(\"abc def\", null)   = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc def\", \" \")    = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc  def\", \" \")   = [\"abc\", \"\", def\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\")   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef:\", \":\")  = [\"ab\", \"cd\", \"ef\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef::\", \":\") = [\"ab\", \"cd\", \"ef\", \"\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"ab::cd:ef\", \":\")  = [\"ab\", \"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\":cd:ef\", \":\")     = [\"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"::cd:ef\", \":\")    = [\"\", \"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\":cd:ef:\", \":\")    = [\"\", cd\", \"ef\", \"\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final String separatorChars) {\n return StringUtils.splitWorker(str, separatorChars, -1, true);\n }\n\n /**\n *

Splits the provided text into an array with a maximum length,\n * separators specified, preserving all tokens, including empty tokens\n * created by adjacent separators.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * Adjacent separators are treated as one separator.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *

If more than max delimited substrings are found, the last\n * returned string includes all characters after the first max - 1\n * returned strings (including separator characters).

\n *\n *
\n     * StringUtils.splitPreserveAllTokens(null, *, *)            = null\n     * StringUtils.splitPreserveAllTokens(\"\", *, *)              = []\n     * StringUtils.splitPreserveAllTokens(\"ab de fg\", null, 0)   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 0) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\", 0)    = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\", 2)    = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 2) = [\"ab\", \"  de fg\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 3) = [\"ab\", \"\", \" de fg\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 4) = [\"ab\", \"\", \"\", \"de fg\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) {\n return StringUtils.splitWorker(str, separatorChars, max, true);\n }\n\n /**\n * Performs the logic for the split and\n * splitPreserveAllTokens methods that return a maximum array\n * length.\n *\n * @param str the String to parse, may be null\n * @param separatorChars the separate character\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit.\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n */\n private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n // Direct code is quicker than StringTokenizer.\n // Also, StringTokenizer uses isSpace() not isWhitespace()\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n List list = new ArrayList<>();\n int sizePlus1 = 1;\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n if (separatorChars == null) {\n // Null separator means use whitespace\n while (i < len) {\n if (Character.isWhitespace(str.charAt(i))) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else if (separatorChars.length() == 1) {\n // Optimise 1 character case\n char sep = separatorChars.charAt(0);\n while (i < len) {\n if (str.charAt(i) == sep) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else {\n // standard case\n while (i < len) {\n if (separatorChars.indexOf(str.charAt(i)) >= 0) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[0]);\n }\n\n /**\n *

Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens.\n *

\n     * StringUtils.splitByCharacterType(null)         = null\n     * StringUtils.splitByCharacterType(\"\")           = []\n     * StringUtils.splitByCharacterType(\"ab de fg\")   = [\"ab\", \" \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterType(\"ab   de fg\") = [\"ab\", \"   \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterType(\"ab:cd:ef\")   = [\"ab\", \":\", \"cd\", \":\", \"ef\"]\n     * StringUtils.splitByCharacterType(\"number5\")    = [\"number\", \"5\"]\n     * StringUtils.splitByCharacterType(\"fooBar\")     = [\"foo\", \"B\", \"ar\"]\n     * StringUtils.splitByCharacterType(\"foo200Bar\")  = [\"foo\", \"200\", \"B\", \"ar\"]\n     * StringUtils.splitByCharacterType(\"ASFRules\")   = [\"ASFR\", \"ules\"]\n     * 
\n * @param str the String to split, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n public static String[] splitByCharacterType(final String str) {\n return StringUtils.splitByCharacterType(str, false);\n }\n\n /**\n *

Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens, with the\n * following exception: the character of type\n * Character.UPPERCASE_LETTER, if any, immediately\n * preceding a token of type Character.LOWERCASE_LETTER\n * will belong to the following token rather than to the preceding, if any,\n * Character.UPPERCASE_LETTER token.\n *

\n     * StringUtils.splitByCharacterTypeCamelCase(null)         = null\n     * StringUtils.splitByCharacterTypeCamelCase(\"\")           = []\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab de fg\")   = [\"ab\", \" \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab   de fg\") = [\"ab\", \"   \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab:cd:ef\")   = [\"ab\", \":\", \"cd\", \":\", \"ef\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"number5\")    = [\"number\", \"5\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"fooBar\")     = [\"foo\", \"Bar\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"foo200Bar\")  = [\"foo\", \"200\", \"Bar\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ASFRules\")   = [\"ASF\", \"Rules\"]\n     * 
\n * @param str the String to split, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n public static String[] splitByCharacterTypeCamelCase(final String str) {\n return StringUtils.splitByCharacterType(str, true);\n }\n\n /**\n *

Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens, with the\n * following exception: if camelCase is true,\n * the character of type Character.UPPERCASE_LETTER, if any,\n * immediately preceding a token of type Character.LOWERCASE_LETTER\n * will belong to the following token rather than to the preceding, if any,\n * Character.UPPERCASE_LETTER token.\n * @param str the String to split, may be null\n * @param camelCase whether to use so-called \"camel-case\" for letter types\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n private static String[] splitByCharacterType(final String str, final boolean camelCase) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n char[] c = str.toCharArray();\n List list = new ArrayList();\n int tokenStart = 0;\n int currentType = Character.getType(c[tokenStart]);\n for (int pos = tokenStart + 1; pos < c.length; pos++) {\n int type = Character.getType(c[pos]);\n if (type == currentType) {\n continue;\n }\n if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) {\n int newTokenStart = pos - 1;\n if (newTokenStart != tokenStart) {\n list.add(new String(c, tokenStart, newTokenStart - tokenStart));\n tokenStart = newTokenStart;\n }\n } else {\n list.add(new String(c, tokenStart, pos - tokenStart));\n tokenStart = pos;\n }\n currentType = type;\n }\n list.add(new String(c, tokenStart, c.length - tokenStart));\n return list.toArray(new String[0]);\n }\n // Joining\n //-----------------------------------------------------------------------\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No separator is added to the joined String.\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null)            = null\n     * StringUtils.join([])              = \"\"\n     * StringUtils.join([null])          = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"]) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"]) = \"a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array) {\n return StringUtils.join(array, null);\n }\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No delimiter is added before or after the list.\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null, *)               = null\n     * StringUtils.join([], *)                 = \"\"\n     * StringUtils.join([null], *)             = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], ';')  = \"a;b;c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ';')  = \";;a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array, final char separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array, separator, 0, array.length);\n }\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No delimiter is added before or after the list.\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null, *)               = null\n     * StringUtils.join([], *)                 = \"\"\n     * StringUtils.join([null], *)             = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], ';')  = \"a;b;c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ';')  = \";;a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use\n * @param startIndex the first index to start joining from. It is\n * an error to pass in an end index past the end of the array\n * @param endIndex the index to stop joining from (exclusive). It is\n * an error to pass in an end index past the end of the array\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) {\n if (array == null) {\n return null;\n }\n int bufSize = endIndex - startIndex;\n if (bufSize <= 0) {\n return StringUtils.EMPTY;\n }\n bufSize *= (array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1;\n StringBuilder buf = new StringBuilder(bufSize);\n for (int i = startIndex; i < endIndex; i++) {\n if (i > startIndex) {\n buf.append(separator);\n }\n if (array[i] != null) {\n buf.append(array[i]);\n }\n }\n return buf.toString();\n }\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No delimiter is added before or after the list.\n * A null separator is the same as an empty String (\"\").\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null, *)                = null\n     * StringUtils.join([], *)                  = \"\"\n     * StringUtils.join([null], *)              = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"--\")  = \"a--b--c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null)  = \"abc\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"\")    = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ',')   = \",,a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use, null treated as \"\"\n * @return the joined String, null if null array input\n */\n public static String join(final Object[] array, final String separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array, separator, 0, array.length);\n }\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No delimiter is added before or after the list.\n * A null separator is the same as an empty String (\"\").\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null, *)                = null\n     * StringUtils.join([], *)                  = \"\"\n     * StringUtils.join([null], *)              = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"--\")  = \"a--b--c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null)  = \"abc\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"\")    = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ',')   = \",,a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use, null treated as \"\"\n * @param startIndex the first index to start joining from. It is\n * an error to pass in an end index past the end of the array\n * @param endIndex the index to stop joining from (exclusive). It is\n * an error to pass in an end index past the end of the array\n * @return the joined String, null if null array input\n */\n public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {\n if (array == null) {\n return null;\n }\n if (separator == null) {\n separator = StringUtils.EMPTY;\n }\n // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))\n // (Assuming that all Strings are roughly equally long)\n int bufSize = endIndex - startIndex;\n if (bufSize <= 0) {\n return StringUtils.EMPTY;\n }\n bufSize *= (array[startIndex] == null ? 16 : array[startIndex].toString().length()) + separator.length();\n StringBuilder buf = new StringBuilder(bufSize);\n for (int i = startIndex; i < endIndex; i++) {\n if (i > startIndex) {\n buf.append(separator);\n }\n if (array[i] != null) {\n buf.append(array[i]);\n }\n }\n return buf.toString();\n }\n // Delete\n //-----------------------------------------------------------------------\n\n /**\n *

Deletes all whitespaces from a String as defined by\n * {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.deleteWhitespace(null)         = null\n     * StringUtils.deleteWhitespace(\"\")           = \"\"\n     * StringUtils.deleteWhitespace(\"abc\")        = \"abc\"\n     * StringUtils.deleteWhitespace(\"   ab  c  \") = \"abc\"\n     * 
\n *\n * @param str the String to delete whitespace from, may be null\n * @return the String without whitespaces, null if null String input\n */\n public static String deleteWhitespace(final String str) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n int sz = str.length();\n char[] chs = new char[sz];\n int count = 0;\n for (int i = 0; i < sz; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n chs[count++] = str.charAt(i);\n }\n }\n if (count == sz) {\n return str;\n }\n return new String(chs, 0, count);\n }\n // Remove\n //-----------------------------------------------------------------------\n\n /**\n *

Removes a substring only if it is at the begining of a source string,\n * otherwise returns the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

\n *\n *
\n     * StringUtils.removeStart(null, *)      = null\n     * StringUtils.removeStart(\"\", *)        = \"\"\n     * StringUtils.removeStart(*, null)      = *\n     * StringUtils.removeStart(\"www.domain.com\", \"www.\")   = \"domain.com\"\n     * StringUtils.removeStart(\"domain.com\", \"www.\")       = \"domain.com\"\n     * StringUtils.removeStart(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeStart(\"abc\", \"\")    = \"abc\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String removeStart(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (str.startsWith(remove)) {\n return str.substring(remove.length());\n }\n return str;\n }\n\n /**\n *

Case insensitive removal of a substring if it is at the begining of a source string,\n * otherwise returns the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

\n *\n *
\n     * StringUtils.removeStartIgnoreCase(null, *)      = null\n     * StringUtils.removeStartIgnoreCase(\"\", *)        = \"\"\n     * StringUtils.removeStartIgnoreCase(*, null)      = *\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"www.\")   = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"WWW.\")   = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"domain.com\", \"www.\")       = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"abc\", \"\")    = \"abc\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for (case insensitive) and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.4\n */\n public static String removeStartIgnoreCase(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (StringUtils.startsWithIgnoreCase(str, remove)) {\n return str.substring(remove.length());\n }\n return str;\n }\n\n /**\n *

Removes a substring only if it is at the end of a source string,\n * otherwise returns the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

\n *\n *
\n     * StringUtils.removeEnd(null, *)      = null\n     * StringUtils.removeEnd(\"\", *)        = \"\"\n     * StringUtils.removeEnd(*, null)      = *\n     * StringUtils.removeEnd(\"www.domain.com\", \".com.\")  = \"www.domain.com\"\n     * StringUtils.removeEnd(\"www.domain.com\", \".com\")   = \"www.domain\"\n     * StringUtils.removeEnd(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeEnd(\"abc\", \"\")    = \"abc\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String removeEnd(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (str.endsWith(remove)) {\n return str.substring(0, str.length() - remove.length());\n }\n return str;\n }\n\n /**\n *

Case insensitive removal of a substring if it is at the end of a source string,\n * otherwise returns the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

\n *\n *
\n     * StringUtils.removeEndIgnoreCase(null, *)      = null\n     * StringUtils.removeEndIgnoreCase(\"\", *)        = \"\"\n     * StringUtils.removeEndIgnoreCase(*, null)      = *\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".com.\")  = \"www.domain.com\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".com\")   = \"www.domain\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeEndIgnoreCase(\"abc\", \"\")    = \"abc\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".COM\") = \"www.domain\")\n     * StringUtils.removeEndIgnoreCase(\"www.domain.COM\", \".com\") = \"www.domain\")\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for (case insensitive) and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.4\n */\n public static String removeEndIgnoreCase(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (StringUtils.endsWithIgnoreCase(str, remove)) {\n return str.substring(0, str.length() - remove.length());\n }\n return str;\n }\n\n /**\n *

Removes all occurrences of a substring from within the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null remove string will return the source string.\n * An empty (\"\") remove string will return the source string.

\n *\n *
\n     * StringUtils.remove(null, *)        = null\n     * StringUtils.remove(\"\", *)          = \"\"\n     * StringUtils.remove(*, null)        = *\n     * StringUtils.remove(*, \"\")          = *\n     * StringUtils.remove(\"queued\", \"ue\") = \"qd\"\n     * StringUtils.remove(\"queued\", \"zz\") = \"queued\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String remove(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n return StringUtils.replace(str, remove, StringUtils.EMPTY, -1);\n }\n\n /**\n *

Removes all occurrences of a character from within the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.

\n *\n *
\n     * StringUtils.remove(null, *)       = null\n     * StringUtils.remove(\"\", *)         = \"\"\n     * StringUtils.remove(\"queued\", 'u') = \"qeed\"\n     * StringUtils.remove(\"queued\", 'z') = \"queued\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the char to search for and remove, may be null\n * @return the substring with the char removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String remove(final String str, final char remove) {\n if (StringUtils.isEmpty(str) || str.indexOf(remove) == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n char[] chars = str.toCharArray();\n int pos = 0;\n for (int i = 0; i < chars.length; i++) {\n if (chars[i] != remove) {\n chars[pos++] = chars[i];\n }\n }\n return new String(chars, 0, pos);\n }\n // Replacing\n //-----------------------------------------------------------------------\n\n /**\n *

Replaces a String with another String inside a larger String, once.

\n *\n *

A null reference passed to this method is a no-op.

\n *\n *
\n     * StringUtils.replaceOnce(null, *, *)        = null\n     * StringUtils.replaceOnce(\"\", *, *)          = \"\"\n     * StringUtils.replaceOnce(\"any\", null, *)    = \"any\"\n     * StringUtils.replaceOnce(\"any\", *, null)    = \"any\"\n     * StringUtils.replaceOnce(\"any\", \"\", *)      = \"any\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", null)  = \"aba\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", \"\")    = \"ba\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", \"z\")   = \"zba\"\n     * 
\n *\n * @see #replace(String text, String searchString, String replacement, int max)\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace with, may be null\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replaceOnce(final String text, final String searchString, final String replacement) {\n return StringUtils.replace(text, searchString, replacement, 1);\n }\n\n /**\n *

Replaces all occurrences of a String within another String.

\n *\n *

A null reference passed to this method is a no-op.

\n *\n *
\n     * StringUtils.replace(null, *, *)        = null\n     * StringUtils.replace(\"\", *, *)          = \"\"\n     * StringUtils.replace(\"any\", null, *)    = \"any\"\n     * StringUtils.replace(\"any\", *, null)    = \"any\"\n     * StringUtils.replace(\"any\", \"\", *)      = \"any\"\n     * StringUtils.replace(\"aba\", \"a\", null)  = \"aba\"\n     * StringUtils.replace(\"aba\", \"a\", \"\")    = \"b\"\n     * StringUtils.replace(\"aba\", \"a\", \"z\")   = \"zbz\"\n     * 
\n *\n * @see #replace(String text, String searchString, String replacement, int max)\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace it with, may be null\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replace(final String text, final String searchString, final String replacement) {\n return StringUtils.replace(text, searchString, replacement, -1);\n }\n\n /**\n *

Replaces a String with another String inside a larger String,\n * for the first max values of the search String.

\n *\n *

A null reference passed to this method is a no-op.

\n *\n *
\n     * StringUtils.replace(null, *, *, *)         = null\n     * StringUtils.replace(\"\", *, *, *)           = \"\"\n     * StringUtils.replace(\"any\", null, *, *)     = \"any\"\n     * StringUtils.replace(\"any\", *, null, *)     = \"any\"\n     * StringUtils.replace(\"any\", \"\", *, *)       = \"any\"\n     * StringUtils.replace(\"any\", *, *, 0)        = \"any\"\n     * StringUtils.replace(\"abaa\", \"a\", null, -1) = \"abaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"\", -1)   = \"b\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 0)   = \"abaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 1)   = \"zbaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 2)   = \"zbza\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", -1)  = \"zbzz\"\n     * 
\n *\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace it with, may be null\n * @param max maximum number of values to replace, or -1 if no maximum\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replace(final String text, final String searchString, final String replacement, int max) {\n if (StringUtils.isEmpty(text) || StringUtils.isEmpty(searchString) || replacement == null || max == 0) {\n return text;\n }\n int start = 0;\n int end = text.indexOf(searchString, start);\n if (end == StringUtils.INDEX_NOT_FOUND) {\n return text;\n }\n int replLength = searchString.length();\n int increase = replacement.length() - replLength;\n increase = Math.max(increase, 0);\n increase *= max < 0 ? 16 : Math.min(max, 64);\n StringBuilder buf = new StringBuilder(text.length() + increase);\n while (end != StringUtils.INDEX_NOT_FOUND) {\n buf.append(text.substring(start, end)).append(replacement);\n start = end + replLength;\n if (--max == 0) {\n break;\n }\n end = text.indexOf(searchString, start);\n }\n buf.append(text.substring(start));\n return buf.toString();\n }\n\n /**\n *

\n * Replaces all occurrences of Strings within another String.\n *

\n *\n *

\n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored. This will not repeat. For repeating replaces, call the\n * overloaded method.\n *

\n *\n *
\n     *  StringUtils.replaceEach(null, *, *)        = null\n     *  StringUtils.replaceEach(\"\", *, *)          = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0]) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null)  = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"})  = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"})  = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"})  = \"wcte\"\n     *  (example of how it does not repeat)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"})  = \"dcte\"\n     * 
\n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) {\n return StringUtils.replaceEach(text, searchList, replacementList, false, 0);\n }\n\n /**\n *

\n * Replaces all occurrences of Strings within another String.\n *

\n *\n *

\n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored. This will not repeat. For repeating replaces, call the\n * overloaded method.\n *

\n *\n *
\n     *  StringUtils.replaceEach(null, *, *, *) = null\n     *  StringUtils.replaceEach(\"\", *, *, *) = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0], *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"}, *) = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"}, *) = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"}, *) = \"wcte\"\n     *  (example of how it repeats)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, false) = \"dcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, true) = \"tcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, true) = IllegalArgumentException\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, false) = \"dcabe\"\n     * 
\n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IllegalArgumentException\n * if the search is repeating and there is an endless loop due\n * to outputs of one being inputs to another\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) {\n // timeToLive should be 0 if not used or nothing to replace, else it's\n // the length of the replace array\n int timeToLive = searchList == null ? 0 : searchList.length;\n return StringUtils.replaceEach(text, searchList, replacementList, true, timeToLive);\n }\n\n /**\n *

\n * Replaces all occurrences of Strings within another String.\n *

\n *\n *

\n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored.\n *

\n *\n *
\n     *  StringUtils.replaceEach(null, *, *, *) = null\n     *  StringUtils.replaceEach(\"\", *, *, *) = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0], *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"}, *) = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"}, *) = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"}, *) = \"wcte\"\n     *  (example of how it repeats)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, false) = \"dcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, true) = \"tcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, *) = IllegalArgumentException\n     * 
\n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @param repeat if true, then replace repeatedly\n * until there are no more possible replacements or timeToLive < 0\n * @param timeToLive\n * if less than 0 then there is a circular reference and endless\n * loop\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IllegalArgumentException\n * if the search is repeating and there is an endless loop due\n * to outputs of one being inputs to another\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n private static String replaceEach(final String text, final String[] searchList, final String[] replacementList, final boolean repeat, final int timeToLive) {\n // mchyzer Performance note: This creates very few new objects (one major goal)\n // let me know if there are performance requests, we can create a harness to measure\n if (text == null || text.length() == 0 || searchList == null || searchList.length == 0 || replacementList == null || replacementList.length == 0) {\n return text;\n }\n // if recursing, this shouldnt be less than 0\n if (timeToLive < 0) {\n throw new IllegalStateException(\"TimeToLive of \" + timeToLive + \" is less than 0: \" + text);\n }\n int searchLength = searchList.length;\n int replacementLength = replacementList.length;\n // make sure lengths are ok, these need to be equal\n if (searchLength != replacementLength) {\n throw new IllegalArgumentException(\"Search and Replace array lengths don't match: \" + searchLength + \" vs \" + replacementLength);\n }\n // keep track of which still have matches\n boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];\n // index on index that the match was found\n int textIndex = -1;\n int replaceIndex = -1;\n int tempIndex = -1;\n // index of replace array that will replace the search string found\n // NOTE: logic duplicated below START\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) {\n continue;\n }\n tempIndex = text.indexOf(searchList[i]);\n // see if we need to keep searching for this\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n // NOTE: logic mostly below END\n // no search strings found, we are done\n if (textIndex == -1) {\n return text;\n }\n int start = 0;\n // get a good guess on the size of the result buffer so it doesnt have to double if it goes over a bit\n int increase = 0;\n // count the replacement text elements that are larger than their corresponding text being replaced\n for (int i = 0; i < searchList.length; i++) {\n if (searchList[i] == null || replacementList[i] == null) {\n continue;\n }\n int greater = replacementList[i].length() - searchList[i].length();\n if (greater > 0) {\n increase += 3 * greater; // assume 3 matches\n }\n }\n // have upper-bound at 20% increase, then let Java take over\n increase = Math.min(increase, text.length() / 5);\n StringBuilder buf = new StringBuilder(text.length() + increase);\n while (textIndex != -1) {\n for (int i = start; i < textIndex; i++) {\n buf.append(text.charAt(i));\n }\n buf.append(replacementList[replaceIndex]);\n start = textIndex + searchList[replaceIndex].length();\n textIndex = -1;\n replaceIndex = -1;\n tempIndex = -1;\n // find the next earliest match\n // NOTE: logic mostly duplicated above START\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) {\n continue;\n }\n tempIndex = text.indexOf(searchList[i], start);\n // see if we need to keep searching for this\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n // NOTE: logic duplicated above END\n }\n int textLength = text.length();\n for (int i = start; i < textLength; i++) {\n buf.append(text.charAt(i));\n }\n String result = buf.toString();\n if (!repeat) {\n return result;\n }\n return StringUtils.replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);\n }\n // Replace, character based\n //-----------------------------------------------------------------------\n\n /**\n *

Replaces all occurrences of a character in a String with another.\n * This is a null-safe version of {@link String#replace(char, char)}.

\n *\n *

A null string input returns null.\n * An empty (\"\") string input returns an empty string.

\n *\n *
\n     * StringUtils.replaceChars(null, *, *)        = null\n     * StringUtils.replaceChars(\"\", *, *)          = \"\"\n     * StringUtils.replaceChars(\"abcba\", 'b', 'y') = \"aycya\"\n     * StringUtils.replaceChars(\"abcba\", 'z', 'y') = \"abcba\"\n     * 
\n *\n * @param str String to replace characters in, may be null\n * @param searchChar the character to search for, may be null\n * @param replaceChar the character to replace, may be null\n * @return modified String, null if null string input\n * @since 2.0\n */\n public static String replaceChars(final String str, final char searchChar, final char replaceChar) {\n if (str == null) {\n return null;\n }\n return str.replace(searchChar, replaceChar);\n }\n\n /**\n *

Replaces multiple characters in a String in one go.\n * This method can also be used to delete characters.

\n *\n *

For example:
\n * replaceChars("hello", "ho", "jy") = jelly.

\n *\n *

A null string input returns null.\n * An empty (\"\") string input returns an empty string.\n * A null or empty set of search characters returns the input string.

\n *\n *

The length of the search characters should normally equal the length\n * of the replace characters.\n * If the search characters is longer, then the extra search characters\n * are deleted.\n * If the search characters is shorter, then the extra replace characters\n * are ignored.

\n *\n *
\n     * StringUtils.replaceChars(null, *, *)           = null\n     * StringUtils.replaceChars(\"\", *, *)             = \"\"\n     * StringUtils.replaceChars(\"abc\", null, *)       = \"abc\"\n     * StringUtils.replaceChars(\"abc\", \"\", *)         = \"abc\"\n     * StringUtils.replaceChars(\"abc\", \"b\", null)     = \"ac\"\n     * StringUtils.replaceChars(\"abc\", \"b\", \"\")       = \"ac\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"yz\")  = \"ayzya\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"y\")   = \"ayya\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"yzx\") = \"ayzya\"\n     * 
\n *\n * @param str String to replace characters in, may be null\n * @param searchChars a set of characters to search for, may be null\n * @param replaceChars a set of characters to replace, may be null\n * @return modified String, null if null string input\n * @since 2.0\n */\n public static String replaceChars(final String str, final String searchChars, String replaceChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return str;\n }\n if (replaceChars == null) {\n replaceChars = StringUtils.EMPTY;\n }\n boolean modified = false;\n int replaceCharsLength = replaceChars.length();\n int strLength = str.length();\n StringBuilder buf = new StringBuilder(strLength);\n for (int i = 0; i < strLength; i++) {\n char ch = str.charAt(i);\n int index = searchChars.indexOf(ch);\n if (index >= 0) {\n modified = true;\n if (index < replaceCharsLength) {\n buf.append(replaceChars.charAt(index));\n }\n } else {\n buf.append(ch);\n }\n }\n if (modified) {\n return buf.toString();\n }\n return str;\n }\n // Overlay\n //-----------------------------------------------------------------------\n\n /**\n *

Overlays part of a String with another String.

\n *\n *

A null string input returns null.\n * A negative index is treated as zero.\n * An index greater than the string length is treated as the string length.\n * The start index is always the smaller of the two indices.

\n *\n *
\n     * StringUtils.overlay(null, *, *, *)            = null\n     * StringUtils.overlay(\"\", \"abc\", 0, 0)          = \"abc\"\n     * StringUtils.overlay(\"abcdef\", null, 2, 4)     = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"\", 2, 4)       = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"\", 4, 2)       = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 2, 4)   = \"abzzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 4, 2)   = \"abzzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", -1, 4)  = \"zzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 2, 8)   = \"abzzzz\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", -2, -3) = \"zzzzabcdef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 8, 10)  = \"abcdefzzzz\"\n     * 
\n *\n * @param str the String to do overlaying in, may be null\n * @param overlay the String to overlay, may be null\n * @param start the position to start overlaying at\n * @param end the position to stop overlaying before\n * @return overlayed String, null if null String input\n * @since 2.0\n */\n public static String overlay(final String str, String overlay, int start, int end) {\n if (str == null) {\n return null;\n }\n if (overlay == null) {\n overlay = StringUtils.EMPTY;\n }\n int len = str.length();\n if (start < 0) {\n start = 0;\n }\n if (start > len) {\n start = len;\n }\n if (end < 0) {\n end = 0;\n }\n if (end > len) {\n end = len;\n }\n if (start > end) {\n int temp = start;\n start = end;\n end = temp;\n }\n return str.substring(0, start) + overlay + str.substring(end);\n }\n // Chomping\n //-----------------------------------------------------------------------\n\n /**\n *

Removes one newline from end of a String if it's there,\n * otherwise leave it alone. A newline is "\\n",\n * "\\r", or "\\r\\n".

\n *\n *

NOTE: This method changed in 2.0.\n * It now more closely matches Perl chomp.

\n *\n *
\n     * StringUtils.chomp(null)          = null\n     * StringUtils.chomp(\"\")            = \"\"\n     * StringUtils.chomp(\"abc \\r\")      = \"abc \"\n     * StringUtils.chomp(\"abc\\n\")       = \"abc\"\n     * StringUtils.chomp(\"abc\\r\\n\")     = \"abc\"\n     * StringUtils.chomp(\"abc\\r\\n\\r\\n\") = \"abc\\r\\n\"\n     * StringUtils.chomp(\"abc\\n\\r\")     = \"abc\\n\"\n     * StringUtils.chomp(\"abc\\n\\rabc\")  = \"abc\\n\\rabc\"\n     * StringUtils.chomp(\"\\r\")          = \"\"\n     * StringUtils.chomp(\"\\n\")          = \"\"\n     * StringUtils.chomp(\"\\r\\n\")        = \"\"\n     * 
\n *\n * @param str the String to chomp a newline from, may be null\n * @return String without newline, null if null String input\n */\n public static String chomp(final String str) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (str.length() == 1) {\n char ch = str.charAt(0);\n if (ch == CharUtils.CR || ch == CharUtils.LF) {\n return StringUtils.EMPTY;\n }\n return str;\n }\n int lastIdx = str.length() - 1;\n char last = str.charAt(lastIdx);\n if (last == CharUtils.LF) {\n if (str.charAt(lastIdx - 1) == CharUtils.CR) {\n lastIdx--;\n }\n } else if (last != CharUtils.CR) {\n lastIdx++;\n }\n return str.substring(0, lastIdx);\n }\n\n /**\n *

Removes separator from the end of\n * str if it's there, otherwise leave it alone.

\n *\n *

NOTE: This method changed in version 2.0.\n * It now more closely matches Perl chomp.\n * For the previous behavior, use {@link #substringBeforeLast(String, String)}.\n * This method uses {@link String#endsWith(String)}.

\n *\n *
\n     * StringUtils.chomp(null, *)         = null\n     * StringUtils.chomp(\"\", *)           = \"\"\n     * StringUtils.chomp(\"foobar\", \"bar\") = \"foo\"\n     * StringUtils.chomp(\"foobar\", \"baz\") = \"foobar\"\n     * StringUtils.chomp(\"foo\", \"foo\")    = \"\"\n     * StringUtils.chomp(\"foo \", \"foo\")   = \"foo \"\n     * StringUtils.chomp(\" foo\", \"foo\")   = \" \"\n     * StringUtils.chomp(\"foo\", \"foooo\")  = \"foo\"\n     * StringUtils.chomp(\"foo\", \"\")       = \"foo\"\n     * StringUtils.chomp(\"foo\", null)     = \"foo\"\n     * 
\n *\n * @param str the String to chomp from, may be null\n * @param separator separator String, may be null\n * @return String without trailing separator, null if null String input\n */\n public static String chomp(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || separator == null) {\n return str;\n }\n if (str.endsWith(separator)) {\n return str.substring(0, str.length() - separator.length());\n }\n return str;\n }\n // Chopping\n //-----------------------------------------------------------------------\n\n /**\n *

Remove the last character from a String.

\n *\n *

If the String ends in \\r\\n, then remove both\n * of them.

\n *\n *
\n     * StringUtils.chop(null)          = null\n     * StringUtils.chop(\"\")            = \"\"\n     * StringUtils.chop(\"abc \\r\")      = \"abc \"\n     * StringUtils.chop(\"abc\\n\")       = \"abc\"\n     * StringUtils.chop(\"abc\\r\\n\")     = \"abc\"\n     * StringUtils.chop(\"abc\")         = \"ab\"\n     * StringUtils.chop(\"abc\\nabc\")    = \"abc\\nab\"\n     * StringUtils.chop(\"a\")           = \"\"\n     * StringUtils.chop(\"\\r\")          = \"\"\n     * StringUtils.chop(\"\\n\")          = \"\"\n     * StringUtils.chop(\"\\r\\n\")        = \"\"\n     * 
\n *\n * @param str the String to chop last character from, may be null\n * @return String without last character, null if null String input\n */\n public static String chop(final String str) {\n if (str == null) {\n return null;\n }\n int strLen = str.length();\n if (strLen < 2) {\n return StringUtils.EMPTY;\n }\n int lastIdx = strLen - 1;\n String ret = str.substring(0, lastIdx);\n char last = str.charAt(lastIdx);\n if (last == CharUtils.LF) {\n if (ret.charAt(lastIdx - 1) == CharUtils.CR) {\n return ret.substring(0, lastIdx - 1);\n }\n }\n return ret;\n }\n // Padding\n //-----------------------------------------------------------------------\n\n /**\n *

Repeat a String repeat times to form a\n * new String.

\n *\n *
\n     * StringUtils.repeat(null, 2) = null\n     * StringUtils.repeat(\"\", 0)   = \"\"\n     * StringUtils.repeat(\"\", 2)   = \"\"\n     * StringUtils.repeat(\"a\", 3)  = \"aaa\"\n     * StringUtils.repeat(\"ab\", 2) = \"abab\"\n     * StringUtils.repeat(\"a\", -2) = \"\"\n     * 
\n *\n * @param character the Character to to repeat, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n */\n public static String repeat(final char character, final int repeat) {\n return repeat(character + \"\", repeat);\n }\n\n /**\n *

Repeat a String repeat times to form a\n * new String.

\n *\n *
\n     * StringUtils.repeat(null, 2) = null\n     * StringUtils.repeat(\"\", 0)   = \"\"\n     * StringUtils.repeat(\"\", 2)   = \"\"\n     * StringUtils.repeat(\"a\", 3)  = \"aaa\"\n     * StringUtils.repeat(\"ab\", 2) = \"abab\"\n     * StringUtils.repeat(\"a\", -2) = \"\"\n     * 
\n *\n * @param str the String to repeat, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n */\n public static String repeat(final String str, final int repeat) {\n // Performance tuned for 2.0 (JDK1.4)\n if (str == null) {\n return null;\n }\n if (repeat <= 0) {\n return StringUtils.EMPTY;\n }\n int inputLength = str.length();\n if (repeat == 1 || inputLength == 0) {\n return str;\n }\n if (inputLength == 1 && repeat <= StringUtils.PAD_LIMIT) {\n return StringUtils.padding(repeat, str.charAt(0));\n }\n int outputLength = inputLength * repeat;\n switch (inputLength) {\n case 1:\n char ch = str.charAt(0);\n char[] output1 = new char[outputLength];\n for (int i = repeat - 1; i >= 0; i--) {\n output1[i] = ch;\n }\n return new String(output1);\n case 2:\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n char[] output2 = new char[outputLength];\n for (int i = repeat * 2 - 2; i >= 0; i--, i--) {\n output2[i] = ch0;\n output2[i + 1] = ch1;\n }\n return new String(output2);\n default:\n StringBuilder buf = new StringBuilder(outputLength);\n for (int i = 0; i < repeat; i++) {\n buf.append(str);\n }\n return buf.toString();\n }\n }\n\n /**\n *

Repeat a String repeat times to form a\n * new String, with a String separator injected each time.

\n *\n *
\n     * StringUtils.repeat(null, null, 2) = null\n     * StringUtils.repeat(null, \"x\", 2)  = null\n     * StringUtils.repeat(\"\", null, 0)   = \"\"\n     * StringUtils.repeat(\"\", \"\", 2)     = \"\"\n     * StringUtils.repeat(\"\", \"x\", 3)    = \"xxx\"\n     * StringUtils.repeat(\"?\", \", \", 3)  = \"?, ?, ?\"\n     * 
\n *\n * @param str the String to repeat, may be null\n * @param separator the String to inject, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n * @since 2.5\n */\n public static String repeat(final String str, final String separator, final int repeat) {\n if (str == null || separator == null) {\n return StringUtils.repeat(str, repeat);\n } else {\n // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it\n String result = StringUtils.repeat(str + separator, repeat);\n return StringUtils.removeEnd(result, separator);\n }\n }\n\n /**\n *

Returns padding using the specified delimiter repeated\n * to a given length.

\n *\n *
\n     * StringUtils.padding(0, 'e')  = \"\"\n     * StringUtils.padding(3, 'e')  = \"eee\"\n     * StringUtils.padding(-2, 'e') = IndexOutOfBoundsException\n     * 
\n *\n *

Note: this method doesn't not support padding with\n * Unicode Supplementary Characters\n * as they require a pair of chars to be represented.\n * If you are needing to support full I18N of your applications\n * consider using {@link #repeat(String, int)} instead.\n *

\n *\n * @param repeat number of times to repeat delim\n * @param padChar character to repeat\n * @return String with repeated character\n * @throws IndexOutOfBoundsException if repeat < 0\n * @see #repeat(String, int)\n */\n private static String padding(final int repeat, final char padChar) throws IndexOutOfBoundsException {\n if (repeat < 0) {\n throw new IndexOutOfBoundsException(\"Cannot pad a negative amount: \" + repeat);\n }\n final char[] buf = new char[repeat];\n Arrays.fill(buf, padChar);\n return new String(buf);\n }\n\n /**\n *

Right pad a String with spaces (' ').

\n *\n *

The String is padded to the size of size.

\n *\n *
\n     * StringUtils.rightPad(null, *)   = null\n     * StringUtils.rightPad(\"\", 3)     = \"   \"\n     * StringUtils.rightPad(\"bat\", 3)  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5)  = \"bat  \"\n     * StringUtils.rightPad(\"bat\", 1)  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1) = \"bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String rightPad(final String str, final int size) {\n return StringUtils.rightPad(str, size, ' ');\n }\n\n /**\n *

Right pad a String with a specified character.

\n *\n *

The String is padded to the size of size.

\n *\n *
\n     * StringUtils.rightPad(null, *, *)     = null\n     * StringUtils.rightPad(\"\", 3, 'z')     = \"zzz\"\n     * StringUtils.rightPad(\"bat\", 3, 'z')  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, 'z')  = \"batzz\"\n     * StringUtils.rightPad(\"bat\", 1, 'z')  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1, 'z') = \"bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padChar the character to pad with\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n * @since 2.0\n */\n public static String rightPad(final String str, final int size, final char padChar) {\n if (str == null) {\n return null;\n }\n int pads = size - str.length();\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (pads > StringUtils.PAD_LIMIT) {\n return StringUtils.rightPad(str, size, String.valueOf(padChar));\n }\n return str.concat(StringUtils.padding(pads, padChar));\n }\n\n /**\n *

Right pad a String with a specified String.

\n *\n *

The String is padded to the size of size.

\n *\n *
\n     * StringUtils.rightPad(null, *, *)      = null\n     * StringUtils.rightPad(\"\", 3, \"z\")      = \"zzz\"\n     * StringUtils.rightPad(\"bat\", 3, \"yz\")  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, \"yz\")  = \"batyz\"\n     * StringUtils.rightPad(\"bat\", 8, \"yz\")  = \"batyzyzy\"\n     * StringUtils.rightPad(\"bat\", 1, \"yz\")  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1, \"yz\") = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, null)  = \"bat  \"\n     * StringUtils.rightPad(\"bat\", 5, \"\")    = \"bat  \"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padStr the String to pad with, null or empty treated as single space\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String rightPad(final String str, final int size, String padStr) {\n if (str == null) {\n return null;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int padLen = padStr.length();\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (padLen == 1 && pads <= StringUtils.PAD_LIMIT) {\n return StringUtils.rightPad(str, size, padStr.charAt(0));\n }\n if (pads == padLen) {\n return str.concat(padStr);\n } else if (pads < padLen) {\n return str.concat(padStr.substring(0, pads));\n } else {\n char[] padding = new char[pads];\n char[] padChars = padStr.toCharArray();\n for (int i = 0; i < pads; i++) {\n padding[i] = padChars[i % padLen];\n }\n return str.concat(new String(padding));\n }\n }\n\n /**\n *

Left pad a String with spaces (' ').

\n *\n *

The String is padded to the size of size.

\n *\n *
\n     * StringUtils.leftPad(null, *)   = null\n     * StringUtils.leftPad(\"\", 3)     = \"   \"\n     * StringUtils.leftPad(\"bat\", 3)  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5)  = \"  bat\"\n     * StringUtils.leftPad(\"bat\", 1)  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1) = \"bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String leftPad(final String str, final int size) {\n return StringUtils.leftPad(str, size, ' ');\n }\n\n /**\n *

Left pad a String with a specified character.

\n *\n *

Pad to a size of size.

\n *\n *
\n     * StringUtils.leftPad(null, *, *)     = null\n     * StringUtils.leftPad(\"\", 3, 'z')     = \"zzz\"\n     * StringUtils.leftPad(\"bat\", 3, 'z')  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, 'z')  = \"zzbat\"\n     * StringUtils.leftPad(\"bat\", 1, 'z')  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1, 'z') = \"bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padChar the character to pad with\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n * @since 2.0\n */\n public static String leftPad(final String str, final int size, final char padChar) {\n if (str == null) {\n return null;\n }\n int pads = size - str.length();\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (pads > StringUtils.PAD_LIMIT) {\n return StringUtils.leftPad(str, size, String.valueOf(padChar));\n }\n return StringUtils.padding(pads, padChar).concat(str);\n }\n\n /**\n *

Left pad a String with a specified String.

\n *\n *

Pad to a size of size.

\n *\n *
\n     * StringUtils.leftPad(null, *, *)      = null\n     * StringUtils.leftPad(\"\", 3, \"z\")      = \"zzz\"\n     * StringUtils.leftPad(\"bat\", 3, \"yz\")  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, \"yz\")  = \"yzbat\"\n     * StringUtils.leftPad(\"bat\", 8, \"yz\")  = \"yzyzybat\"\n     * StringUtils.leftPad(\"bat\", 1, \"yz\")  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1, \"yz\") = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, null)  = \"  bat\"\n     * StringUtils.leftPad(\"bat\", 5, \"\")    = \"  bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padStr the String to pad with, null or empty treated as single space\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String leftPad(final String str, final int size, String padStr) {\n if (str == null) {\n return null;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int padLen = padStr.length();\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (padLen == 1 && pads <= StringUtils.PAD_LIMIT) {\n return StringUtils.leftPad(str, size, padStr.charAt(0));\n }\n if (pads == padLen) {\n return padStr.concat(str);\n } else if (pads < padLen) {\n return padStr.substring(0, pads).concat(str);\n } else {\n char[] padding = new char[pads];\n char[] padChars = padStr.toCharArray();\n for (int i = 0; i < pads; i++) {\n padding[i] = padChars[i % padLen];\n }\n return new String(padding).concat(str);\n }\n }\n\n /**\n * Gets a String's length or 0 if the String is null.\n *\n * @param str\n * a String or null\n * @return String length or 0 if the String is null.\n * @since 2.4\n */\n public static int length(final String str) {\n return str == null ? 0 : str.length();\n }\n // Centering\n //-----------------------------------------------------------------------\n\n /**\n *

Centers a String in a larger String of size size\n * using the space character (' ').

\n *\n *

If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

\n *\n *

Equivalent to center(str, size, \" \").

\n *\n *
\n     * StringUtils.center(null, *)   = null\n     * StringUtils.center(\"\", 4)     = \"    \"\n     * StringUtils.center(\"ab\", -1)  = \"ab\"\n     * StringUtils.center(\"ab\", 4)   = \" ab \"\n     * StringUtils.center(\"abcd\", 2) = \"abcd\"\n     * StringUtils.center(\"a\", 4)    = \" a  \"\n     * 
\n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @return centered String, null if null String input\n */\n public static String center(final String str, final int size) {\n return StringUtils.center(str, size, ' ');\n }\n\n /**\n *

Centers a String in a larger String of size size.\n * Uses a supplied character as the value to pad the String with.

\n *\n *

If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

\n *\n *
\n     * StringUtils.center(null, *, *)     = null\n     * StringUtils.center(\"\", 4, ' ')     = \"    \"\n     * StringUtils.center(\"ab\", -1, ' ')  = \"ab\"\n     * StringUtils.center(\"ab\", 4, ' ')   = \" ab\"\n     * StringUtils.center(\"abcd\", 2, ' ') = \"abcd\"\n     * StringUtils.center(\"a\", 4, ' ')    = \" a  \"\n     * StringUtils.center(\"a\", 4, 'y')    = \"yayy\"\n     * 
\n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @param padChar the character to pad the new String with\n * @return centered String, null if null String input\n * @since 2.0\n */\n public static String center(String str, final int size, final char padChar) {\n if (str == null || size <= 0) {\n return str;\n }\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str;\n }\n str = StringUtils.leftPad(str, strLen + pads / 2, padChar);\n str = StringUtils.rightPad(str, size, padChar);\n return str;\n }\n\n /**\n *

Centers a String in a larger String of size size.\n * Uses a supplied String as the value to pad the String with.

\n *\n *

If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

\n *\n *
\n     * StringUtils.center(null, *, *)     = null\n     * StringUtils.center(\"\", 4, \" \")     = \"    \"\n     * StringUtils.center(\"ab\", -1, \" \")  = \"ab\"\n     * StringUtils.center(\"ab\", 4, \" \")   = \" ab\"\n     * StringUtils.center(\"abcd\", 2, \" \") = \"abcd\"\n     * StringUtils.center(\"a\", 4, \" \")    = \" a  \"\n     * StringUtils.center(\"a\", 4, \"yz\")   = \"yayz\"\n     * StringUtils.center(\"abc\", 7, null) = \"  abc  \"\n     * StringUtils.center(\"abc\", 7, \"\")   = \"  abc  \"\n     * 
\n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @param padStr the String to pad the new String with, must not be null or empty\n * @return centered String, null if null String input\n * @throws IllegalArgumentException if padStr is null or empty\n */\n public static String center(String str, final int size, String padStr) {\n if (str == null || size <= 0) {\n return str;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str;\n }\n str = StringUtils.leftPad(str, strLen + pads / 2, padStr);\n str = StringUtils.rightPad(str, size, padStr);\n return str;\n }\n // Case conversion\n //-----------------------------------------------------------------------\n\n /**\n *

Converts a String to upper case as per {@link String#toUpperCase()}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.upperCase(null)  = null\n     * StringUtils.upperCase(\"\")    = \"\"\n     * StringUtils.upperCase(\"aBc\") = \"ABC\"\n     * 
\n *\n *

Note: As described in the documentation for {@link String#toUpperCase()},\n * the result of this method is affected by the current locale.\n * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}\n * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

\n *\n * @param str the String to upper case, may be null\n * @return the upper cased String, null if null String input\n */\n public static String upperCase(final String str) {\n if (str == null) {\n return null;\n }\n return str.toUpperCase();\n }\n\n /**\n *

Converts a String to upper case as per {@link String#toUpperCase(Locale)}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.upperCase(null, Locale.ENGLISH)  = null\n     * StringUtils.upperCase(\"\", Locale.ENGLISH)    = \"\"\n     * StringUtils.upperCase(\"aBc\", Locale.ENGLISH) = \"ABC\"\n     * 
\n *\n * @param str the String to upper case, may be null\n * @param locale the locale that defines the case transformation rules, must not be null\n * @return the upper cased String, null if null String input\n * @since 2.5\n */\n public static String upperCase(final String str, final Locale locale) {\n if (str == null) {\n return null;\n }\n return str.toUpperCase(locale);\n }\n\n /**\n *

Converts a String to lower case as per {@link String#toLowerCase()}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.lowerCase(null)  = null\n     * StringUtils.lowerCase(\"\")    = \"\"\n     * StringUtils.lowerCase(\"aBc\") = \"abc\"\n     * 
\n *\n *

Note: As described in the documentation for {@link String#toLowerCase()},\n * the result of this method is affected by the current locale.\n * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}\n * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

\n *\n * @param str the String to lower case, may be null\n * @return the lower cased String, null if null String input\n */\n public static String lowerCase(final String str) {\n if (str == null) {\n return null;\n }\n return str.toLowerCase();\n }\n\n /**\n *

Converts a String to lower case as per {@link String#toLowerCase(Locale)}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.lowerCase(null, Locale.ENGLISH)  = null\n     * StringUtils.lowerCase(\"\", Locale.ENGLISH)    = \"\"\n     * StringUtils.lowerCase(\"aBc\", Locale.ENGLISH) = \"abc\"\n     * 
\n *\n * @param str the String to lower case, may be null\n * @param locale the locale that defines the case transformation rules, must not be null\n * @return the lower cased String, null if null String input\n * @since 2.5\n */\n public static String lowerCase(final String str, final Locale locale) {\n if (str == null) {\n return null;\n }\n return str.toLowerCase(locale);\n }\n\n /**\n *

Capitalizes a String changing the first letter to title case as\n * per {@link Character#toTitleCase(char)}. No other letters are changed.

\n *\n * A null input String returns null.

\n *\n *
\n     * StringUtils.capitalize(null)  = null\n     * StringUtils.capitalize(\"\")    = \"\"\n     * StringUtils.capitalize(\"cat\") = \"Cat\"\n     * StringUtils.capitalize(\"cAt\") = \"CAt\"\n     * 
\n *\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null String input\n * @see #uncapitalize(String)\n * @since 2.0\n */\n public static String capitalize(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n return Character.toTitleCase(str.charAt(0)) + str.substring(1);\n }\n\n /**\n *

Uncapitalizes a String changing the first letter to title case as\n * per {@link Character#toLowerCase(char)}. No other letters are changed.

\n *\n * A null input String returns null.

\n *\n *
\n     * StringUtils.uncapitalize(null)  = null\n     * StringUtils.uncapitalize(\"\")    = \"\"\n     * StringUtils.uncapitalize(\"Cat\") = \"cat\"\n     * StringUtils.uncapitalize(\"CAT\") = \"cAT\"\n     * 
\n *\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null String input\n * @see #capitalize(String)\n * @since 2.0\n */\n public static String uncapitalize(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n return Character.toLowerCase(str.charAt(0)) + str.substring(1);\n }\n\n /**\n *

Swaps the case of a String changing upper and title case to\n * lower case, and lower case to upper case.

\n *\n *
    \n *
  • Upper case character converts to Lower case
  • \n *
  • Title case character converts to Lower case
  • \n *
  • Lower case character converts to Upper case
  • \n *
\n *\n * A null input String returns null.

\n *\n *
\n     * StringUtils.swapCase(null)                 = null\n     * StringUtils.swapCase(\"\")                   = \"\"\n     * StringUtils.swapCase(\"The dog has a BONE\") = \"tHE DOG HAS A bone\"\n     * 
\n *\n *

NOTE: This method changed in Lang version 2.0.\n * It no longer performs a word based algorithm.\n * If you only use ASCII, you will notice no change.\n * That functionality is available in WordUtils.

\n *\n * @param str the String to swap case, may be null\n * @return the changed String, null if null String input\n */\n public static String swapCase(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n StringBuilder buffer = new StringBuilder(strLen);\n char ch = 0;\n for (int i = 0; i < strLen; i++) {\n ch = str.charAt(i);\n if (Character.isUpperCase(ch)) {\n ch = Character.toLowerCase(ch);\n } else if (Character.isTitleCase(ch)) {\n ch = Character.toLowerCase(ch);\n } else if (Character.isLowerCase(ch)) {\n ch = Character.toUpperCase(ch);\n }\n buffer.append(ch);\n }\n return buffer.toString();\n }\n // Count matches\n //-----------------------------------------------------------------------\n\n /**\n *

Counts how many times the substring appears in the larger String.

\n *\n *

A null or empty (\"\") String input returns 0.

\n *\n *
\n     * StringUtils.countMatches(null, *)       = 0\n     * StringUtils.countMatches(\"\", *)         = 0\n     * StringUtils.countMatches(\"abba\", null)  = 0\n     * StringUtils.countMatches(\"abba\", \"\")    = 0\n     * StringUtils.countMatches(\"abba\", \"a\")   = 2\n     * StringUtils.countMatches(\"abba\", \"ab\")  = 1\n     * StringUtils.countMatches(\"abba\", \"xxx\") = 0\n     * 
\n *\n * @param str the String to check, may be null\n * @param sub the substring to count, may be null\n * @return the number of occurrences, 0 if either String is null\n */\n public static int countMatches(final String str, final String sub) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(sub)) {\n return 0;\n }\n int count = 0;\n int idx = 0;\n while ((idx = str.indexOf(sub, idx)) != StringUtils.INDEX_NOT_FOUND) {\n count++;\n idx += sub.length();\n }\n return count;\n }\n // Character Tests\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if the String contains only unicode letters.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAlpha(null)   = false\n     * StringUtils.isAlpha(\"\")     = true\n     * StringUtils.isAlpha(\"  \")   = false\n     * StringUtils.isAlpha(\"abc\")  = true\n     * StringUtils.isAlpha(\"ab2c\") = false\n     * StringUtils.isAlpha(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains letters, and is non-null\n */\n public static boolean isAlpha(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetter(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode letters and\n * space (' ').

\n *\n *

null will return false\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAlphaSpace(null)   = false\n     * StringUtils.isAlphaSpace(\"\")     = true\n     * StringUtils.isAlphaSpace(\"  \")   = true\n     * StringUtils.isAlphaSpace(\"abc\")  = true\n     * StringUtils.isAlphaSpace(\"ab c\") = true\n     * StringUtils.isAlphaSpace(\"ab2c\") = false\n     * StringUtils.isAlphaSpace(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains letters and space,\n * and is non-null\n */\n public static boolean isAlphaSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetter(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode letters or digits.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAlphanumeric(null)   = false\n     * StringUtils.isAlphanumeric(\"\")     = true\n     * StringUtils.isAlphanumeric(\"  \")   = false\n     * StringUtils.isAlphanumeric(\"abc\")  = true\n     * StringUtils.isAlphanumeric(\"ab c\") = false\n     * StringUtils.isAlphanumeric(\"ab2c\") = true\n     * StringUtils.isAlphanumeric(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains letters or digits,\n * and is non-null\n */\n public static boolean isAlphanumeric(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetterOrDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode letters, digits\n * or space (' ').

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAlphanumeric(null)   = false\n     * StringUtils.isAlphanumeric(\"\")     = true\n     * StringUtils.isAlphanumeric(\"  \")   = true\n     * StringUtils.isAlphanumeric(\"abc\")  = true\n     * StringUtils.isAlphanumeric(\"ab c\") = true\n     * StringUtils.isAlphanumeric(\"ab2c\") = true\n     * StringUtils.isAlphanumeric(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains letters, digits or space,\n * and is non-null\n */\n public static boolean isAlphanumericSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetterOrDigit(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the string contains only ASCII printable characters.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAsciiPrintable(null)     = false\n     * StringUtils.isAsciiPrintable(\"\")       = true\n     * StringUtils.isAsciiPrintable(\" \")      = true\n     * StringUtils.isAsciiPrintable(\"Ceki\")   = true\n     * StringUtils.isAsciiPrintable(\"ab2c\")   = true\n     * StringUtils.isAsciiPrintable(\"!ab-c~\") = true\n     * StringUtils.isAsciiPrintable(\"\\u0020\") = true\n     * StringUtils.isAsciiPrintable(\"\\u0021\") = true\n     * StringUtils.isAsciiPrintable(\"\\u007e\") = true\n     * StringUtils.isAsciiPrintable(\"\\u007f\") = false\n     * StringUtils.isAsciiPrintable(\"Ceki G\\u00fclc\\u00fc\") = false\n     * 
\n *\n * @param str the string to check, may be null\n * @return true if every character is in the range\n * 32 thru 126\n * @since 2.1\n */\n public static boolean isAsciiPrintable(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!CharUtils.isAsciiPrintable(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode digits.\n * A decimal point is not a unicode digit and returns false.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isNumeric(null)   = false\n     * StringUtils.isNumeric(\"\")     = true\n     * StringUtils.isNumeric(\"  \")   = false\n     * StringUtils.isNumeric(\"123\")  = true\n     * StringUtils.isNumeric(\"12 3\") = false\n     * StringUtils.isNumeric(\"ab2c\") = false\n     * StringUtils.isNumeric(\"12-3\") = false\n     * StringUtils.isNumeric(\"12.3\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains digits, and is non-null\n */\n public static boolean isNumeric(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode digits or space\n * (' ').\n * A decimal point is not a unicode digit and returns false.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isNumeric(null)   = false\n     * StringUtils.isNumeric(\"\")     = true\n     * StringUtils.isNumeric(\"  \")   = true\n     * StringUtils.isNumeric(\"123\")  = true\n     * StringUtils.isNumeric(\"12 3\") = true\n     * StringUtils.isNumeric(\"ab2c\") = false\n     * StringUtils.isNumeric(\"12-3\") = false\n     * StringUtils.isNumeric(\"12.3\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains digits or space,\n * and is non-null\n */\n public static boolean isNumericSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only whitespace.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isWhitespace(null)   = false\n     * StringUtils.isWhitespace(\"\")     = true\n     * StringUtils.isWhitespace(\"  \")   = true\n     * StringUtils.isWhitespace(\"abc\")  = false\n     * StringUtils.isWhitespace(\"ab2c\") = false\n     * StringUtils.isWhitespace(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains whitespace, and is non-null\n * @since 2.0\n */\n public static boolean isWhitespace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only lowercase characters.

\n *\n *

null will return false.\n * An empty String (length()=0) will return false.

\n *\n *
\n     * StringUtils.isAllLowerCase(null)   = false\n     * StringUtils.isAllLowerCase(\"\")     = false\n     * StringUtils.isAllLowerCase(\"  \")   = false\n     * StringUtils.isAllLowerCase(\"abc\")  = true\n     * StringUtils.isAllLowerCase(\"abC\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains lowercase characters, and is non-null\n * @since 2.5\n */\n public static boolean isAllLowerCase(final String str) {\n if (str == null || StringUtils.isEmpty(str)) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLowerCase(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only uppercase characters.

\n *\n *

null will return false.\n * An empty String (length()=0) will return false.

\n *\n *
\n     * StringUtils.isAllUpperCase(null)   = false\n     * StringUtils.isAllUpperCase(\"\")     = false\n     * StringUtils.isAllUpperCase(\"  \")   = false\n     * StringUtils.isAllUpperCase(\"ABC\")  = true\n     * StringUtils.isAllUpperCase(\"aBC\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains uppercase characters, and is non-null\n * @since 2.5\n */\n public static boolean isAllUpperCase(final String str) {\n if (str == null || StringUtils.isEmpty(str)) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isUpperCase(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n // Defaults\n //-----------------------------------------------------------------------\n\n /**\n *

Returns either the passed in String,\n * or if the String is null, an empty String (\"\").

\n *\n *
\n     * StringUtils.defaultString(null)  = \"\"\n     * StringUtils.defaultString(\"\")    = \"\"\n     * StringUtils.defaultString(\"bat\") = \"bat\"\n     * 
\n *\n * @see ObjectUtils#toString(Object)\n * @see String#valueOf(Object)\n * @param str the String to check, may be null\n * @return the passed in String, or the empty String if it\n * was null\n */\n public static String defaultString(final String str) {\n return str == null ? StringUtils.EMPTY : str;\n }\n\n /**\n *

Returns either the passed in String, or if the String is\n * null, the value of defaultStr.

\n *\n *
\n     * StringUtils.defaultString(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultString(\"\", \"NULL\")    = \"\"\n     * StringUtils.defaultString(\"bat\", \"NULL\") = \"bat\"\n     * 
\n *\n * @see ObjectUtils#toString(Object, String)\n * @see String#valueOf(Object)\n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is null, may be null\n * @return the passed in String, or the default if it was null\n */\n public static String defaultString(final String str, final String defaultStr) {\n return str == null ? defaultStr : str;\n }\n\n /**\n *

Returns either the passed in String, or if the String is\n * whitespace, empty (\"\") or null, the value of defaultStr.

\n *\n *
\n     * StringUtils.defaultIfBlank(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultIfBlank(\"\", \"NULL\")    = \"NULL\"\n     * StringUtils.defaultIfBlank(\" \", \"NULL\")   = \"NULL\"\n     * StringUtils.defaultIfBlank(\"bat\", \"NULL\") = \"bat\"\n     * StringUtils.defaultIfBlank(\"\", null)      = null\n     * 
\n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is whitespace, empty (\"\") or null, may be null\n * @return the passed in String, or the default\n * @see StringUtils#defaultString(String, String)\n * @since 2.6\n */\n public static String defaultIfBlank(final String str, final String defaultStr) {\n return StringUtils.isBlank(str) ? defaultStr : str;\n }\n\n /**\n *

Returns either the passed in String, or if the String is\n * empty or null, the value of defaultStr.

\n *\n *
\n     * StringUtils.defaultIfEmpty(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultIfEmpty(\"\", \"NULL\")    = \"NULL\"\n     * StringUtils.defaultIfEmpty(\"bat\", \"NULL\") = \"bat\"\n     * StringUtils.defaultIfEmpty(\"\", null)      = null\n     * 
\n *\n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is empty (\"\") or null, may be null\n * @return the passed in String, or the default\n * @see StringUtils#defaultString(String, String)\n */\n public static String defaultIfEmpty(final String str, final String defaultStr) {\n return StringUtils.isEmpty(str) ? defaultStr : str;\n }\n // Reversing\n //-----------------------------------------------------------------------\n\n /**\n *

Reverses a String as per {@link StringBuilder#reverse()}.

\n *\n *

A null String returns null.

\n *\n *
\n     * StringUtils.reverse(null)  = null\n     * StringUtils.reverse(\"\")    = \"\"\n     * StringUtils.reverse(\"bat\") = \"tab\"\n     * 
\n *\n * @param str the String to reverse, may be null\n * @return the reversed String, null if null String input\n */\n public static String reverse(final String str) {\n if (str == null) {\n return null;\n }\n return new StringBuilder(str).reverse().toString();\n }\n\n /**\n *

Reverses a String that is delimited by a specific character.

\n *\n *

The Strings between the delimiters are not reversed.\n * Thus java.lang.String becomes String.lang.java (if the delimiter\n * is '.').

\n *\n *
\n     * StringUtils.reverseDelimited(null, *)      = null\n     * StringUtils.reverseDelimited(\"\", *)        = \"\"\n     * StringUtils.reverseDelimited(\"a.b.c\", 'x') = \"a.b.c\"\n     * StringUtils.reverseDelimited(\"a.b.c\", \".\") = \"c.b.a\"\n     * 
\n *\n * @param str the String to reverse, may be null\n * @param separatorChar the separator character to use\n * @return the reversed String, null if null String input\n * @since 2.0\n */\n public static String reverseDelimited(final String str, final char separatorChar) {\n if (str == null) {\n return null;\n }\n // could implement manually, but simple way is to reuse other,\n // probably slower, methods.\n String[] strs = StringUtils.split(str, separatorChar);\n ArrayUtils.reverse(strs);\n return StringUtils.join(strs, separatorChar);\n }\n // Abbreviating\n //-----------------------------------------------------------------------\n\n /**\n *

Abbreviates a String using ellipses. This will turn\n * \"Now is the time for all good men\" into \"Now is the time for...\"

\n *\n *

Specifically:\n *

    \n *
  • If str is less than maxWidth characters\n * long, return it.
  • \n *
  • Else abbreviate it to (substring(str, 0, max-3) + \"...\").
  • \n *
  • If maxWidth is less than 4, throw an\n * IllegalArgumentException.
  • \n *
  • In no case will it return a String of length greater than\n * maxWidth.
  • \n *
\n *

\n *\n *
\n     * StringUtils.abbreviate(null, *)      = null\n     * StringUtils.abbreviate(\"\", 4)        = \"\"\n     * StringUtils.abbreviate(\"abcdefg\", 6) = \"abc...\"\n     * StringUtils.abbreviate(\"abcdefg\", 7) = \"abcdefg\"\n     * StringUtils.abbreviate(\"abcdefg\", 8) = \"abcdefg\"\n     * StringUtils.abbreviate(\"abcdefg\", 4) = \"a...\"\n     * StringUtils.abbreviate(\"abcdefg\", 3) = IllegalArgumentException\n     * 
\n *\n * @param str the String to check, may be null\n * @param maxWidth maximum length of result String, must be at least 4\n * @return abbreviated String, null if null String input\n * @throws IllegalArgumentException if the width is too small\n * @since 2.0\n */\n public static String abbreviate(final String str, final int maxWidth) {\n return StringUtils.abbreviate(str, 0, maxWidth);\n }\n\n /**\n *

Abbreviates a String using ellipses. This will turn\n * \"Now is the time for all good men\" into \"...is the time for...\"

\n *\n *

Works like abbreviate(String, int), but allows you to specify\n * a \"left edge\" offset. Note that this left edge is not necessarily going to\n * be the leftmost character in the result, or the first character following the\n * ellipses, but it will appear somewhere in the result.\n *\n *

In no case will it return a String of length greater than\n * maxWidth.

\n *\n *
\n     * StringUtils.abbreviate(null, *, *)                = null\n     * StringUtils.abbreviate(\"\", 0, 4)                  = \"\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", -1, 10) = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 0, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 1, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 4, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 5, 10)  = \"...fghi...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 6, 10)  = \"...ghij...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 8, 10)  = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 10, 10) = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 12, 10) = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghij\", 0, 3)        = IllegalArgumentException\n     * StringUtils.abbreviate(\"abcdefghij\", 5, 6)        = IllegalArgumentException\n     * 
\n *\n * @param str the String to check, may be null\n * @param offset left edge of source String\n * @param maxWidth maximum length of result String, must be at least 4\n * @return abbreviated String, null if null String input\n * @throws IllegalArgumentException if the width is too small\n * @since 2.0\n */\n public static String abbreviate(final String str, int offset, final int maxWidth) {\n if (str == null) {\n return null;\n }\n if (maxWidth < 4) {\n throw new IllegalArgumentException(\"Minimum abbreviation width is 4\");\n }\n if (str.length() <= maxWidth) {\n return str;\n }\n if (offset > str.length()) {\n offset = str.length();\n }\n if (str.length() - offset < maxWidth - 3) {\n offset = str.length() - (maxWidth - 3);\n }\n if (offset <= 4) {\n return str.substring(0, maxWidth - 3) + \"...\";\n }\n if (maxWidth < 7) {\n throw new IllegalArgumentException(\"Minimum abbreviation width with offset is 7\");\n }\n if (offset + maxWidth - 3 < str.length()) {\n return \"...\" + StringUtils.abbreviate(str.substring(offset), maxWidth - 3);\n }\n return \"...\" + str.substring(str.length() - (maxWidth - 3));\n }\n\n /**\n *

Abbreviates a String to the length passed, replacing the middle characters with the supplied\n * replacement String.

\n *\n *

This abbreviation only occurs if the following criteria is met:\n *

    \n *
  • Neither the String for abbreviation nor the replacement String are null or empty
  • \n *
  • The length to truncate to is less than the length of the supplied String
  • \n *
  • The length to truncate to is greater than 0
  • \n *
  • The abbreviated String will have enough room for the length supplied replacement String\n * and the first and last characters of the supplied String for abbreviation
  • \n *
\n * Otherwise, the returned String will be the same as the supplied String for abbreviation.\n *

\n *\n *
\n     * StringUtils.abbreviateMiddle(null, null, 0)      = null\n     * StringUtils.abbreviateMiddle(\"abc\", null, 0)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abc\", \".\", 0)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abc\", \".\", 3)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abcdef\", \".\", 4)     = \"ab.f\"\n     * 
\n *\n * @param str the String to abbreviate, may be null\n * @param middle the String to replace the middle characters with, may be null\n * @param length the length to abbreviate str to.\n * @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation.\n * @since 2.5\n */\n public static String abbreviateMiddle(final String str, final String middle, final int length) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(middle)) {\n return str;\n }\n if (length >= str.length() || length < middle.length() + 2) {\n return str;\n }\n int targetSting = length - middle.length();\n int startOffset = targetSting / 2 + targetSting % 2;\n int endOffset = str.length() - targetSting / 2;\n return str.substring(0, startOffset) + middle + str.substring(endOffset);\n }\n // Difference\n //-----------------------------------------------------------------------\n\n /**\n *

Compares two Strings, and returns the portion where they differ.\n * (More precisely, return the remainder of the second String,\n * starting from where it's different from the first.)

\n *\n *

For example,\n * difference(\"i am a machine\", \"i am a robot\") -> \"robot\".

\n *\n *
\n     * StringUtils.difference(null, null) = null\n     * StringUtils.difference(\"\", \"\") = \"\"\n     * StringUtils.difference(\"\", \"abc\") = \"abc\"\n     * StringUtils.difference(\"abc\", \"\") = \"\"\n     * StringUtils.difference(\"abc\", \"abc\") = \"\"\n     * StringUtils.difference(\"ab\", \"abxyz\") = \"xyz\"\n     * StringUtils.difference(\"abcde\", \"abxyz\") = \"xyz\"\n     * StringUtils.difference(\"abcde\", \"xyz\") = \"xyz\"\n     * 
\n *\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return the portion of str2 where it differs from str1; returns the\n * empty String if they are equal\n * @since 2.0\n */\n public static String difference(final String str1, final String str2) {\n if (str1 == null) {\n return str2;\n }\n if (str2 == null) {\n return str1;\n }\n int at = StringUtils.indexOfDifference(str1, str2);\n if (at == StringUtils.INDEX_NOT_FOUND) {\n return StringUtils.EMPTY;\n }\n return str2.substring(at);\n }\n\n /**\n *

Compares two Strings, and returns the index at which the\n * Strings begin to differ.

\n *\n *

For example,\n * indexOfDifference(\"i am a machine\", \"i am a robot\") -> 7

\n *\n *
\n     * StringUtils.indexOfDifference(null, null) = -1\n     * StringUtils.indexOfDifference(\"\", \"\") = -1\n     * StringUtils.indexOfDifference(\"\", \"abc\") = 0\n     * StringUtils.indexOfDifference(\"abc\", \"\") = 0\n     * StringUtils.indexOfDifference(\"abc\", \"abc\") = -1\n     * StringUtils.indexOfDifference(\"ab\", \"abxyz\") = 2\n     * StringUtils.indexOfDifference(\"abcde\", \"abxyz\") = 2\n     * StringUtils.indexOfDifference(\"abcde\", \"xyz\") = 0\n     * 
\n *\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return the index where str2 and str1 begin to differ; -1 if they are equal\n * @since 2.0\n */\n public static int indexOfDifference(final String str1, final String str2) {\n if (str1 != null && str1.equals(str2)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (str1 == null || str2 == null) {\n return 0;\n }\n int i;\n for (i = 0; i < str1.length() && i < str2.length(); ++i) {\n if (str1.charAt(i) != str2.charAt(i)) {\n break;\n }\n }\n if (i < str2.length() || i < str1.length()) {\n return i;\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Compares all Strings in an array and returns the index at which the\n * Strings begin to differ.

\n *\n *

For example,\n * indexOfDifference(new String[] {\"i am a machine\", \"i am a robot\"}) -> 7

\n *\n *
\n     * StringUtils.indexOfDifference(null) = -1\n     * StringUtils.indexOfDifference(new String[] {}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"abc\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {null, null}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"\", \"\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"\", null}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", null, null}) = 0\n     * StringUtils.indexOfDifference(new String[] {null, null, \"abc\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"\", \"abc\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"abc\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"a\"}) = 1\n     * StringUtils.indexOfDifference(new String[] {\"ab\", \"abxyz\"}) = 2\n     * StringUtils.indexOfDifference(new String[] {\"abcde\", \"abxyz\"}) = 2\n     * StringUtils.indexOfDifference(new String[] {\"abcde\", \"xyz\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"xyz\", \"abcde\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"i am a machine\", \"i am a robot\"}) = 7\n     * 
\n *\n * @param strs array of strings, entries may be null\n * @return the index where the strings begin to differ; -1 if they are all equal\n * @since 2.4\n */\n public static int indexOfDifference(final String[] strs) {\n if (strs == null || strs.length <= 1) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n boolean anyStringNull = false;\n boolean allStringsNull = true;\n int arrayLen = strs.length;\n int shortestStrLen = Integer.MAX_VALUE;\n int longestStrLen = 0;\n // find the min and max string lengths; this avoids checking to make\n // sure we are not exceeding the length of the string each time through\n // the bottom loop.\n for (int i = 0; i < arrayLen; i++) {\n if (strs[i] == null) {\n anyStringNull = true;\n shortestStrLen = 0;\n } else {\n allStringsNull = false;\n shortestStrLen = Math.min(strs[i].length(), shortestStrLen);\n longestStrLen = Math.max(strs[i].length(), longestStrLen);\n }\n }\n // handle lists containing all nulls or all empty strings\n if (allStringsNull || longestStrLen == 0 && !anyStringNull) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n // handle lists containing some nulls or some empty strings\n if (shortestStrLen == 0) {\n return 0;\n }\n // find the position with the first difference across all strings\n int firstDiff = -1;\n for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {\n char comparisonChar = strs[0].charAt(stringPos);\n for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {\n if (strs[arrayPos].charAt(stringPos) != comparisonChar) {\n firstDiff = stringPos;\n break;\n }\n }\n if (firstDiff != -1) {\n break;\n }\n }\n if (firstDiff == -1 && shortestStrLen != longestStrLen) {\n // we compared all of the characters up to the length of the\n // shortest string and didn't find a match, but the string lengths\n // vary, so return the length of the shortest string.\n return shortestStrLen;\n }\n return firstDiff;\n }\n\n /**\n *

Compares all Strings in an array and returns the initial sequence of\n * characters that is common to all of them.

\n *\n *

For example,\n * getCommonPrefix(new String[] {\"i am a machine\", \"i am a robot\"}) -> \"i am a \"

\n *\n *
\n     * StringUtils.getCommonPrefix(null) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\"}) = \"abc\"\n     * StringUtils.getCommonPrefix(new String[] {null, null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", \"\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", null, null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {null, null, \"abc\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", \"abc\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"abc\"}) = \"abc\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"a\"}) = \"a\"\n     * StringUtils.getCommonPrefix(new String[] {\"ab\", \"abxyz\"}) = \"ab\"\n     * StringUtils.getCommonPrefix(new String[] {\"abcde\", \"abxyz\"}) = \"ab\"\n     * StringUtils.getCommonPrefix(new String[] {\"abcde\", \"xyz\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"xyz\", \"abcde\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"i am a machine\", \"i am a robot\"}) = \"i am a \"\n     * 
\n *\n * @param strs array of String objects, entries may be null\n * @return the initial sequence of characters that are common to all Strings\n * in the array; empty String if the array is null, the elements are all null\n * or if there is no common prefix.\n * @since 2.4\n */\n public static String getCommonPrefix(final String[] strs) {\n if (strs == null || strs.length == 0) {\n return StringUtils.EMPTY;\n }\n int smallestIndexOfDiff = StringUtils.indexOfDifference(strs);\n if (smallestIndexOfDiff == StringUtils.INDEX_NOT_FOUND) {\n // all strings were identical\n if (strs[0] == null) {\n return StringUtils.EMPTY;\n }\n return strs[0];\n } else if (smallestIndexOfDiff == 0) {\n // there were no common initial characters\n return StringUtils.EMPTY;\n } else {\n // we found a common initial character sequence\n return strs[0].substring(0, smallestIndexOfDiff);\n }\n }\n // Misc\n //-----------------------------------------------------------------------\n\n /**\n *

Find the Levenshtein distance between two Strings.

\n *\n *

This is the number of changes needed to change one String into\n * another, where each change is a single character modification (deletion,\n * insertion or substitution).

\n *\n *

The previous implementation of the Levenshtein distance algorithm\n * was from http://www.merriampark.com/ld.htm

\n *\n *

Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError\n * which can occur when my Java implementation is used with very large strings.
\n * This implementation of the Levenshtein distance algorithm\n * is from http://www.merriampark.com/ldjava.htm

\n *\n *
\n     * StringUtils.getLevenshteinDistance(null, *)             = IllegalArgumentException\n     * StringUtils.getLevenshteinDistance(*, null)             = IllegalArgumentException\n     * StringUtils.getLevenshteinDistance(\"\",\"\")               = 0\n     * StringUtils.getLevenshteinDistance(\"\",\"a\")              = 1\n     * StringUtils.getLevenshteinDistance(\"aaapppp\", \"\")       = 7\n     * StringUtils.getLevenshteinDistance(\"frog\", \"fog\")       = 1\n     * StringUtils.getLevenshteinDistance(\"fly\", \"ant\")        = 3\n     * StringUtils.getLevenshteinDistance(\"elephant\", \"hippo\") = 7\n     * StringUtils.getLevenshteinDistance(\"hippo\", \"elephant\") = 7\n     * StringUtils.getLevenshteinDistance(\"hippo\", \"zzzzzzzz\") = 8\n     * StringUtils.getLevenshteinDistance(\"hello\", \"hallo\")    = 1\n     * 
\n *\n * @param s the first String, must not be null\n * @param t the second String, must not be null\n * @return result distance\n * @throws IllegalArgumentException if either String input null\n */\n public static int getLevenshteinDistance(String s, String t) {\n if (s == null || t == null) {\n throw new IllegalArgumentException(\"Strings must not be null\");\n }\n /*\n The difference between this impl. and the previous is that, rather\n than creating and retaining a matrix of size s.length()+1 by t.length()+1,\n we maintain two single-dimensional arrays of length s.length()+1. The first, d,\n is the 'current working' distance array that maintains the newest distance cost\n counts as we iterate through the characters of String s. Each time we increment\n the index of String t we are comparing, d is copied to p, the second int[]. Doing so\n allows us to retain the previous cost counts as required by the algorithm (taking\n the minimum of the cost count to the left, up one, and diagonally up and to the left\n of the current cost count being calculated). (Note that the arrays aren't really\n copied anymore, just switched...this is clearly much better than cloning an array\n or doing a System.arraycopy() each time through the outer loop.)\n\n Effectively, the difference between the two implementations is this one does not\n cause an out of memory condition when calculating the LD over two very large strings.\n */\n int n = s.length(); // length of s\n int m = t.length(); // length of t\n if (n == 0) {\n return m;\n } else if (m == 0) {\n return n;\n }\n if (n > m) {\n // swap the input strings to consume less memory\n String tmp = s;\n s = t;\n t = tmp;\n n = m;\n m = t.length();\n }\n int[] p = new int[n + 1]; //'previous' cost array, horizontally\n int[] d = new int[n + 1]; // cost array, horizontally\n int[] _d; //placeholder to assist in swapping p and d\n // indexes into strings s and t\n int i; // iterates through s\n int j; // iterates through t\n char t_j; // jth character of t\n int cost; // cost\n for (i = 0; i <= n; i++) {\n p[i] = i;\n }\n for (j = 1; j <= m; j++) {\n t_j = t.charAt(j - 1);\n d[0] = j;\n for (i = 1; i <= n; i++) {\n cost = s.charAt(i - 1) == t_j ? 0 : 1;\n // minimum of cell to the left+1, to the top+1, diagonally left and up +cost\n d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);\n }\n // copy current distance counts to 'previous row' distance counts\n _d = p;\n p = d;\n d = _d;\n }\n // our last action in the above loop was to switch d and p, so p now\n // actually has the most recent cost counts\n return p[n];\n }\n // startsWith\n //-----------------------------------------------------------------------\n\n /**\n *

Check if a String starts with a specified prefix.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

\n *\n *
\n     * StringUtils.startsWith(null, null)      = true\n     * StringUtils.startsWith(null, \"abc\")     = false\n     * StringUtils.startsWith(\"abcdef\", null)  = false\n     * StringUtils.startsWith(\"abcdef\", \"abc\") = true\n     * StringUtils.startsWith(\"ABCDEF\", \"abc\") = false\n     * 
\n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @return true if the String starts with the prefix, case sensitive, or\n * both null\n * @since 2.4\n */\n public static boolean startsWith(final String str, final String prefix) {\n return StringUtils.startsWith(str, prefix, false);\n }\n\n /**\n *

Case insensitive check if a String starts with a specified prefix.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case insensitive.

\n *\n *
\n     * StringUtils.startsWithIgnoreCase(null, null)      = true\n     * StringUtils.startsWithIgnoreCase(null, \"abc\")     = false\n     * StringUtils.startsWithIgnoreCase(\"abcdef\", null)  = false\n     * StringUtils.startsWithIgnoreCase(\"abcdef\", \"abc\") = true\n     * StringUtils.startsWithIgnoreCase(\"ABCDEF\", \"abc\") = true\n     * 
\n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @return true if the String starts with the prefix, case insensitive, or\n * both null\n * @since 2.4\n */\n public static boolean startsWithIgnoreCase(final String str, final String prefix) {\n return StringUtils.startsWith(str, prefix, true);\n }\n\n /**\n *

Check if a String starts with a specified prefix (optionally case insensitive).

\n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @param ignoreCase inidicates whether the compare should ignore case\n * (case insensitive) or not.\n * @return true if the String starts with the prefix or\n * both null\n */\n private static boolean startsWith(final String str, final String prefix, final boolean ignoreCase) {\n if (str == null || prefix == null) {\n return str == null && prefix == null;\n }\n if (prefix.length() > str.length()) {\n return false;\n }\n return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());\n }\n\n /**\n *

Check if a String starts with any of an array of specified strings.

\n *\n *
\n     * StringUtils.startsWithAny(null, null)      = false\n     * StringUtils.startsWithAny(null, new String[] {\"abc\"})  = false\n     * StringUtils.startsWithAny(\"abcxyz\", null)     = false\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {\"\"}) = false\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {\"abc\"}) = true\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {null, \"xyz\", \"abc\"}) = true\n     * 
\n *\n * @see #startsWith(String, String)\n * @param string the String to check, may be null\n * @param searchStrings the Strings to find, may be null or empty\n * @return true if the String starts with any of the the prefixes, case insensitive, or\n * both null\n * @since 2.5\n */\n public static boolean startsWithAny(final String string, final String[] searchStrings) {\n if (StringUtils.isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {\n return false;\n }\n for (String searchString : searchStrings) {\n if (StringUtils.startsWith(string, searchString)) {\n return true;\n }\n }\n return false;\n }\n // endsWith\n //-----------------------------------------------------------------------\n\n /**\n *

Check if a String ends with a specified suffix.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

\n *\n *
\n     * StringUtils.endsWith(null, null)      = true\n     * StringUtils.endsWith(null, \"def\")     = false\n     * StringUtils.endsWith(\"abcdef\", null)  = false\n     * StringUtils.endsWith(\"abcdef\", \"def\") = true\n     * StringUtils.endsWith(\"ABCDEF\", \"def\") = false\n     * StringUtils.endsWith(\"ABCDEF\", \"cde\") = false\n     * 
\n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @return true if the String ends with the suffix, case sensitive, or\n * both null\n * @since 2.4\n */\n public static boolean endsWith(final String str, final String suffix) {\n return StringUtils.endsWith(str, suffix, false);\n }\n\n /**\n *

Case insensitive check if a String ends with a specified suffix.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case insensitive.

\n *\n *
\n     * StringUtils.endsWithIgnoreCase(null, null)      = true\n     * StringUtils.endsWithIgnoreCase(null, \"def\")     = false\n     * StringUtils.endsWithIgnoreCase(\"abcdef\", null)  = false\n     * StringUtils.endsWithIgnoreCase(\"abcdef\", \"def\") = true\n     * StringUtils.endsWithIgnoreCase(\"ABCDEF\", \"def\") = true\n     * StringUtils.endsWithIgnoreCase(\"ABCDEF\", \"cde\") = false\n     * 
\n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @return true if the String ends with the suffix, case insensitive, or\n * both null\n * @since 2.4\n */\n public static boolean endsWithIgnoreCase(final String str, final String suffix) {\n return StringUtils.endsWith(str, suffix, true);\n }\n\n /**\n *

Check if a String ends with a specified suffix (optionally case insensitive).

\n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @param ignoreCase inidicates whether the compare should ignore case\n * (case insensitive) or not.\n * @return true if the String starts with the prefix or\n * both null\n */\n private static boolean endsWith(final String str, final String suffix, final boolean ignoreCase) {\n if (str == null || suffix == null) {\n return str == null && suffix == null;\n }\n if (suffix.length() > str.length()) {\n return false;\n }\n int strOffset = str.length() - suffix.length();\n return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());\n }\n\n /**\n *

\n * Similar to http://www.w3.org/TR/xpath/#function-normalize\n * -space\n *

\n *

\n * The function returns the argument string with whitespace normalized by using\n * {@link #trim(String)} to remove leading and trailing whitespace\n * and then replacing sequences of whitespace characters by a single space.\n *

\n * In XML Whitespace characters are the same as those allowed by the S production, which is S ::= (#x20 | #x9 | #xD | #xA)+\n *

\n * See Java's {@link Character#isWhitespace(char)} for which characters are considered whitespace.\n *

\n * The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also\n * normalize. Additonally {@link #trim(String)} removes control characters (char <= 32) from both\n * ends of this String.\n *

\n *\n * @see Character#isWhitespace(char)\n * @see #trim(String)\n * @see \n * http://www.w3.org/TR/xpath/#function-normalize-space\n * @param str the source String to normalize whitespaces from, may be null\n * @return the modified string with whitespace normalized, null if null String input\n *\n * @since 2.6\n */\n public static String normalizeSpace(String str) {\n str = StringUtils.strip(str);\n if (str == null || str.length() <= 2) {\n return str;\n }\n StringBuilder b = new StringBuilder(str.length());\n for (int i = 0; i < str.length(); i++) {\n char c = str.charAt(i);\n if (Character.isWhitespace(c)) {\n if (i > 0 && !Character.isWhitespace(str.charAt(i - 1))) {\n b.append(' ');\n }\n } else {\n b.append(c);\n }\n }\n return b.toString();\n }\n\n /**\n *

Check if a String ends with any of an array of specified strings.

\n *\n *
\n     * StringUtils.endsWithAny(null, null)      = false\n     * StringUtils.endsWithAny(null, new String[] {\"abc\"})  = false\n     * StringUtils.endsWithAny(\"abcxyz\", null)     = false\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {\"\"}) = true\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {\"xyz\"}) = true\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {null, \"xyz\", \"abc\"}) = true\n     * 
\n *\n * @param string the String to check, may be null\n * @param searchStrings the Strings to find, may be null or empty\n * @return true if the String ends with any of the the prefixes, case insensitive, or\n * both null\n * @since 2.6\n */\n public static boolean endsWithAny(final String string, final String[] searchStrings) {\n if (StringUtils.isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {\n return false;\n }\n for (String searchString : searchStrings) {\n if (StringUtils.endsWith(string, searchString)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 转换首字母大写。\n *
\n     * StringUtils.firstCharToUpperCase(null)      = null\n     * StringUtils.firstCharToUpperCase(\"\")        = \"\"\n     * StringUtils.firstCharToUpperCase(\"abc\")     = \"Abc\"\n     * StringUtils.firstCharToUpperCase(\"Abc\")     = \"Abc\"\n     * StringUtils.firstCharToUpperCase(\"ABC\")     = \"ABC\"\n     * 
\n */\n public static String firstCharToUpperCase(final String value) {\n if (StringUtils.isBlank(value)) {\n return value;\n }\n StringBuilder sb = new StringBuilder(value);\n char firstChar = sb.charAt(0);\n sb.delete(0, 1);\n sb.insert(0, (char) (firstChar >= 97 ? firstChar - 32 : firstChar));\n return sb.toString();\n }\n\n /**\n * 转换首字母小写。\n *
\n     * StringUtils.firstCharToLowerCase(null)      = null\n     * StringUtils.firstCharToLowerCase(\"\")        = \"\"\n     * StringUtils.firstCharToLowerCase(\"abc\")     = \"abc\"\n     * StringUtils.firstCharToLowerCase(\"Abc\")     = \"abc\"\n     * StringUtils.firstCharToLowerCase(\"ABC\")     = \"aBC\"\n     * 
\n */\n public static String firstCharToLowerCase(final String value) {\n if (StringUtils.isBlank(value)) {\n return value;\n }\n StringBuilder sb = new StringBuilder(value);\n char firstChar = sb.charAt(0);\n sb.delete(0, 1);\n sb.insert(0, (char) (firstChar <= 90 ? firstChar + 32 : firstChar));\n return sb.toString();\n }\n\n /**\n * 执行字符串匹配。\n *
\n     * StringUtils.equalsBlankIgnoreCase(null,\"\")         = true\n     * StringUtils.equalsBlankIgnoreCase(\"\",\"\")           = true\n     * StringUtils.equalsBlankIgnoreCase(\" \",\"\")          = true\n     * StringUtils.equalsBlankIgnoreCase(\" \",null)        = true\n     * StringUtils.equalsBlankIgnoreCase(\"bob\",\"\")        = false\n     * StringUtils.equalsBlankIgnoreCase(\"  bob  \",\"bob\") = true\n     * 
\n */\n public static boolean equalsBlankIgnoreCase(final String str1, final String str2) {\n return StringUtils.equalsIgnoreCase(StringUtils.trimToEmpty(str1), StringUtils.trimToEmpty(str2));\n }\n\n /* ------------------------------------------------------------ */\n private static final char[] escapes = new char[32];\n\n static {\n Arrays.fill(escapes, (char) 0xFFFF);\n escapes['\\b'] = 'b';\n escapes['\\t'] = 't';\n escapes['\\n'] = 'n';\n escapes['\\f'] = 'f';\n escapes['\\r'] = 'r';\n }\n\n /** Quote a string into an Appendable.\n * The characters \", \\, \\n, \\r, \\t, \\f and \\b are escaped\n * @param input The String to quote.\n */\n public static String quote(String input) {\n StringBuilder buffer = new StringBuilder();\n quote(buffer, input);\n return buffer.toString();\n }\n\n public static void quote(Appendable buffer, String input) {\n try {\n buffer.append('\"');\n for (int i = 0; i < input.length(); ++i) {\n char c = input.charAt(i);\n if (c >= 32) {\n if (c == '\"' || c == '\\\\')\n buffer.append('\\\\');\n buffer.append(c);\n } else {\n char escape = escapes[c];\n if (escape == 0xFFFF) {\n // Unicode escape\n buffer.append('\\\\').append('u').append('0').append('0');\n if (c < 0x10)\n buffer.append('0');\n buffer.append(Integer.toString(c, 16));\n } else {\n buffer.append('\\\\').append(escape);\n }\n }\n }\n buffer.append('\"');\n } catch (IOException x) {\n throw new RuntimeException(x);\n }\n }\n\n /** Object to String ,when null object then null else return toString(); */\n public static String toString(Object object) {\n return (object == null) ? null : object.toString();\n }\n}", "file_name": "StringUtils.java", "human_label": "Determines whether a character string ends with a specified suffix.", "level": "self_contained", "lineno": "5925", "name": "endsWith", "oracle_context": "{ \"apis\" : \"[length, regionMatches]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "6367667f1a6d9265ec01745d", "all_context": "{ \"class_level\" : \"import java.io.UnsupportedEncodingException;\\nimport java.net.URI;\\nimport java.net.URLDecoder;\\nimport java.nio.Buffer;\\nimport java.nio.ByteBuffer;\\nimport java.nio.CharBuffer;\\nimport java.nio.charset.Charset;\\nimport java.nio.charset.StandardCharsets;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collections;\\nimport java.util.HashMap;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Map;\\nchar[] HEX_DIGITS;\\nString[] SCHEME;\\nString[] UNRESERVED;\\nString[] SUB_DELIMS;\\nboolean[][] ENCODING_TABLES;\\nCharset UTF_8_CHARSET;\\nPathSegmentImpl EMPTY_PATH_SEGMENT;\\nString path;\\nMap matrixParameters;\\nint[] HEX_TABLE;\\nUriComponent();\\nvalidate(String s,Type t,boolean template);\\nvalid(String s,Type t);\\nvalid(String s,Type t,boolean template);\\n_valid(String s,Type t,boolean template);\\ncontextualEncode(String s,Type t);\\ncontextualEncode(String s,Type t,boolean template);\\nencode(String s,Type t);\\nencode(String s,Type t,boolean template);\\nencodeTemplateNames(String s);\\n_encode(String s,Type t,boolean template,boolean contextualEncode);\\nappendPercentEncodedOctet(StringBuilder sb,int b);\\nappendUTF8EncodedCharacter(StringBuilder sb,char c);\\ncreatingEncodingTables();\\ncreatingEncodingTable(List allowed);\\ndecode(String s,Type t);\\ndecodeQuery(URI u,boolean decode);\\ndecodeQuery(String q,boolean decode);\\ndecodeQueryParam(Map params,String param,boolean decode);\\nPathSegmentImpl(String path,boolean decode);\\nPathSegmentImpl(String path,boolean decode,Map matrixParameters);\\ngetPath();\\ngetMatrixParameters();\\ndecodePath(URI u,boolean decode);\\ndecodePath(String path,boolean decode);\\ndecodePathSegment(List segments,String segment,boolean decode);\\ndecodeMatrix(String pathSegment,boolean decode);\\ndecodeMatrixParam(Map params,String param,boolean decode);\\ndecode(String s,int n);\\ndecodeQueryParam(String s,int n);\\ndecodeHost(String s,int n);\\ndecodePercentEncodedOctets(String s,int i,ByteBuffer bb);\\ndecodeOctets(int i,ByteBuffer bb,StringBuilder sb);\\ndecodeHex(String s,int i);\\ncreateHexTable();\\ndecodeHex(char c);\\nisHexCharacter(char c);\\nvalidate(String s,Type t);\\n\", \"repo_level\" : \"\" }", "class_name": "UriComponent", "code": "public static List decodePath(URI u,boolean decode){\n String rawPath=u.getRawPath();\n if (rawPath != null && rawPath.length() > 0 && rawPath.charAt(0) == '/') {\n rawPath=rawPath.substring(1);\n }\n return decodePath(rawPath,decode);\n}\n", "docstring": "/** \n * Decode the path component of a URI as path segments.\n * @param u the URI. If the path component is an absolute path componentthen the leading '/' is ignored and is not considered a delimiator of a path segment.\n * @param decode true if the path segments of the path componentshould be in decoded form.\n * @return the list of path segments.\n */\n", "end_lineno": "591", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * Copyright (c) 2010-2018 Oracle and/or its affiliates. All rights reserved.\n *\n * The contents of this file are subject to the terms of either the GNU\n * General Public License Version 2 only (\"GPL\") or the Common Development\n * and Distribution License(\"CDDL\") (collectively, the \"License\"). You\n * may not use this file except in compliance with the License. You can\n * obtain a copy of the License at\n * http://glassfish.java.net/public/CDDL+GPL_1_1.html\n * or packager/legal/LICENSE.txt. See the License for the specific\n * language governing permissions and limitations under the License.\n *\n * When distributing the software, include this License Header Notice in each\n * file and include the License file at packager/legal/LICENSE.txt.\n *\n * GPL Classpath Exception:\n * Oracle designates this particular file as subject to the \"Classpath\"\n * exception as provided by Oracle in the GPL Version 2 section of the License\n * file that accompanied this code.\n *\n * Modifications:\n * If applicable, add the following below the License Header, with the fields\n * enclosed by brackets [] replaced by your own identifying information:\n * \"Portions Copyright [year] [name of copyright owner]\"\n *\n * Contributor(s):\n * If you wish your version of this file to be governed by only the CDDL or\n * only the GPL Version 2, indicate your decision by adding \"[Contributor]\n * elects to include this software in this distribution under the [CDDL or GPL\n * Version 2] license.\" If you don't indicate a single choice of license, a\n * recipient has the option to distribute your version of this file under\n * either the CDDL, the GPL Version 2 or to extend the choice of license to\n * its licensees as provided above. However, if you add GPL Version 2 code\n * and therefore, elected the GPL Version 2 license, then the option applies\n * only if the new code is made subject to such option by the copyright\n * holder.\n */\npackage org.atmosphere.util.uri;\n\nimport java.io.UnsupportedEncodingException;\nimport java.net.URI;\nimport java.net.URLDecoder;\nimport java.nio.Buffer;\nimport java.nio.ByteBuffer;\nimport java.nio.CharBuffer;\nimport java.nio.charset.Charset;\nimport java.nio.charset.StandardCharsets;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Utility class for validating, encoding and decoding components\n * of a URI.\n *\n * @author Paul.Sandoz@Sun.Com\n */\npublic class UriComponent {\n\n // TODO rewrite to use masks and not lookup tables\n /**\n * The URI component type.\n */\n public enum Type {\n\n /**\n * ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\" characters\n */\n UNRESERVED,\n /**\n * The URI scheme component type.\n */\n SCHEME,\n /**\n * The URI authority component type.\n */\n AUTHORITY,\n /**\n * The URI user info component type.\n */\n USER_INFO,\n /**\n * The URI host component type.\n */\n HOST,\n /**\n * The URI port component type.\n */\n PORT,\n /**\n * The URI path component type.\n */\n PATH,\n /**\n * The URI path component type that is a path segment.\n */\n PATH_SEGMENT,\n /**\n * The URI path component type that is a matrix parameter.\n */\n MATRIX_PARAM,\n /**\n * The URI query component type.\n */\n QUERY,\n /**\n * The URI query component type that is a query parameter.\n */\n QUERY_PARAM,\n /**\n * The URI fragment component type.\n */\n FRAGMENT,\n }\n\n private UriComponent() {\n }\n\n /**\n * Validates the legal characters of a percent-encoded string that \n * represents a URI component type.\n *\n * @param s the encoded string.\n * @param t the URI compontent type identifying the legal characters.\n * @throws IllegalArgumentException if the encoded string contains illegal\n * characters.\n */\n public static void validate(String s, Type t) {\n validate(s, t, false);\n }\n\n /**\n * Validates the legal characters of a percent-encoded string that \n * represents a URI component type.\n *\n * @param s the encoded string.\n * @param t the URI compontent type identifying the legal characters.\n * @param template true if the encoded string contains URI template variables\n * @throws IllegalArgumentException if the encoded string contains illegal\n * characters.\n */\n public static void validate(String s, Type t, boolean template) {\n int i = _valid(s, t, template);\n if (i > -1) // TODO localize\n {\n throw new IllegalArgumentException(\"The string '\" + s +\n \"' for the URI component \" + t +\n \" contains an invalid character, '\" + s.charAt(i) + \"', at index \" + i);\n }\n }\n\n /**\n * Validates the legal characters of a percent-encoded string that \n * represents a URI component type.\n *\n * @param s the encoded string.\n * @param t the URI compontent type identifying the legal characters.\n * @return true if the encoded string is valid, otherwise false.\n */\n public static boolean valid(String s, Type t) {\n return valid(s, t, false);\n }\n\n /**\n * Validates the legal characters of a percent-encoded string that \n * represents a URI component type.\n *\n * @param s the encoded string.\n * @param t the URI compontent type identifying the legal characters.\n * @param template true if the encoded string contains URI template variables\n * @return true if the encoded string is valid, otherwise false.\n */\n public static boolean valid(String s, Type t, boolean template) {\n return _valid(s, t, template) == -1;\n }\n\n private static int _valid(String s, Type t, boolean template) {\n boolean[] table = ENCODING_TABLES[t.ordinal()];\n\n for (int i = 0; i < s.length(); i++) {\n final char c = s.charAt(i);\n if (c >= 0x80 || (c != '%' && !table[c])) {\n if (!template || (c != '{' && c != '}')) {\n return i;\n }\n }\n }\n return -1;\n }\n\n /**\n * Contextually encodes the characters of string that are either non-ASCII\n * characters or are ASCII characters that must be percent-encoded using the\n * UTF-8 encoding. Percent-encoded characters will be recognized and not\n * double encoded.\n *\n * @param s the string to be encoded.\n * @param t the URI compontent type identifying the ASCII characters that \n * must be percent-encoded.\n * @return the encoded string.\n */\n public static String contextualEncode(String s, Type t) {\n return _encode(s, t, false, true);\n }\n\n /**\n * Contextually encodes the characters of string that are either non-ASCII\n * characters or are ASCII characters that must be percent-encoded using the\n * UTF-8 encoding. Percent-encoded characters will be recognized and not\n * double encoded.\n *\n * @param s the string to be encoded.\n * @param t the URI compontent type identifying the ASCII characters that \n * must be percent-encoded.\n * @param template true if the encoded string contains URI template variables\n * @return the encoded string.\n */\n public static String contextualEncode(String s, Type t, boolean template) {\n return _encode(s, t, template, true);\n }\n\n /**\n * Encodes the characters of string that are either non-ASCII characters \n * or are ASCII characters that must be percent-encoded using the \n * UTF-8 encoding.\n *\n * @param s the string to be encoded.\n * @param t the URI compontent type identifying the ASCII characters that \n * must be percent-encoded.\n * @return the encoded string.\n */\n public static String encode(String s, Type t) {\n return _encode(s, t, false, false);\n }\n\n /**\n * Encodes the characters of string that are either non-ASCII characters \n * or are ASCII characters that must be percent-encoded using the \n * UTF-8 encoding.\n *\n * @param s the string to be encoded.\n * @param t the URI compontent type identifying the ASCII characters that \n * must be percent-encoded.\n * @param template true if the encoded string contains URI template variables\n * @return the encoded string.\n */\n public static String encode(String s, Type t, boolean template) {\n return _encode(s, t, template, false);\n }\n\n /**\n * Encodes a string with template parameters names present, specifically the\n * characters '{' and '}' will be percent-encoded.\n * \n * @param s the string with zero or more template parameters names\n * @return the string with encoded template parameters names.\n */\n public static String encodeTemplateNames(String s) {\n int i = s.indexOf('{');\n if (i != -1)\n s = s.replace(\"{\", \"%7B\");\n i = s.indexOf('}');\n if (i != -1)\n s = s.replace(\"}\", \"%7D\");\n\n return s;\n }\n\n private static String _encode(String s, Type t, boolean template, boolean contextualEncode) {\n final boolean[] table = ENCODING_TABLES[t.ordinal()];\n\n StringBuilder sb = null;\n for (int i = 0; i < s.length(); i++) {\n final char c = s.charAt(i);\n if (c < 0x80 && table[c]) {\n if (sb != null) sb.append(c);\n } else {\n if (template && (c == '{' || c == '}')) {\n if (sb != null) sb.append(c);\n continue;\n } else if (contextualEncode) {\n if (c == '%' && i + 2 < s.length()) {\n if (isHexCharacter(s.charAt(i + 1)) &&\n isHexCharacter(s.charAt(i + 2))) {\n if (sb != null)\n sb.append('%').append(s.charAt(i + 1)).append(s.charAt(i + 2));\n i += 2;\n continue;\n }\n }\n }\n\n if (sb == null) {\n sb = new StringBuilder();\n sb.append(s, 0, i);\n }\n\n if (c < 0x80) {\n if (c == ' ' && (t == Type.QUERY_PARAM)) {\n sb.append('+');\n } else {\n appendPercentEncodedOctet(sb, c);\n }\n } else {\n appendUTF8EncodedCharacter(sb, c);\n }\n }\n }\n\n return (sb == null) ? s : sb.toString();\n }\n private final static char[] HEX_DIGITS = {\n '0', '1', '2', '3', '4', '5', '6', '7',\n '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'\n };\n\n private static void appendPercentEncodedOctet(StringBuilder sb, int b) {\n sb.append('%');\n sb.append(HEX_DIGITS[b >> 4]);\n sb.append(HEX_DIGITS[b & 0x0F]);\n }\n\n private static void appendUTF8EncodedCharacter(StringBuilder sb, char c) {\n final ByteBuffer bb = UTF_8_CHARSET.encode(\"\" + c);\n\n while (bb.hasRemaining()) {\n appendPercentEncodedOctet(sb, bb.get() & 0xFF);\n }\n }\n private static final String[] SCHEME = {\"0-9\", \"A-Z\", \"a-z\", \"+\", \"-\", \".\"};\n private static final String[] UNRESERVED = {\"0-9\", \"A-Z\", \"a-z\", \"-\", \".\", \"_\", \"~\"};\n private static final String[] SUB_DELIMS = {\"!\", \"$\", \"&\", \"'\", \"(\", \")\", \"*\", \"+\", \",\", \";\", \"=\"};\n private static final boolean[][] ENCODING_TABLES = creatingEncodingTables();\n\n private static boolean[][] creatingEncodingTables() {\n boolean[][] tables = new boolean[Type.values().length][];\n\n List l = new ArrayList<>(Arrays.asList(SCHEME));\n tables[Type.SCHEME.ordinal()] = creatingEncodingTable(l);\n\n l.clear();\n\n l.addAll(Arrays.asList(UNRESERVED));\n tables[Type.UNRESERVED.ordinal()] = creatingEncodingTable(l);\n\n l.addAll(Arrays.asList(SUB_DELIMS));\n\n tables[Type.HOST.ordinal()] = creatingEncodingTable(l);\n\n tables[Type.PORT.ordinal()] = creatingEncodingTable(Collections.singletonList(\"0-9\"));\n\n l.add(\":\");\n\n tables[Type.USER_INFO.ordinal()] = creatingEncodingTable(l);\n\n l.add(\"@\");\n\n tables[Type.AUTHORITY.ordinal()] = creatingEncodingTable(l);\n\n tables[Type.PATH_SEGMENT.ordinal()] = creatingEncodingTable(l);\n tables[Type.PATH_SEGMENT.ordinal()][';'] = false;\n\n tables[Type.MATRIX_PARAM.ordinal()] = tables[Type.PATH_SEGMENT.ordinal()].clone();\n tables[Type.MATRIX_PARAM.ordinal()]['='] = false;\n\n l.add(\"/\");\n\n tables[Type.PATH.ordinal()] = creatingEncodingTable(l);\n\n l.add(\"?\");\n\n tables[Type.QUERY.ordinal()] = creatingEncodingTable(l);\n\n tables[Type.FRAGMENT.ordinal()] = tables[Type.QUERY.ordinal()];\n\n tables[Type.QUERY_PARAM.ordinal()] = creatingEncodingTable(l);\n tables[Type.QUERY_PARAM.ordinal()]['='] = false;\n tables[Type.QUERY_PARAM.ordinal()]['+'] = false;\n tables[Type.QUERY_PARAM.ordinal()]['&'] = false;\n\n return tables;\n }\n\n private static boolean[] creatingEncodingTable(List allowed) {\n boolean[] table = new boolean[0x80];\n for (String range : allowed) {\n if (range.length() == 1) {\n table[range.charAt(0)] = true;\n } else if (range.length() == 3 && range.charAt(1) == '-') {\n for (int i = range.charAt(0); i <= range.charAt(2); i++) {\n table[i] = true;\n }\n }\n }\n\n return table;\n }\n private static final Charset UTF_8_CHARSET = StandardCharsets.UTF_8;\n\n /**\n * Decodes characters of a string that are percent-encoded octets using \n * UTF-8 decoding (if needed).\n *

\n * It is assumed that the string is valid according to an (unspecified) URI \n * component type. If a sequence of contiguous percent-encoded octets is \n * not a valid UTF-8 character then the octets are replaced with '\\uFFFD'.\n *

\n * If the URI component is of type HOST then any \"%\" found between \"[]\" is \n * left alone. It is an IPv6 literal with a scope_id.\n *

\n * If the URI component is of type QUERY_PARAM then any \"+\" is decoded as\n * as ' '.\n *

\n * @param s the string to be decoded.\n * @param t the URI component type, may be null.\n * @return the decoded string.\n * @throws IllegalArgumentException if a malformed percent-encoded octet is\n * detected\n */\n public static String decode(String s, Type t) {\n if (s == null) {\n throw new IllegalArgumentException();\n }\n\n final int n = s.length();\n if (n == 0) {\n return s;\n }\n\n // If there are no percent-escaped octets\n if (s.indexOf('%') < 0) {\n // If there are no '+' characters for query param\n if (t == Type.QUERY_PARAM) {\n if (s.indexOf('+') < 0) {\n return s;\n }\n } else {\n return s;\n }\n } else {\n // Malformed percent-escaped octet at the end\n if (n < 2) // TODO localize\n {\n throw new IllegalArgumentException(\"Malformed percent-encoded octet at index 1\");\n }\n\n // Malformed percent-escaped octet at the end\n if (s.charAt(n - 2) == '%') // TODO localize\n {\n throw new IllegalArgumentException(\"Malformed percent-encoded octet at index \" + (n - 2));\n }\n }\n\n if (t == null)\n return decode(s, n);\n \n switch (t) {\n case HOST :\n return decodeHost(s, n);\n case QUERY_PARAM :\n return decodeQueryParam(s, n);\n default :\n return decode(s, n);\n }\n }\n\n /**\n * Decode the query component of a URI.\n * \n * @param u the URI.\n * @param decode true if the query parameters of the query component\n * should be in decoded form.\n * @return the multivalued map of query parameters.\n */\n public static Map decodeQuery(URI u, boolean decode) {\n return decodeQuery(u.getRawQuery(), decode);\n }\n\n /**\n * Decode the query component of a URI.\n * \n * @param q the query component in encoded form.\n * @param decode true of the query parameters of the query component\n * should be in decoded form.\n * @return the multivalued map of query parameters.\n */\n public static Map decodeQuery(String q, boolean decode) {\n Map queryParameters = new HashMap<>();\n\n if (q == null || q.length() == 0) {\n return queryParameters;\n }\n\n int s = 0, e;\n do {\n e = q.indexOf('&', s);\n\n if (e == -1) {\n decodeQueryParam(queryParameters, q.substring(s), decode);\n } else if (e > s) {\n decodeQueryParam(queryParameters, q.substring(s, e), decode);\n }\n s = e + 1;\n } while (s > 0 && s < q.length());\n\n return queryParameters;\n }\n\n private static void decodeQueryParam(Map params,\n String param, boolean decode) {\n try {\n int equals = param.indexOf('=');\n if (equals > 0) {\n params.put(\n URLDecoder.decode(param.substring(0, equals), \"UTF-8\"),\n (decode) ? URLDecoder.decode(param.substring(equals + 1), \"UTF-8\") : param.substring(equals + 1));\n } else if (equals == 0) {\n // no key declared, ignore\n } else if (param.length() > 0) {\n params.put(\n URLDecoder.decode(param, \"UTF-8\"),\n \"\");\n }\n } catch (UnsupportedEncodingException ex) {\n // This should never occur\n throw new IllegalArgumentException(ex);\n }\n }\n\n private static final class PathSegmentImpl {\n\n private static final PathSegmentImpl EMPTY_PATH_SEGMENT = new PathSegmentImpl(\"\", false);\n private final String path;\n private final Map matrixParameters;\n\n PathSegmentImpl(String path, boolean decode) {\n this(path, decode, new HashMap ());\n }\n\n PathSegmentImpl(String path, boolean decode, Map matrixParameters) {\n this.path = (decode) ? UriComponent.decode(path, UriComponent.Type.PATH_SEGMENT) : path;\n this.matrixParameters = matrixParameters;\n }\n\n public String getPath() {\n return path;\n }\n\n public Map getMatrixParameters() {\n return matrixParameters;\n }\n }\n\n /**\n * Decode the path component of a URI as path segments.\n *\n * @param u the URI. If the path component is an absolute path component\n * then the leading '/' is ignored and is not considered a delimiator\n * of a path segment.\n * @param decode true if the path segments of the path component\n * should be in decoded form.\n * @return the list of path segments.\n */\n public static List decodePath(URI u, boolean decode) {\n String rawPath = u.getRawPath();\n if (rawPath != null && rawPath.length() > 0 && rawPath.charAt(0) == '/') {\n rawPath = rawPath.substring(1);\n }\n return decodePath(rawPath, decode);\n }\n\n /**\n * Decode the path component of a URI as path segments.\n *

\n * Any '/' character in the path is considered to be a deliminator\n * between two path segments. Thus if the path is '/' then the path segment\n * list will contain two empty path segments. If the path is \"//\" then\n * the path segment list will contain three empty path segments. If the path\n * is \"/a/\" the path segment list will consist of the following path\n * segments in order: \"\", \"a\" and \"\".\n *\n * @param path the path component in encoded form.\n * @param decode true if the path segments of the path component\n * should be in decoded form.\n * @return the list of path segments.\n */\n public static List decodePath(String path, boolean decode) {\n List segments = new LinkedList<>();\n\n if (path == null) {\n return segments;\n }\n\n int s;\n int e = -1;\n do {\n s = e + 1;\n e = path.indexOf('/', s);\n\n if (e > s) {\n decodePathSegment(segments, path.substring(s, e), decode);\n } else if (e == s) {\n segments.add(PathSegmentImpl.EMPTY_PATH_SEGMENT);\n }\n } while (e != -1);\n if (s < path.length()) {\n decodePathSegment(segments, path.substring(s), decode);\n } else {\n segments.add(PathSegmentImpl.EMPTY_PATH_SEGMENT);\n }\n return segments;\n }\n\n public static void decodePathSegment(List segments, String segment, boolean decode) {\n int colon = segment.indexOf(';');\n if (colon != -1) {\n segments.add(new PathSegmentImpl(\n (colon == 0) ? \"\" : segment.substring(0, colon),\n decode,\n decodeMatrix(segment, decode)));\n } else {\n segments.add(new PathSegmentImpl(\n segment,\n decode));\n }\n }\n\n /**\n * Decode the matrix component of a URI path segment.\n *\n * @param pathSegment the path segment component in encoded form.\n * @param decode true if the matrix parameters of the path segment component\n * should be in decoded form.\n * @return the multivalued map of matrix parameters.\n */\n public static Map decodeMatrix(String pathSegment, boolean decode) {\n Map matrixMap = new HashMap<>();\n\n // Skip over path segment\n int s = pathSegment.indexOf(';') + 1;\n if (s == 0 || s == pathSegment.length()) {\n return matrixMap;\n }\n\n int e;\n do {\n e = pathSegment.indexOf(';', s);\n\n if (e == -1) {\n decodeMatrixParam(matrixMap, pathSegment.substring(s), decode);\n } else if (e > s) {\n decodeMatrixParam(matrixMap, pathSegment.substring(s, e), decode);\n }\n s = e + 1;\n } while (s > 0 && s < pathSegment.length());\n\n return matrixMap;\n }\n\n private static void decodeMatrixParam(Map params,\n String param, boolean decode) {\n int equals = param.indexOf('=');\n if (equals > 0) {\n params.put(\n UriComponent.decode(param.substring(0, equals), UriComponent.Type.MATRIX_PARAM),\n (decode) ? UriComponent.decode(param.substring(equals + 1), UriComponent.Type.MATRIX_PARAM) : param.substring(equals + 1));\n } else if (equals == 0) {\n // no key declared, ignore\n } else if (param.length() > 0) {\n params.put(\n UriComponent.decode(param, UriComponent.Type.MATRIX_PARAM),\n \"\");\n }\n }\n\n private static String decode(String s, int n) {\n final StringBuilder sb = new StringBuilder(n);\n ByteBuffer bb = null;\n\n for (int i = 0; i < n;) {\n final char c = s.charAt(i++);\n if (c != '%') {\n sb.append(c);\n } else {\n bb = decodePercentEncodedOctets(s, i, bb);\n i = decodeOctets(i, bb, sb);\n }\n }\n\n return sb.toString();\n }\n\n private static String decodeQueryParam(String s, int n) {\n final StringBuilder sb = new StringBuilder(n);\n ByteBuffer bb = null;\n\n for (int i = 0; i < n;) {\n final char c = s.charAt(i++);\n if (c != '%') {\n if (c != '+')\n sb.append(c);\n else\n sb.append(' ');\n } else {\n bb = decodePercentEncodedOctets(s, i, bb);\n i = decodeOctets(i, bb, sb);\n }\n }\n\n return sb.toString();\n }\n\n private static String decodeHost(String s, int n) {\n final StringBuilder sb = new StringBuilder(n);\n ByteBuffer bb = null;\n\n boolean betweenBrackets = false;\n for (int i = 0; i < n;) {\n final char c = s.charAt(i++);\n if (c == '[') {\n betweenBrackets = true;\n } else if (betweenBrackets && c == ']') {\n betweenBrackets = false;\n }\n\n if (c != '%' || betweenBrackets) {\n sb.append(c);\n } else {\n bb = decodePercentEncodedOctets(s, i, bb);\n i = decodeOctets(i, bb, sb);\n }\n }\n\n return sb.toString();\n }\n\n /**\n * Decode a contigious sequence of percent encoded octets.\n *

\n * Assumes the index, i, starts that the first hex digit of the first\n * percent-encoded octet.\n */\n private static ByteBuffer decodePercentEncodedOctets(String s, int i, ByteBuffer bb) {\n if (bb == null)\n bb = ByteBuffer.allocate(1);\n else\n ((Buffer)bb).clear();\n\n while (true) {\n // Decode the hex digits\n bb.put((byte) (decodeHex(s, i++) << 4 | decodeHex(s, i++)));\n\n // Finish if at the end of the string\n if (i == s.length()) {\n break;\n }\n\n // Finish if no more percent-encoded octets follow\n if (s.charAt(i++) != '%') {\n break;\n }\n\n // Check if the byte buffer needs to be increased in size\n if (bb.position() == bb.capacity()) {\n ((Buffer)bb).flip();\n // Create a new byte buffer with the maximum number of possible\n // octets, hence resize should only occur once\n ByteBuffer bb_new = ByteBuffer.allocate(s.length() / 3);\n bb_new.put(bb);\n bb = bb_new;\n }\n }\n\n ((Buffer)bb).flip();\n return bb;\n }\n\n /**\n * Decodes octets to characters using the UTF-8 decoding and appends\n * the characters to a StringBuffer.\n * @return the index to the next unchecked character in the string to decode\n */\n private static int decodeOctets(int i, ByteBuffer bb, StringBuilder sb) {\n // If there is only one octet and is an ASCII character\n if (bb.limit() == 1 && (bb.get(0) & 0xFF) < 0x80) {\n // Octet can be appended directly\n sb.append((char) bb.get(0));\n return i + 2;\n } else {\n // \n CharBuffer cb = UTF_8_CHARSET.decode(bb);\n sb.append(cb);\n return i + bb.limit() * 3 - 1;\n }\n }\n\n private static int decodeHex(String s, int i) {\n final int v = decodeHex(s.charAt(i));\n if (v == -1) // TODO localize\n {\n throw new IllegalArgumentException(\"Malformed percent-encoded octet at index \" + i +\n \", invalid hexadecimal digit '\" + s.charAt(i) + \"'\");\n }\n return v;\n }\n private static final int[] HEX_TABLE = createHexTable();\n\n private static int[] createHexTable() {\n int[] table = new int[0x80];\n Arrays.fill(table, -1);\n\n for (char c = '0'; c <= '9'; c++) {\n table[c] = c - '0';\n }\n for (char c = 'A'; c <= 'F'; c++) {\n table[c] = c - 'A' + 10;\n }\n for (char c = 'a'; c <= 'f'; c++) {\n table[c] = c - 'a' + 10;\n }\n return table;\n }\n\n private static int decodeHex(char c) {\n return (c < 128) ? HEX_TABLE[c] : -1;\n }\n\n private static boolean isHexCharacter(char c) {\n return c < 128 && HEX_TABLE[c] != -1;\n }\n}", "file_name": "UriComponent.java", "human_label": "Decode the raw path.", "level": "slib_runnable", "lineno": "575", "name": "decodePath", "oracle_context": "{ \"apis\" : \"[getRawPath, length, charAt, substring, PathSegmentImpl]\", \"classes\" : \"[String]\", \"vars\" : \"[]\" }", "package": "org.atmosphere.util.uri", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636766f11a6d9265ec017651", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static Character[] nullToEmpty(final Character[] array){\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n}\n", "docstring": "/** \n *

Defensive programming technique to change a null reference to an empty one.

This method returns an empty array for a null input array.

As a memory optimizing technique an empty array passed in will be overridden with the empty public static references in this class.

\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n", "end_lineno": "597", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

\n *\n *

This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

\n *\n *

#ThreadSafe#

\n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

\n *\n *

This method can be used to initialize:

\n *
\n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
\n *\n *

This method returns null for a null input array.

\n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

Shallow clones an array returning a typecast result and handling\n * null.

\n *\n *

The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

Produces a new array containing the elements between\n * the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n *

The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

\n *\n *
\n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new long array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new int array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new short array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new char array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new byte array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new double array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new float array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new boolean array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

Any multi-dimensional aspects of the arrays are ignored.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

\n *\n *

If the input array is null, 0 is returned.

\n *\n *
\n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
\n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

\n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

Reverses the order of the given array.

\n *\n *

There is no special handling for multi-dimensional arrays.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given object in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

Finds the index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given object within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the object is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

\n *\n *

The method returns false if a null array\n * is passed in.

\n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Characters to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Character to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive chars to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Longs to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Long to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive longs to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Integers to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Integer to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive ints to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Shorts to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Short to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive shorts to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Bytes to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Bytes to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive bytes to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Doubles to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Doubles to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive doubles to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Floats to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Floats to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive floats to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Booleans to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Booleans to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive booleans to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive longs is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive ints is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive chars is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive floats is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive longs is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive ints is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive chars is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive floats is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

\n *\n *
\n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "If array is null or its length is 0, convert array to EMPTY_CHARACTER_OBJECT_ARRAY. Otherwise, return array itself.", "level": "self_contained", "lineno": "579", "name": "nullToEmpty", "oracle_context": "{ \"apis\" : \"[ArrayUtils]\", \"classes\" : \"[ArrayUtils]\", \"vars\" : \"[length, EMPTY_CHARACTER_OBJECT_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636767821a6d9265ec0183ab", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.io.PrintWriter;\\nimport java.io.StringWriter;\\nlong _seqCount;\\nLogLevel _level;\\nString _message;\\nlong _sequenceNumber;\\nlong _millis;\\nString _category;\\nString _thread;\\nString _thrownStackTrace;\\nThrowable _thrown;\\nString _ndc;\\nString _location;\\nLogRecord();\\ngetLevel();\\nsetLevel(LogLevel level);\\nhasThrown();\\nisFatal();\\ngetCategory();\\nsetCategory(String category);\\ngetMessage();\\nsetMessage(String message);\\ngetSequenceNumber();\\nsetSequenceNumber(long number);\\ngetMillis();\\nsetMillis(long millis);\\ngetThreadDescription();\\nsetThreadDescription(String threadDescription);\\ngetThrownStackTrace();\\nsetThrownStackTrace(String trace);\\ngetThrown();\\nsetThrown(Throwable thrown);\\ntoString();\\ngetNDC();\\nsetNDC(String ndc);\\ngetLocation();\\nsetLocation(String location);\\nresetSequenceNumber();\\ngetNextId();\\nisSevereLevel();\\n\", \"repo_level\" : \"\" }", "class_name": "LogRecord", "code": "public boolean hasThrown(){\n Throwable thrown=getThrown();\n if (thrown == null) {\n return false;\n }\n String thrownString=thrown.toString();\n return thrownString != null && thrownString.trim().length() != 0;\n}\n", "docstring": "/** \n * @return true if getThrown().toString() is a non-empty string.\n */\n", "end_lineno": "117", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.log4j.lf5;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.io.StringWriter;\n\n/**\n * LogRecord. A LogRecord encapsulates the details of your desired log\n * request.\n *\n * @author Michael J. Sikorsky\n * @author Robert Shaw\n */\n\n// Contributed by ThoughtWorks Inc.\n\npublic abstract class LogRecord implements java.io.Serializable {\n //--------------------------------------------------------------------------\n // Constants:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Protected Variables:\n //--------------------------------------------------------------------------\n protected static long _seqCount = 0;\n\n protected LogLevel _level;\n protected String _message;\n protected long _sequenceNumber;\n protected long _millis;\n protected String _category;\n protected String _thread;\n protected String _thrownStackTrace;\n protected Throwable _thrown;\n protected String _ndc;\n protected String _location;\n\n //--------------------------------------------------------------------------\n // Private Variables:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Constructors:\n //--------------------------------------------------------------------------\n\n public LogRecord() {\n super();\n\n _millis = System.currentTimeMillis();\n _category = \"Debug\";\n _message = \"\";\n _level = LogLevel.INFO;\n _sequenceNumber = getNextId();\n _thread = Thread.currentThread().toString();\n _ndc = \"\";\n _location = \"\";\n }\n\n //--------------------------------------------------------------------------\n // Public Methods:\n //--------------------------------------------------------------------------\n\n /**\n * Get the level of this LogRecord.\n *\n * @return The LogLevel of this record.\n * @see #setLevel(LogLevel)\n * @see LogLevel\n */\n public LogLevel getLevel() {\n return (_level);\n }\n\n /**\n * Set the level of this LogRecord.\n *\n * @param level The LogLevel for this record.\n * @see #getLevel()\n * @see LogLevel\n */\n public void setLevel(LogLevel level) {\n _level = level;\n }\n\n /**\n * Abstract method. Must be overridden to indicate what log level\n * to show in red.\n */\n public abstract boolean isSevereLevel();\n\n /**\n * @return true if getThrown().toString() is a non-empty string.\n */\n public boolean hasThrown() {\n Throwable thrown = getThrown();\n if (thrown == null) {\n return false;\n }\n String thrownString = thrown.toString();\n return thrownString != null && thrownString.trim().length() != 0;\n }\n\n /**\n * @return true if isSevereLevel() or hasThrown() returns true.\n */\n public boolean isFatal() {\n return isSevereLevel() || hasThrown();\n }\n\n /**\n * Get the category asscociated with this LogRecord. For a more detailed\n * description of what a category is see setCategory().\n *\n * @return The category of this record.\n * @see #setCategory(String)\n */\n public String getCategory() {\n return (_category);\n }\n\n /**\n * Set the category associated with this LogRecord. A category represents\n * a hierarchical dot (\".\") separated namespace for messages.\n * The definition of a category is application specific, but a common convention\n * is as follows:\n *\n *

\n * When logging messages\n * for a particluar class you can use its class name:\n * com.thoughtworks.framework.servlet.ServletServiceBroker.

\n * Futhermore, to log a message for a particular method in a class\n * add the method name:\n * com.thoughtworks.framework.servlet.ServletServiceBroker.init().\n *

\n *\n * @param category The category for this record.\n * @see #getCategory()\n */\n public void setCategory(String category) {\n _category = category;\n }\n\n /**\n * Get the message asscociated with this LogRecord.\n *\n * @return The message of this record.\n * @see #setMessage(String)\n */\n public String getMessage() {\n return (_message);\n }\n\n /**\n * Set the message associated with this LogRecord.\n *\n * @param message The message for this record.\n * @see #getMessage()\n */\n public void setMessage(String message) {\n _message = message;\n }\n\n /**\n * Get the sequence number associated with this LogRecord. Sequence numbers\n * are generally assigned when a LogRecord is constructed. Sequence numbers\n * start at 0 and increase with each newly constructed LogRocord.\n *\n * @return The sequence number of this record.\n * @see #setSequenceNumber(long)\n */\n public long getSequenceNumber() {\n return (_sequenceNumber);\n }\n\n /**\n * Set the sequence number assocsiated with this LogRecord. A sequence number\n * will automatically be assigned to evey newly constructed LogRecord, however,\n * this method can override the value.\n *\n * @param number The sequence number.\n * @see #getSequenceNumber()\n */\n public void setSequenceNumber(long number) {\n _sequenceNumber = number;\n }\n\n /**\n * Get the event time of this record in milliseconds from 1970.\n * When a LogRecord is constructed the event time is set but may be\n * overridden by calling setMillis();\n *\n * @return The event time of this record in milliseconds from 1970.\n * @see #setMillis(long)\n */\n public long getMillis() {\n return _millis;\n }\n\n /**\n * Set the event time of this record. When a LogRecord is constructed\n * the event time is set but may be overridden by calling this method.\n *\n * @param millis The time in milliseconds from 1970.\n * @see #getMillis()\n */\n public void setMillis(long millis) {\n _millis = millis;\n }\n\n /**\n * Get the thread description asscociated with this LogRecord. When a\n * LogRecord is constructed, the thread description is set by calling:\n * Thread.currentThread().toString(). You may supply a thread description\n * of your own by calling the setThreadDescription(String) method.\n *\n * @return The thread description of this record.\n * @see #setThreadDescription(String)\n */\n public String getThreadDescription() {\n return (_thread);\n }\n\n /**\n * Set the thread description associated with this LogRecord. When a\n * LogRecord is constructed, the thread description is set by calling:\n * Thread.currentThread().toString(). You may supply a thread description\n * of your own by calling this method.\n *\n * @param threadDescription The description of the thread for this record.\n * @see #getThreadDescription()\n */\n public void setThreadDescription(String threadDescription) {\n _thread = threadDescription;\n }\n\n /**\n * Get the stack trace in a String-based format for the associated Throwable\n * of this LogRecord. The stack trace in a String-based format is set\n * when the setThrown(Throwable) method is called.\n *\n *

\n * Why do we need this method considering that we\n * have the getThrown() and setThrown() methods?\n * A Throwable object may not be serializable, however, a String representation\n * of it is. Users of LogRecords should generally call this method over\n * getThrown() for the reasons of serialization.\n *

\n *\n * @return The Stack Trace for the asscoiated Throwable of this LogRecord.\n * @see #setThrown(Throwable)\n * @see #getThrown()\n */\n public String getThrownStackTrace() {\n return (_thrownStackTrace);\n }\n\n /**\n * Set the ThrownStackTrace for the log record.\n *\n * @param trace A String to associate with this LogRecord\n * @see #getThrownStackTrace()\n */\n public void setThrownStackTrace(String trace) {\n _thrownStackTrace = trace;\n }\n\n /**\n * Get the Throwable associated with this LogRecord.\n *\n * @return The LogLevel of this record.\n * @see #setThrown(Throwable)\n * @see #getThrownStackTrace()\n */\n public Throwable getThrown() {\n return (_thrown);\n }\n\n /**\n * Set the Throwable associated with this LogRecord. When this method\n * is called, the stack trace in a String-based format is made\n * available via the getThrownStackTrace() method.\n *\n * @param thrown A Throwable to associate with this LogRecord.\n * @see #getThrown()\n * @see #getThrownStackTrace()\n */\n public void setThrown(Throwable thrown) {\n if (thrown == null) {\n return;\n }\n _thrown = thrown;\n StringWriter sw = new StringWriter();\n PrintWriter out = new PrintWriter(sw);\n thrown.printStackTrace(out);\n out.flush();\n _thrownStackTrace = sw.toString();\n try {\n out.close();\n sw.close();\n } catch (IOException e) {\n // Do nothing, this should not happen as it is StringWriter.\n }\n out = null;\n sw = null;\n }\n\n /**\n * Return a String representation of this LogRecord.\n */\n public String toString() {\n StringBuffer buf = new StringBuffer();\n buf.append(\"LogRecord: [\" + _level + \", \" + _message + \"]\");\n return (buf.toString());\n }\n\n /**\n * Get the NDC (nested diagnostic context) for this record.\n *\n * @return The string representing the NDC.\n */\n public String getNDC() {\n return _ndc;\n }\n\n /**\n * Set the NDC (nested diagnostic context) for this record.\n *\n * @param ndc A string representing the NDC.\n */\n public void setNDC(String ndc) {\n _ndc = ndc;\n }\n\n /**\n * Get the location in code where this LogRecord originated.\n *\n * @return The string containing the location information.\n */\n public String getLocation() {\n return _location;\n }\n\n /**\n * Set the location in code where this LogRecord originated.\n *\n * @param location A string containing location information.\n */\n public void setLocation(String location) {\n _location = location;\n }\n\n /**\n * Resets that sequence number to 0.\n *\n */\n public static synchronized void resetSequenceNumber() {\n _seqCount = 0;\n }\n\n //--------------------------------------------------------------------------\n // Protected Methods:\n //--------------------------------------------------------------------------\n\n protected static synchronized long getNextId() {\n _seqCount++;\n return _seqCount;\n }\n //--------------------------------------------------------------------------\n // Private Methods:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Nested Top-Level Classes or Interfaces:\n //--------------------------------------------------------------------------\n\n}\n\n\n\n", "file_name": "LogRecord.java", "human_label": "Check whether there is a thrown", "level": "class_runnable", "lineno": "107", "name": "hasThrown", "oracle_context": "{ \"apis\" : \"[getThrown, toString, length, trim]\", \"classes\" : \"[Throwable, String]\", \"vars\" : \"[]\" }", "package": "org.apache.log4j.lf5", "project": "logging-log4j1-main" }, { "_id": "636767831a6d9265ec0183c9", "all_context": "{ \"class_level\" : \"import java.util.Hashtable;\\nimport java.util.Stack;\\nimport java.util.Enumeration;\\nimport java.util.Vector;\\nimport org.apache.log4j.helpers.LogLog;\\nHashtable ht;\\nint pushCounter;\\nint REAP_THRESHOLD;\\nString fullMessage;\\nString message;\\nNDC();\\ngetCurrentStack();\\ncloneStack();\\ninherit(Stack stack);\\nget();\\ngetDepth();\\nlazyRemove();\\npop();\\npeek();\\npush(String message);\\nremove();\\nsetMaxDepth(int maxDepth);\\nDiagnosticContext(String message,DiagnosticContext parent);\\nclear();\\n\", \"repo_level\" : \"public interface LogLog {public void setInternalDebugging(boolean enabled);\\nstatic void debug(String msg);\\nstatic void debug(String msg,Throwable t);\\nstatic void error(String msg);\\nstatic void error(String msg,Throwable t);\\nstatic void setQuietMode(boolean quietMode);\\nstatic void warn(String msg);\\nstatic void warn(String msg,Throwable t);\\n }\\n\" }", "class_name": "NDC", "code": "public static String peek(){\n Stack stack=getCurrentStack();\n if (stack != null && !stack.isEmpty()) return ((DiagnosticContext)stack.peek()).message;\n else return \"\";\n}\n", "docstring": "/** \n * Looks at the last diagnostic context at the top of this NDC without removing it.

The returned value is the value that was pushed last. If no context is available, then the empty string \"\" is returned.\n * @return String The innermost diagnostic context.\n */\n", "end_lineno": "326", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Contributors: Dan Milstein \n// Ray Millard\n\npackage org.apache.log4j;\n\nimport java.util.Hashtable;\nimport java.util.Stack;\nimport java.util.Enumeration;\nimport java.util.Vector;\n\nimport org.apache.log4j.helpers.LogLog;\n\n/**\n The NDC class implements nested diagnostic contexts as\n defined by Neil Harrison in the article \"Patterns for Logging\n Diagnostic Messages\" part of the book \"Pattern Languages of\n Program Design 3\" edited by Martin et al.\n\n

A Nested Diagnostic Context, or NDC in short, is an instrument\n to distinguish interleaved log output from different sources. Log\n output is typically interleaved when a server handles multiple\n clients near-simultaneously.\n\n

Interleaved log output can still be meaningful if each log entry\n from different contexts had a distinctive stamp. This is where NDCs\n come into play.\n\n

Note that NDCs are managed on a per thread\n basis. NDC operations such as {@link #push push}, {@link\n #pop}, {@link #clear}, {@link #getDepth} and {@link #setMaxDepth}\n affect the NDC of the current thread only. NDCs of other\n threads remain unaffected.\n\n

For example, a servlet can build a per client request NDC\n consisting the clients host name and other information contained in\n the the request. Cookies are another source of distinctive\n information. To build an NDC one uses the {@link #push push}\n operation. Simply put,\n\n

    \n
  • Contexts can be nested.\n\n

  • When entering a context, call NDC.push. As a\n side effect, if there is no nested diagnostic context for the\n current thread, this method will create it.\n\n

  • When leaving a context, call NDC.pop.\n\n

  • When exiting a thread make sure to call {@link #remove\n NDC.remove()}. \n
\n \n

There is no penalty for forgetting to match each\n push operation with a corresponding pop,\n except the obvious mismatch between the real application context\n and the context set in the NDC.\n\n

If configured to do so, {@link PatternLayout} and {@link\n TTCCLayout} instances automatically retrieve the nested diagnostic\n context for the current thread without any user intervention.\n Hence, even if a servlet is serving multiple clients\n simultaneously, the logs emanating from the same code (belonging to\n the same category) can still be distinguished because each client\n request will have a different NDC tag.\n\n

Heavy duty systems should call the {@link #remove} method when\n leaving the run method of a thread. This ensures that the memory\n used by the thread can be freed by the Java garbage\n collector. There is a mechanism to lazily remove references to dead\n threads. In practice, this means that you can be a little sloppy\n and sometimes forget to call {@link #remove} before exiting a\n thread.\n \n

A thread may inherit the nested diagnostic context of another\n (possibly parent) thread using the {@link #inherit inherit}\n method. A thread may obtain a copy of its NDC with the {@link\n #cloneStack cloneStack} method and pass the reference to any other\n thread, in particular to a child.\n \n @author Ceki Gülcü\n @since 0.7.0\n \n*/\n \npublic class NDC {\n\n // The synchronized keyword is not used in this class. This may seem\n // dangerous, especially since the class will be used by\n // multiple-threads. In particular, all threads share the same\n // hashtable (the \"ht\" variable). This is OK since java hashtables\n // are thread safe. Same goes for Stacks.\n\n // More importantly, when inheriting diagnostic contexts the child\n // thread is handed a clone of the parent's NDC. It follows that\n // each thread has its own NDC (i.e. stack).\n\n static Hashtable ht = new Hashtable();\n\n static int pushCounter = 0; // the number of times push has been called\n // after the latest call to lazyRemove\n\n // The number of times we allow push to be called before we call lazyRemove\n // 5 is a relatively small number. As such, lazyRemove is not called too\n // frequently. We thus avoid the cost of creating an Enumeration too often.\n // The higher this number, the longer is the avarage period for which all\n // logging calls in all threads are blocked.\n static final int REAP_THRESHOLD = 5;\n \n // No instances allowed.\n private NDC() {}\n \n /**\n * Get NDC stack for current thread.\n * @return NDC stack for current thread.\n */\n private static Stack getCurrentStack() {\n if (ht != null) {\n return (Stack) ht.get(Thread.currentThread());\n }\n return null;\n }\n\n\n /**\n Clear any nested diagnostic information if any. This method is\n useful in cases where the same thread can be potentially used\n over and over in different unrelated contexts.\n\n

This method is equivalent to calling the {@link #setMaxDepth}\n method with a zero maxDepth argument.\n \n @since 0.8.4c */\n public\n static\n void clear() {\n Stack stack = getCurrentStack(); \n if(stack != null) \n stack.setSize(0); \n }\n\n \n /**\n Clone the diagnostic context for the current thread.\n\n

Internally a diagnostic context is represented as a stack. A\n given thread can supply the stack (i.e. diagnostic context) to a\n child thread so that the child can inherit the parent thread's\n diagnostic context.\n\n

The child thread uses the {@link #inherit inherit} method to\n inherit the parent's diagnostic context.\n \n @return Stack A clone of the current thread's diagnostic context.\n\n */\n public\n static\n Stack cloneStack() {\n Stack stack = getCurrentStack();\n if(stack == null)\n return null;\n else {\n return (Stack) stack.clone();\n }\n }\n\n \n /**\n Inherit the diagnostic context of another thread.\n\n

The parent thread can obtain a reference to its diagnostic\n context using the {@link #cloneStack} method. It should\n communicate this information to its child so that it may inherit\n the parent's diagnostic context.\n\n

The parent's diagnostic context is cloned before being\n inherited. In other words, once inherited, the two diagnostic\n contexts can be managed independently.\n \n

In java, a child thread cannot obtain a reference to its\n parent, unless it is directly handed the reference. Consequently,\n there is no client-transparent way of inheriting diagnostic\n contexts. Do you know any solution to this problem?\n\n @param stack The diagnostic context of the parent thread.\n\n */\n public\n static\n void inherit(Stack stack) {\n if(stack != null)\n ht.put(Thread.currentThread(), stack);\n }\n\n\n /**\n Never use this method directly, use the {@link\n org.apache.log4j.spi.LoggingEvent#getNDC} method instead.\n */\n static\n public\n String get() {\n Stack s = getCurrentStack();\n if(s != null && !s.isEmpty()) \n return ((DiagnosticContext) s.peek()).fullMessage;\n else\n return null;\n }\n \n /**\n * Get the current nesting depth of this diagnostic context.\n *\n * @see #setMaxDepth\n * @since 0.7.5\n */\n public\n static\n int getDepth() {\n Stack stack = getCurrentStack(); \n if(stack == null)\n return 0;\n else\n return stack.size(); \n }\n\n private\n static\n void lazyRemove() {\n if (ht == null) return;\n \n // The synchronization on ht is necessary to prevent JDK 1.2.x from\n // throwing ConcurrentModificationExceptions at us. This sucks BIG-TIME.\n // One solution is to write our own hashtable implementation.\n Vector v;\n \n synchronized(ht) {\n // Avoid calling clean-up too often.\n if(++pushCounter <= REAP_THRESHOLD) {\n\treturn; // We release the lock ASAP.\n } else {\n\tpushCounter = 0; // OK let's do some work.\n }\n\n int misses = 0;\n v = new Vector(); \n Enumeration enumeration = ht.keys();\n // We give up after 4 straigt missses. That is 4 consecutive\n // inspected threads in 'ht' that turn out to be alive.\n // The higher the proportion on dead threads in ht, the higher the\n // chances of removal.\n while(enumeration.hasMoreElements() && (misses <= 4)) {\n\tThread t = (Thread) enumeration.nextElement();\n\tif(t.isAlive()) {\n\t misses++;\n\t} else {\n\t misses = 0;\n\t v.addElement(t);\n\t}\n }\n } // synchronized\n\n int size = v.size();\n for(int i = 0; i < size; i++) {\n Thread t = (Thread) v.elementAt(i);\n LogLog.debug(\"Lazy NDC removal for thread [\" + t.getName() + \"] (\"+ \n\t\t ht.size() + \").\");\n ht.remove(t);\n }\n }\n\n /**\n Clients should call this method before leaving a diagnostic\n context.\n\n

The returned value is the value that was pushed last. If no\n context is available, then the empty string \"\" is returned.\n \n @return String The innermost diagnostic context.\n \n */\n public\n static\n String pop() {\n Stack stack = getCurrentStack();\n if(stack != null && !stack.isEmpty()) \n return ((DiagnosticContext) stack.pop()).message;\n else\n return \"\";\n }\n\n /**\n Looks at the last diagnostic context at the top of this NDC\n without removing it.\n\n

The returned value is the value that was pushed last. If no\n context is available, then the empty string \"\" is returned.\n \n @return String The innermost diagnostic context.\n \n */\n public\n static\n String peek() {\n Stack stack = getCurrentStack();\n if(stack != null && !stack.isEmpty())\n return ((DiagnosticContext) stack.peek()).message;\n else\n return \"\";\n }\n \n /**\n Push new diagnostic context information for the current thread.\n\n

The contents of the message parameter is\n determined solely by the client. \n \n @param message The new diagnostic context information. */\n public\n static\n void push(String message) {\n Stack stack = getCurrentStack();\n \n if(stack == null) {\n DiagnosticContext dc = new DiagnosticContext(message, null); \n stack = new Stack();\n Thread key = Thread.currentThread();\n ht.put(key, stack);\n stack.push(dc);\n } else if (stack.isEmpty()) {\n DiagnosticContext dc = new DiagnosticContext(message, null); \n stack.push(dc);\n } else {\n DiagnosticContext parent = (DiagnosticContext) stack.peek();\n stack.push(new DiagnosticContext(message, parent));\n } \n }\n\n /**\n Remove the diagnostic context for this thread.\n\n

Each thread that created a diagnostic context by calling\n {@link #push} should call this method before exiting. Otherwise,\n the memory used by the thread cannot be reclaimed by the\n VM.\n\n

As this is such an important problem in heavy duty systems and\n because it is difficult to always guarantee that the remove\n method is called before exiting a thread, this method has been\n augmented to lazily remove references to dead threads. In\n practice, this means that you can be a little sloppy and\n occasionally forget to call {@link #remove} before exiting a\n thread. However, you must call remove sometime. If\n you never call it, then your application is sure to run out of\n memory.\n \n */\n static\n public\n void remove() {\n if (ht != null) {\n ht.remove(Thread.currentThread());\n \n // Lazily remove dead-thread references in ht.\n lazyRemove();\n }\n }\n\n /**\n Set maximum depth of this diagnostic context. If the current\n depth is smaller or equal to maxDepth, then no\n action is taken.\n\n

This method is a convenient alternative to multiple {@link\n #pop} calls. Moreover, it is often the case that at the end of\n complex call sequences, the depth of the NDC is\n unpredictable. The setMaxDepth method circumvents\n this problem.\n\n

For example, the combination\n

\n       void foo() {\n          int depth = NDC.getDepth();\n\n          ... complex sequence of calls\n\n          NDC.setMaxDepth(depth);\n       }\n     
\n\n ensures that between the entry and exit of foo the depth of the\n diagnostic stack is conserved.\n \n @see #getDepth\n @since 0.7.5 */\n static\n public\n void setMaxDepth(int maxDepth) {\n Stack stack = getCurrentStack(); \n if(stack != null && maxDepth < stack.size()) \n stack.setSize(maxDepth);\n }\n \n // =====================================================================\n private static class DiagnosticContext {\n\n String fullMessage;\n String message;\n \n DiagnosticContext(String message, DiagnosticContext parent) {\n this.message = message;\n if(parent != null) {\n\tfullMessage = parent.fullMessage + ' ' + message;\n } else {\n\tfullMessage = message;\n }\n }\n }\n}\n\n", "file_name": "NDC.java", "human_label": "Return the value at the top of the stack", "level": "class_runnable", "lineno": "308", "name": "peek", "oracle_context": "{ \"apis\" : \"[getCurrentStack, isEmpty, DiagnosticContext]\", \"classes\" : \"[Stack]\", \"vars\" : \"[message]\" }", "package": "org.apache.log4j", "project": "logging-log4j1-main" }, { "_id": "636767de1a6d9265ec01871c", "all_context": "{ \"class_level\" : \"import java.util.ArrayList;\\nimport java.util.Comparator;\\nimport java.util.HashMap;\\nimport java.util.List;\\nimport java.util.Set;\\nimport java.util.stream.Collectors;\\nimport lombok.EqualsAndHashCode;\\nimport lombok.ToString;\\nimport org.apache.skywalking.oap.server.core.Const;\\nimport org.apache.skywalking.oap.server.core.storage.type.StorageDataComplexObject;\\nHashMap data;\\nDataTable();\\nDataTable(int initialCapacity);\\nDataTable(String data);\\nget(String key);\\nput(String key,Long value);\\nsumOfValues();\\nkeysEqual(DataTable that);\\nsortedKeys(Comparator keyComparator);\\nsortedValues(Comparator keyComparator);\\nkeys();\\nhasData();\\nhasKey(String key);\\nsize();\\ntoStorageData();\\ntoObject(String data);\\ncopyFrom(DataTable source);\\nappend(DataTable dataTable);\\n\", \"repo_level\" : \"public interface Const { }\\npublic interface StorageDataComplexObject { String toStorageData();\\n void toObject(String data);\\n void copyFrom(T source);\\npublic void serialize(StorageDataComplexObject value,JsonGenerator gen,SerializerProvider provider);\\n }\\n\" }", "class_name": "DataTable", "code": "public void valueAccumulation(String key,Long value){\n Long element=data.get(key);\n if (element == null) {\n element=value;\n }\n else {\n element+=value;\n }\n data.put(key,element);\n}\n", "docstring": "/** \n * Accumulate the value with existing value in the same given key.\n */\n", "end_lineno": "71", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.skywalking.oap.server.core.analysis.metrics;\n\nimport java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport lombok.EqualsAndHashCode;\nimport lombok.ToString;\nimport org.apache.skywalking.oap.server.core.Const;\nimport org.apache.skywalking.oap.server.core.storage.type.StorageDataComplexObject;\n\n/**\n * DataTable includes a hashmap to store string key and long value. It enhanced the serialization capability.\n */\n@ToString\n@EqualsAndHashCode\npublic class DataTable implements StorageDataComplexObject {\n private HashMap data;\n\n public DataTable() {\n data = new HashMap<>();\n }\n\n public DataTable(int initialCapacity) {\n data = new HashMap<>(initialCapacity);\n }\n\n public DataTable(String data) {\n this();\n toObject(data);\n }\n\n public Long get(String key) {\n return data.get(key);\n }\n\n public void put(String key, Long value) {\n data.put(key, value);\n }\n\n /**\n * Accumulate the value with existing value in the same given key.\n */\n public void valueAccumulation(String key, Long value) {\n Long element = data.get(key);\n if (element == null) {\n element = value;\n } else {\n element += value;\n }\n data.put(key, element);\n }\n\n /**\n * @return the sum of all values.\n */\n public long sumOfValues() {\n return data.values().stream().mapToLong(element -> element).sum();\n }\n\n public boolean keysEqual(DataTable that) {\n if (this.data.keySet().size() != that.data.keySet().size()) {\n return false;\n }\n return this.data.keySet().equals(that.data.keySet());\n }\n\n public List sortedKeys(Comparator keyComparator) {\n return data.keySet().stream().sorted(keyComparator).collect(Collectors.toList());\n }\n\n public List sortedValues(Comparator keyComparator) {\n final List collect = data.keySet().stream().sorted(keyComparator).collect(Collectors.toList());\n List values = new ArrayList<>(collect.size());\n collect.forEach(key -> values.add(data.get(key)));\n return values;\n }\n\n public Set keys() {\n return data.keySet();\n }\n\n public boolean hasData() {\n return !data.isEmpty();\n }\n\n public boolean hasKey(String key) {\n return data.containsKey(key);\n }\n\n public int size() {\n return data.size();\n }\n\n @Override\n public String toStorageData() {\n StringBuilder builder = new StringBuilder();\n\n this.data.forEach((key, value) -> {\n if (builder.length() != 0) {\n // For the first element.\n builder.append(Const.ARRAY_SPLIT);\n }\n builder.append(key).append(Const.KEY_VALUE_SPLIT).append(value);\n });\n return builder.toString();\n }\n\n @Override\n public void toObject(String data) {\n String[] keyValues = data.split(Const.ARRAY_PARSER_SPLIT);\n for (String keyValue : keyValues) {\n final String[] keyValuePair = keyValue.split(Const.KEY_VALUE_SPLIT);\n if (keyValuePair.length == 2) {\n this.data.put(keyValuePair[0], Long.parseLong(keyValuePair[1]));\n }\n }\n }\n\n @Override\n public void copyFrom(final DataTable source) {\n this.append(source);\n }\n\n public DataTable append(DataTable dataTable) {\n dataTable.data.forEach((key, value) -> {\n Long current = this.data.get(key);\n if (current == null) {\n current = value;\n } else {\n current += value;\n }\n this.data.put(key, current);\n });\n return this;\n }\n}\n", "file_name": "DataTable.java", "human_label": "Add the value to the original value of the key.", "level": "class_runnable", "lineno": "60", "name": "valueAccumulation", "oracle_context": "{ \"apis\" : \"[get, put]\", \"classes\" : \"[Long]\", \"vars\" : \"[data]\" }", "package": "org.apache.skywalking.oap.server.core.analysis.metrics", "project": "skywalking-master" }, { "_id": "636766811a6d9265ec017496", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.io.InputStream;\\nimport java.util.Deque;\\nimport java.util.LinkedList;\\nDeque stack;\\nint rootCount;\\nInputStream current;\\nInputStreamIterator(InputStream filesOrDirectories);\\naddReverse(InputStream[] files);\\n\", \"repo_level\" : \"\" }", "class_name": "InputStreamIterator", "code": "public InputStream next() throws IOException {\n if (stack.isEmpty()) {\n current=null;\n return null;\n }\n else {\n current=stack.removeLast();\n return current;\n }\n}\n", "docstring": "/** \n * Return the next {@link java.io.File} object or {@code null} if no more files areavailable.\n */\n", "end_lineno": "74", "file_content": "package org.atmosphere.util.annotation;/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Deque;\nimport java.util.LinkedList;\n\n/**\n * {@code FileIterator} enables iteration over all files in a directory and all\n * its sub directories.\n *
\n * Usage:\n *
\n * FileIterator iter = new FileIterator(new File(\"./src\"));\n * File f;\n * while ((f = iter.next()) != null) {\n *     // do something with f\n *     assert f == iter.getCurrent();\n * }\n * 
\n *\n * @author Ronald K. Muller\n * @since annotation-detector 3.0.0\n */\npublic final class InputStreamIterator {\n\n private final Deque stack;\n private final int rootCount;\n private InputStream current;\n\n /**\n * Create a new {@code FileIterator} using the specified 'filesOrDirectories' as root.\n *
\n * If 'filesOrDirectories' contains a file, the iterator just returns that single file.\n * If 'filesOrDirectories' contains a directory, all files in that directory\n * and its sub directories are returned (depth first).\n *\n * @param filesOrDirectories Zero or more {@link java.io.File} objects, which are iterated\n * in the specified order (depth first)\n */\n public InputStreamIterator(final InputStream... filesOrDirectories) {\n addReverse(filesOrDirectories);\n stack = new LinkedList<>();\n rootCount = 0;\n }\n\n /**\n * Return the next {@link java.io.File} object or {@code null} if no more files are\n * available.\n *\n */\n public InputStream next() throws IOException {\n if (stack.isEmpty()) {\n current = null;\n return null;\n } else {\n current = stack.removeLast();\n return current;\n }\n }\n\n /**\n * Add the specified files in reverse order.\n */\n private void addReverse(final InputStream[] files) {\n for (int i = files.length - 1; i >=0; --i) {\n stack.add(files[i]);\n }\n }\n\n}\n\n", "file_name": "InputStreamIterator.java", "human_label": "If the stack is not empty, the last element of the stack is returned. Otherwise, null is returned.", "level": "class_runnable", "lineno": "61", "name": "next", "oracle_context": "{ \"apis\" : \"[isEmpty, removeLast]\", \"classes\" : \"[]\", \"vars\" : \"[stack, current]\" }", "package": "org.atmosphere.util.annotation", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "6367677e1a6d9265ec01832e", "all_context": "{ \"class_level\" : \"import java.util.Hashtable;\\nimport java.util.Enumeration;\\nimport java.util.Vector;\\nimport org.apache.log4j.spi.LoggerFactory;\\nimport org.apache.log4j.spi.HierarchyEventListener;\\nimport org.apache.log4j.spi.LoggerRepository;\\nimport org.apache.log4j.spi.RendererSupport;\\nimport org.apache.log4j.or.RendererMap;\\nimport org.apache.log4j.or.ObjectRenderer;\\nimport org.apache.log4j.helpers.LogLog;\\nimport org.apache.log4j.spi.ThrowableRendererSupport;\\nimport org.apache.log4j.spi.ThrowableRenderer;\\nLoggerFactory defaultFactory;\\nVector listeners;\\nHashtable ht;\\nLogger root;\\nRendererMap rendererMap;\\nint thresholdInt;\\nLevel threshold;\\nboolean emittedNoAppenderWarning;\\nboolean emittedNoResourceBundleWarning;\\nThrowableRenderer throwableRenderer;\\nHierarchy(Logger root);\\naddHierarchyEventListener(HierarchyEventListener listener);\\nclear();\\nemitNoAppenderWarning(Category cat);\\nexists(String name);\\nsetThreshold(String levelStr);\\nsetThreshold(Level l);\\nfireAddAppenderEvent(Category logger,Appender appender);\\nfireRemoveAppenderEvent(Category logger,Appender appender);\\ngetThreshold();\\ngetLogger(String name);\\ngetLogger(String name,LoggerFactory factory);\\ngetCurrentLoggers();\\ngetCurrentCategories();\\ngetRendererMap();\\ngetRootLogger();\\nisDisabled(int level);\\noverrideAsNeeded(String override);\\nresetConfiguration();\\nsetDisableOverride(String override);\\nsetRenderer(Class renderedClass,ObjectRenderer renderer);\\nsetThrowableRenderer(ThrowableRenderer renderer);\\ngetThrowableRenderer();\\nshutdown();\\nupdateParents(Logger cat);\\nupdateChildren(ProvisionNode pn,Logger logger);\\naddRenderer(Class classToRender,ObjectRenderer or);\\n\", \"repo_level\" : \"public interface LoggerFactory {public Logger makeNewLoggerInstance(String name);\\n }\\npublic interface HierarchyEventListener {public void addAppenderEvent(Category cat,Appender appender);\\npublic void removeAppenderEvent(Category cat,Appender appender);\\n }\\npublic interface LoggerRepository {public void addHierarchyEventListener(HierarchyEventListener listener);\\n boolean isDisabled(int level);\\npublic void setThreshold(Level level);\\npublic void setThreshold(String val);\\npublic void emitNoAppenderWarning(Category cat);\\npublic Level getThreshold();\\npublic Logger getLogger(String name);\\npublic Logger getLogger(String name,LoggerFactory factory);\\npublic Logger getRootLogger();\\nabstract Logger exists(String name);\\nabstract void shutdown();\\npublic Enumeration getCurrentLoggers();\\npublic Enumeration getCurrentCategories();\\nabstract void fireAddAppenderEvent(Category logger,Appender appender);\\nabstract void resetConfiguration();\\n }\\npublic interface RendererSupport {public RendererMap getRendererMap();\\npublic void setRenderer(Class renderedClass,ObjectRenderer renderer);\\n }\\npublic interface RendererMap {public void addRenderer(RendererSupport repository,String renderedClassName,String renderingClassName);\\npublic String findAndRender(Object o);\\npublic ObjectRenderer get(Object o);\\npublic ObjectRenderer get(Class clazz);\\n ObjectRenderer searchInterfaces(Class c);\\npublic ObjectRenderer getDefaultRenderer();\\npublic void clear();\\npublic void put(Class clazz,ObjectRenderer or);\\n }\\npublic interface ObjectRenderer {public String doRender(Object o);\\n }\\npublic interface LogLog {public void setInternalDebugging(boolean enabled);\\nstatic void debug(String msg);\\nstatic void debug(String msg,Throwable t);\\nstatic void error(String msg);\\nstatic void error(String msg,Throwable t);\\nstatic void setQuietMode(boolean quietMode);\\nstatic void warn(String msg);\\nstatic void warn(String msg,Throwable t);\\n }\\npublic interface ThrowableRendererSupport { ThrowableRenderer getThrowableRenderer();\\n void setThrowableRenderer(ThrowableRenderer renderer);\\n }\\npublic interface ThrowableRenderer {public String[] doRender(Throwable t);\\n }\\n\" }", "class_name": "Hierarchy", "code": "public Logger exists(String name){\n Object o=ht.get(new CategoryKey(name));\n if (o instanceof Logger) {\n return (Logger)o;\n }\n else {\n return null;\n }\n}\n", "docstring": "/** \n * Check if the named logger exists in the hierarchy. If so return its reference, otherwise returns null.\n * @param name The name of the logger to search for.\n */\n", "end_lineno": "160", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// WARNING This class MUST not have references to the Category or\n// WARNING RootCategory classes in its static initiliazation neither\n// WARNING directly nor indirectly.\n\n// Contributors:\n// Luke Blanshard \n// Mario Schomburg - IBM Global Services/Germany\n// Anders Kristensen\n// Igor Poteryaev\n\npackage org.apache.log4j;\n\n\nimport java.util.Hashtable;\nimport java.util.Enumeration;\nimport java.util.Vector;\n\nimport org.apache.log4j.spi.LoggerFactory;\nimport org.apache.log4j.spi.HierarchyEventListener;\nimport org.apache.log4j.spi.LoggerRepository;\nimport org.apache.log4j.spi.RendererSupport;\nimport org.apache.log4j.or.RendererMap;\nimport org.apache.log4j.or.ObjectRenderer;\nimport org.apache.log4j.helpers.LogLog;\nimport org.apache.log4j.spi.ThrowableRendererSupport;\nimport org.apache.log4j.spi.ThrowableRenderer;\n\n/**\n This class is specialized in retrieving loggers by name and also\n maintaining the logger hierarchy.\n\n

The casual user does not have to deal with this class\n directly.\n\n

The structure of the logger hierarchy is maintained by the\n {@link #getLogger} method. The hierarchy is such that children link\n to their parent but parents do not have any pointers to their\n children. Moreover, loggers can be instantiated in any order, in\n particular descendant before ancestor.\n\n

In case a descendant is created before a particular ancestor,\n then it creates a provision node for the ancestor and adds itself\n to the provision node. Other descendants of the same ancestor add\n themselves to the previously created provision node.\n\n @author Ceki Gülcü\n\n*/\npublic class Hierarchy implements LoggerRepository, RendererSupport, ThrowableRendererSupport {\n\n private LoggerFactory defaultFactory;\n private Vector listeners;\n\n Hashtable ht;\n Logger root;\n RendererMap rendererMap;\n\n int thresholdInt;\n Level threshold;\n\n boolean emittedNoAppenderWarning = false;\n boolean emittedNoResourceBundleWarning = false;\n\n private ThrowableRenderer throwableRenderer = null;\n\n /**\n Create a new logger hierarchy.\n\n @param root The root of the new hierarchy.\n\n */\n public\n Hierarchy(Logger root) {\n ht = new Hashtable();\n listeners = new Vector(1);\n this.root = root;\n // Enable all level levels by default.\n setThreshold(Level.ALL);\n this.root.setHierarchy(this);\n rendererMap = new RendererMap();\n defaultFactory = new DefaultCategoryFactory();\n }\n\n /**\n Add an object renderer for a specific class.\n */\n public\n void addRenderer(Class classToRender, ObjectRenderer or) {\n rendererMap.put(classToRender, or);\n }\n\n public\n void addHierarchyEventListener(HierarchyEventListener listener) {\n if(listeners.contains(listener)) {\n LogLog.warn(\"Ignoring attempt to add an existent listener.\");\n } else {\n listeners.addElement(listener);\n }\n }\n\n /**\n This call will clear all logger definitions from the internal\n hashtable. Invoking this method will irrevocably mess up the\n logger hierarchy.\n\n

You should really know what you are doing before\n invoking this method.\n\n @since 0.9.0 */\n public\n void clear() {\n //System.out.println(\"\\n\\nAbout to clear internal hash table.\");\n ht.clear();\n }\n\n public\n void emitNoAppenderWarning(Category cat) {\n // No appenders in hierarchy, warn user only once.\n if(!this.emittedNoAppenderWarning) {\n LogLog.warn(\"No appenders could be found for logger (\" +\n\t\t cat.getName() + \").\");\n LogLog.warn(\"Please initialize the log4j system properly.\");\n LogLog.warn(\"See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.\");\n this.emittedNoAppenderWarning = true;\n }\n }\n\n /**\n Check if the named logger exists in the hierarchy. If so return\n its reference, otherwise returns null.\n\n @param name The name of the logger to search for.\n\n */\n public\n Logger exists(String name) {\n Object o = ht.get(new CategoryKey(name));\n if(o instanceof Logger) {\n return (Logger) o;\n } else {\n return null;\n }\n }\n\n /**\n The string form of {@link #setThreshold(Level)}.\n */\n public\n void setThreshold(String levelStr) {\n Level l = (Level) Level.toLevel(levelStr, null);\n if(l != null) {\n setThreshold(l);\n } else {\n LogLog.warn(\"Could not convert [\"+levelStr+\"] to Level.\");\n }\n }\n\n\n /**\n Enable logging for logging requests with level l or\n higher. By default all levels are enabled.\n\n @param l The minimum level for which logging requests are sent to\n their appenders. */\n public\n void setThreshold(Level l) {\n if(l != null) {\n thresholdInt = l.level;\n threshold = l;\n }\n }\n\n public\n void fireAddAppenderEvent(Category logger, Appender appender) {\n if(listeners != null) {\n int size = listeners.size();\n HierarchyEventListener listener;\n for(int i = 0; i < size; i++) {\n\tlistener = (HierarchyEventListener) listeners.elementAt(i);\n\tlistener.addAppenderEvent(logger, appender);\n }\n }\n }\n\n void fireRemoveAppenderEvent(Category logger, Appender appender) {\n if(listeners != null) {\n int size = listeners.size();\n HierarchyEventListener listener;\n for(int i = 0; i < size; i++) {\n\tlistener = (HierarchyEventListener) listeners.elementAt(i);\n\tlistener.removeAppenderEvent(logger, appender);\n }\n }\n }\n\n /**\n Returns a {@link Level} representation of the enable\n state.\n\n @since 1.2 */\n public\n Level getThreshold() {\n return threshold;\n }\n\n /**\n Returns an integer representation of the this repository's\n threshold.\n\n @since 1.2 */\n //public\n //int getThresholdInt() {\n // return thresholdInt;\n //}\n\n\n /**\n Return a new logger instance named as the first parameter using\n the default factory.\n\n

If a logger of that name already exists, then it will be\n returned. Otherwise, a new logger will be instantiated and\n then linked with its existing ancestors as well as children.\n\n @param name The name of the logger to retrieve.\n\n */\n public\n Logger getLogger(String name) {\n return getLogger(name, defaultFactory);\n }\n\n /**\n Return a new logger instance named as the first parameter using\n factory.\n\n

If a logger of that name already exists, then it will be\n returned. Otherwise, a new logger will be instantiated by the\n factory parameter and linked with its existing\n ancestors as well as children.\n\n @param name The name of the logger to retrieve.\n @param factory The factory that will make the new logger instance.\n\n */\n public\n Logger getLogger(String name, LoggerFactory factory) {\n //System.out.println(\"getInstance(\"+name+\") called.\");\n CategoryKey key = new CategoryKey(name);\n // Synchronize to prevent write conflicts. Read conflicts (in\n // getChainedLevel method) are possible only if variable\n // assignments are non-atomic.\n Logger logger;\n\n synchronized(ht) {\n Object o = ht.get(key);\n if(o == null) {\n\tlogger = factory.makeNewLoggerInstance(name);\n\tlogger.setHierarchy(this);\n\tht.put(key, logger);\n\tupdateParents(logger);\n\treturn logger;\n } else if(o instanceof Logger) {\n\treturn (Logger) o;\n } else if (o instanceof ProvisionNode) {\n\t//System.out.println(\"(\"+name+\") ht.get(this) returned ProvisionNode\");\n\tlogger = factory.makeNewLoggerInstance(name);\n\tlogger.setHierarchy(this);\n\tht.put(key, logger);\n\tupdateChildren((ProvisionNode) o, logger);\n\tupdateParents(logger);\n\treturn logger;\n }\n else {\n\t// It should be impossible to arrive here\n\treturn null; // but let's keep the compiler happy.\n }\n }\n }\n\n /**\n Returns all the currently defined categories in this hierarchy as\n an {@link java.util.Enumeration Enumeration}.\n\n

The root logger is not included in the returned\n {@link Enumeration}. */\n public\n Enumeration getCurrentLoggers() {\n // The accumlation in v is necessary because not all elements in\n // ht are Logger objects as there might be some ProvisionNodes\n // as well.\n Vector v = new Vector(ht.size());\n\n Enumeration elems = ht.elements();\n while(elems.hasMoreElements()) {\n Object o = elems.nextElement();\n if(o instanceof Logger) {\n\tv.addElement(o);\n }\n }\n return v.elements();\n }\n\n /**\n @deprecated Please use {@link #getCurrentLoggers} instead.\n */\n public\n Enumeration getCurrentCategories() {\n return getCurrentLoggers();\n }\n\n\n /**\n Get the renderer map for this hierarchy.\n */\n public\n RendererMap getRendererMap() {\n return rendererMap;\n }\n\n\n /**\n Get the root of this hierarchy.\n\n @since 0.9.0\n */\n public\n Logger getRootLogger() {\n return root;\n }\n\n /**\n This method will return true if this repository is\n disabled for level object passed as parameter and\n false otherwise. See also the {@link\n #setThreshold(Level) threshold} emthod. */\n public\n boolean isDisabled(int level) {\n return thresholdInt > level;\n }\n\n /**\n @deprecated Deprecated with no replacement.\n */\n public\n void overrideAsNeeded(String override) {\n LogLog.warn(\"The Hiearchy.overrideAsNeeded method has been deprecated.\");\n }\n\n /**\n Reset all values contained in this hierarchy instance to their\n default. This removes all appenders from all categories, sets\n the level of all non-root categories to null,\n sets their additivity flag to true and sets the level\n of the root logger to {@link Level#DEBUG DEBUG}. Moreover,\n message disabling is set its default \"off\" value.\n\n

Existing categories are not removed. They are just reset.\n\n

This method should be used sparingly and with care as it will\n block all logging until it is completed.

\n\n @since 0.8.5 */\n public\n void resetConfiguration() {\n\n getRootLogger().setLevel((Level) Level.DEBUG);\n root.setResourceBundle(null);\n setThreshold(Level.ALL);\n\n // the synchronization is needed to prevent JDK 1.2.x hashtable\n // surprises\n synchronized(ht) {\n shutdown(); // nested locks are OK\n\n Enumeration cats = getCurrentLoggers();\n while(cats.hasMoreElements()) {\n\tLogger c = (Logger) cats.nextElement();\n\tc.setLevel(null);\n\tc.setAdditivity(true);\n\tc.setResourceBundle(null);\n }\n }\n rendererMap.clear();\n throwableRenderer = null;\n }\n\n /**\n Does nothing.\n\n @deprecated Deprecated with no replacement.\n */\n public\n void setDisableOverride(String override) {\n LogLog.warn(\"The Hiearchy.setDisableOverride method has been deprecated.\");\n }\n\n\n\n /**\n Used by subclasses to add a renderer to the hierarchy passed as parameter.\n */\n public\n void setRenderer(Class renderedClass, ObjectRenderer renderer) {\n rendererMap.put(renderedClass, renderer);\n }\n\n /**\n * {@inheritDoc}\n */\n public void setThrowableRenderer(final ThrowableRenderer renderer) {\n throwableRenderer = renderer;\n }\n\n /**\n * {@inheritDoc}\n */\n public ThrowableRenderer getThrowableRenderer() {\n return throwableRenderer;\n }\n\n\n /**\n Shutting down a hierarchy will safely close and remove\n all appenders in all categories including the root logger.\n\n

Some appenders such as {@link org.apache.log4j.net.SocketAppender}\n and {@link AsyncAppender} need to be closed before the\n application exists. Otherwise, pending logging events might be\n lost.\n\n

The shutdown method is careful to close nested\n appenders before closing regular appenders. This is allows\n configurations where a regular appender is attached to a logger\n and again to a nested appender.\n\n\n @since 1.0 */\n public\n void shutdown() {\n Logger root = getRootLogger();\n\n // begin by closing nested appenders\n root.closeNestedAppenders();\n\n synchronized(ht) {\n Enumeration cats = this.getCurrentLoggers();\n while(cats.hasMoreElements()) {\n\tLogger c = (Logger) cats.nextElement();\n\tc.closeNestedAppenders();\n }\n\n // then, remove all appenders\n root.removeAllAppenders();\n cats = this.getCurrentLoggers();\n while(cats.hasMoreElements()) {\n\tLogger c = (Logger) cats.nextElement();\n\tc.removeAllAppenders();\n }\n }\n }\n\n\n /**\n This method loops through all the *potential* parents of\n 'cat'. There 3 possible cases:\n\n 1) No entry for the potential parent of 'cat' exists\n\n We create a ProvisionNode for this potential parent and insert\n 'cat' in that provision node.\n\n 2) There entry is of type Logger for the potential parent.\n\n The entry is 'cat's nearest existing parent. We update cat's\n parent field with this entry. We also break from the loop\n because updating our parent's parent is our parent's\n responsibility.\n\n 3) There entry is of type ProvisionNode for this potential parent.\n\n We add 'cat' to the list of children for this potential parent.\n */\n final\n private\n void updateParents(Logger cat) {\n String name = cat.name;\n int length = name.length();\n boolean parentFound = false;\n\n //System.out.println(\"UpdateParents called for \" + name);\n\n // if name = \"w.x.y.z\", loop thourgh \"w.x.y\", \"w.x\" and \"w\", but not \"w.x.y.z\"\n for(int i = name.lastIndexOf('.', length-1); i >= 0;\n\t i = name.lastIndexOf('.', i-1)) {\n String substr = name.substring(0, i);\n\n //System.out.println(\"Updating parent : \" + substr);\n CategoryKey key = new CategoryKey(substr); // simple constructor\n Object o = ht.get(key);\n // Create a provision node for a future parent.\n if(o == null) {\n\t//System.out.println(\"No parent \"+substr+\" found. Creating ProvisionNode.\");\n\tProvisionNode pn = new ProvisionNode(cat);\n\tht.put(key, pn);\n } else if(o instanceof Category) {\n\tparentFound = true;\n\tcat.parent = (Category) o;\n\t//System.out.println(\"Linking \" + cat.name + \" -> \" + ((Category) o).name);\n\tbreak; // no need to update the ancestors of the closest ancestor\n } else if(o instanceof ProvisionNode) {\n\t((ProvisionNode) o).addElement(cat);\n } else {\n\tException e = new IllegalStateException(\"unexpected object type \" +\n\t\t\t\t\to.getClass() + \" in ht.\");\n\te.printStackTrace();\n }\n }\n // If we could not find any existing parents, then link with root.\n if(!parentFound)\n cat.parent = root;\n }\n\n /**\n We update the links for all the children that placed themselves\n in the provision node 'pn'. The second argument 'cat' is a\n reference for the newly created Logger, parent of all the\n children in 'pn'\n\n We loop on all the children 'c' in 'pn':\n\n If the child 'c' has been already linked to a child of\n 'cat' then there is no need to update 'c'.\n\n\t Otherwise, we set cat's parent field to c's parent and set\n\t c's parent field to cat.\n\n */\n final\n private\n void updateChildren(ProvisionNode pn, Logger logger) {\n //System.out.println(\"updateChildren called for \" + logger.name);\n final int last = pn.size();\n\n for(int i = 0; i < last; i++) {\n Logger l = (Logger) pn.elementAt(i);\n //System.out.println(\"Updating child \" +p.name);\n\n // Unless this child already points to a correct (lower) parent,\n // make cat.parent point to l.parent and l.parent to cat.\n if(!l.parent.name.startsWith(logger.name)) {\n\tlogger.parent = l.parent;\n\tl.parent = logger;\n }\n }\n }\n\n}\n\n\n", "file_name": "Hierarchy.java", "human_label": "Check if the named logger exists. If so return its reference, otherwise returns null.", "level": "project_runnable", "lineno": "145", "name": "exists", "oracle_context": "{ \"apis\" : \"[get]\", \"classes\" : \"[Object]\", \"vars\" : \"[ht]\" }", "package": "org.apache.log4j", "project": "logging-log4j1-main" }, { "_id": "6367670a1a6d9265ec0179e7", "all_context": "{ \"class_level\" : \"import net.hasor.utils.convert.convert.*;\\nimport net.hasor.utils.supplier.ContextClassLoaderLocal;\\nimport java.io.File;\\nimport java.lang.reflect.Array;\\nimport java.math.BigDecimal;\\nimport java.math.BigInteger;\\nimport java.net.URI;\\nimport java.net.URL;\\nimport java.sql.Timestamp;\\nimport java.util.Calendar;\\nimport java.util.Collection;\\nInteger ZERO;\\nCharacter SPACE;\\nConverterBeanContextClassLoaderLocal BEANS_BY_CLASSLOADER;\\nWeakFastHashMap converters;\\ninitialValue();\\ngetInstance();\\nConverterBean();\\nconvert(String value,Class clazz);\\nconvert(String[] values,Class clazz);\\nconvert(T value,Class targetType);\\nderegister();\\nregister(boolean throwException,boolean defaultNull,int defaultArraySize);\\nregisterPrimitives(boolean throwException);\\nregisterStandard(boolean throwException,boolean defaultNull);\\nregisterOther(boolean throwException);\\nregisterArrays(boolean throwException,int defaultArraySize);\\nregisterArrayConverter(Class componentType,Converter componentConverter,boolean throwException,int defaultArraySize);\\nregister(Class clazz,Converter converter);\\nderegister(Class clazz);\\nlookup(Class clazz);\\nlookup(Class sourceType,Class targetType);\\nregister(Converter converter,Class clazz);\\nconvert(Object value);\\n\", \"repo_level\" : \"public interface ContextClassLoaderLocal {protected T initialValue();\\nsynchronized T get();\\nsynchronized void set(T value);\\nsynchronized void unset();\\nsynchronized void unset(ClassLoader classLoader);\\n }\\n\" }", "class_name": "ConverterBean", "code": "public Converter lookup(final Class clazz){\n Converter conv=(Converter)this.converters.get(clazz);\n if (conv != null) {\n return conv;\n }\n for ( Object regType : this.converters.keySet()) {\n if (((Class)regType).isAssignableFrom(clazz)) {\n return (Converter)this.converters.get(regType);\n }\n }\n return null;\n}\n", "docstring": "/** \n * Look up and return any registered {@link Converter} for the specifieddestination class; if there is no registered Converter, return null.\n * @param clazz Class for which to return a registered Converter\n * @return The registered {@link Converter} or null if not found\n */\n", "end_lineno": "491", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.convert;\nimport net.hasor.utils.convert.convert.*;\nimport net.hasor.utils.supplier.ContextClassLoaderLocal;\n\nimport java.io.File;\nimport java.lang.reflect.Array;\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.net.URI;\nimport java.net.URL;\nimport java.sql.Timestamp;\nimport java.util.Calendar;\nimport java.util.Collection;\n\n/**\n *

Utility methods for converting String scalar values to objects of the\n * specified Class, String arrays to arrays of the specified Class. The\n * actual {@link Converter} instance to be used can be registered for each\n * possible destination Class. Unless you override them, standard\n * {@link Converter} instances are provided for all of the following\n * destination Classes:

\n *
    \n *
  • java.lang.BigDecimal (no default value)
  • \n *
  • java.lang.BigInteger (no default value)
  • \n *
  • boolean and java.lang.Boolean (default to false)
  • \n *
  • byte and java.lang.Byte (default to zero)
  • \n *
  • char and java.lang.Character (default to a space)
  • \n *
  • java.lang.Class (no default value)
  • \n *
  • double and java.lang.Double (default to zero)
  • \n *
  • float and java.lang.Float (default to zero)
  • \n *
  • int and java.lang.Integer (default to zero)
  • \n *
  • long and java.lang.Long (default to zero)
  • \n *
  • short and java.lang.Short (default to zero)
  • \n *
  • java.lang.String (default to null)
  • \n *
  • java.io.File (no default value)
  • \n *
  • java.net.URL (no default value)
  • \n *
  • java.sql.Date (no default value)
  • \n *
  • java.sql.Time (no default value)
  • \n *
  • java.sql.Timestamp (no default value)
  • \n *
\n *\n *

For backwards compatibility, the standard Converters for primitive\n * types (and the corresponding wrapper classes) return a defined\n * default value when a conversion error occurs. If you prefer to have a\n * {@link ConversionException} thrown instead, replace the standard Converter\n * instances with instances created with the zero-arguments constructor. For\n * example, to cause the Converters for integers to throw an exception on\n * conversion errors, you could do this:

\n *
\n *   // No-args constructor gets the version that throws exceptions\n *   Converter myConverter = new net.hasor.utils.convert.convert.IntegerConverter();\n *   ConverterUtils.register(myConverter, Integer.TYPE);    // Native type\n *   ConverterUtils.register(myConverter, Integer.class);   // Wrapper class\n * 
\n *\n *

\n * Converters generally treat null input as if it were invalid\n * input, ie they return their default value if one was specified when the\n * converter was constructed, and throw an exception otherwise. If you prefer\n * nulls to be preserved for converters that are converting to objects (not\n * primitives) then register a converter as above, passing a default value of\n * null to the converter constructor (and of course registering that converter\n * only for the .class target).\n *

\n *\n *

\n * When a converter is listed above as having no default value, then that\n * converter will throw an exception when passed null or an invalid value\n * as its input. In particular, by default the BigInteger and BigDecimal\n * converters have no default (and are therefore somewhat inconsistent\n * with the other numerical converters which all have zero as their default).\n *

\n *\n *

\n * Converters that generate arrays of each of the primitive types are\n * also automatically configured (including String[]). When passed null\n * or invalid input, these return an empty array (not null). See class\n * AbstractArrayConverter for the supported input formats for these converters.\n *

\n *\n * @author Craig R. McClanahan\n * @author Ralph Schaer\n * @author Chris Audley\n * @author James Strachan\n * @version $Revision: 745079 $ $Date: 2009-02-17 14:04:10 +0000 (Tue, 17 Feb 2009) $\n * @since 1.7\n */\npublic class ConverterBean {\n private static final Integer ZERO = 0;\n private static final Character SPACE = ' ';\n /** Contains ConverterBean instances indexed by context classloader. */\n private static final ConverterBeanContextClassLoaderLocal BEANS_BY_CLASSLOADER = new ConverterBeanContextClassLoaderLocal();\n\n private static class ConverterBeanContextClassLoaderLocal extends ContextClassLoaderLocal {\n @Override\n protected ConverterBean initialValue() {\n return new ConverterBean();\n }\n }\n // ------------------------------------------------------- Class Methods\n\n /**\n * Get singleton instance\n * @return The singleton instance\n */\n protected static ConverterBean getInstance() {\n return ConverterBean.BEANS_BY_CLASSLOADER.get();\n }\n // ------------------------------------------------------- Variables\n /**\n * The set of {@link Converter}s that can be used to convert Strings\n * into objects of a specified Class, keyed by the destination Class.\n */\n private WeakFastHashMap converters = new WeakFastHashMap();\n // ------------------------------------------------------- Constructors\n\n /** Construct a bean with standard converters registered */\n public ConverterBean() {\n this.converters.setFast(false);\n this.deregister();\n this.converters.setFast(true);\n }\n // --------------------------------------------------------- Public Methods\n\n /**\n * Convert the specified value into a String. If the specified value\n * is an array, the first element (converted to a String) will be\n * returned. The registered {@link Converter} for the\n * java.lang.String class will be used, which allows\n * applications to customize Object->String conversions (the default\n * implementation simply uses toString()).\n *\n * @param value Value to be converted (may be null)\n * @return The converted String value\n */\n public String convert(Object value) {\n if (value == null) {\n return null;\n } else if (value.getClass().isArray()) {\n if (Array.getLength(value) < 1) {\n return null;\n }\n value = Array.get(value, 0);\n if (value == null) {\n return null;\n } else {\n Converter converter = this.lookup(String.class);\n return (String) converter.convert(String.class, value);\n }\n } else {\n Converter converter = this.lookup(String.class);\n return (String) converter.convert(String.class, value);\n }\n }\n\n /**\n * Convert the specified value to an object of the specified class (if\n * possible). Otherwise, return a String representation of the value.\n *\n * @param value Value to be converted (may be null)\n * @param clazz Java class to be converted to\n * @return The converted value\n *\n * @exception ConversionException if thrown by an underlying Converter\n */\n public Object convert(final String value, final Class clazz) {\n Converter converter = this.lookup(clazz);\n if (converter == null) {\n converter = this.lookup(String.class);\n }\n return converter.convert(clazz, value);\n }\n\n /**\n * Convert an array of specified values to an array of objects of the\n * specified class (if possible). If the specified Java class is itself\n * an array class, this class will be the type of the returned value.\n * Otherwise, an array will be constructed whose component type is the\n * specified class.\n *\n * @param values Array of values to be converted\n * @param clazz Java array or element class to be converted to\n * @return The converted value\n *\n * @exception ConversionException if thrown by an underlying Converter\n */\n public Object convert(final String[] values, final Class clazz) {\n Class type = clazz;\n if (clazz.isArray()) {\n type = clazz.getComponentType();\n }\n Converter converter = this.lookup(type);\n if (converter == null) {\n converter = this.lookup(String.class);\n }\n Object array = Array.newInstance(type, values.length);\n for (int i = 0; i < values.length; i++) {\n Array.set(array, i, converter.convert(type, values[i]));\n }\n return array;\n }\n\n /**\n *

Convert the value to an object of the specified class (if\n * possible).

\n *\n * @param value Value to be converted (may be null)\n * @param targetType Class of the value to be converted to\n * @return The converted value\n *\n * @exception ConversionException if thrown by an underlying Converter\n */\n public T convert(final T value, final Class targetType) {\n Class sourceType = value == null ? null : value.getClass();\n Object converted = value;\n Converter converter = this.lookup(sourceType, targetType);\n if (converter != null) {\n converted = converter.convert(targetType, value);\n }\n if (targetType == String.class && converted != null && !(converted instanceof String)) {\n // NOTE: For backwards compatibility, if the Converter\n // doesn't handle conversion-->String then\n // use the registered String Converter\n converter = this.lookup(String.class);\n if (converter != null) {\n converted = converter.convert(String.class, converted);\n }\n // If the object still isn't a String, use toString() method\n if (converted != null && !(converted instanceof String)) {\n converted = converted.toString();\n }\n }\n return (T) converted;\n }\n\n /**\n * Remove all registered {@link Converter}s, and re-establish the\n * standard Converters.\n */\n public void deregister() {\n this.converters.clear();\n this.registerPrimitives(false);\n this.registerStandard(false, false);\n this.registerOther(true);\n this.registerArrays(false, 0);\n }\n\n /**\n * Register the provided converters with the specified defaults.\n *\n * @param throwException true if the converters should\n * throw an exception when a conversion error occurs, otherwise \n * false if a default value should be used.\n * @param defaultNull trueif the standard converters\n * (see {@link ConverterBean#registerStandard(boolean, boolean)})\n * should use a default value of null, otherwise false.\n * N.B. This values is ignored if throwException is true\n * @param defaultArraySize The size of the default array value for array converters\n * (N.B. This values is ignored if throwException is true).\n * Specifying a value less than zero causes a null value to be used for\n * the default.\n */\n public void register(final boolean throwException, final boolean defaultNull, final int defaultArraySize) {\n this.registerPrimitives(throwException);\n this.registerStandard(throwException, defaultNull);\n this.registerOther(throwException);\n this.registerArrays(throwException, defaultArraySize);\n }\n\n /**\n * Register the converters for primitive types.\n *

\n * This method registers the following converters:\n *
    \n *
  • Boolean.TYPE - {@link BooleanConverter}
  • \n *
  • Byte.TYPE - {@link ByteConverter}
  • \n *
  • Character.TYPE - {@link CharacterConverter}
  • \n *
  • Double.TYPE - {@link DoubleConverter}
  • \n *
  • Float.TYPE - {@link FloatConverter}
  • \n *
  • Integer.TYPE - {@link IntegerConverter}
  • \n *
  • Long.TYPE - {@link LongConverter}
  • \n *
  • Short.TYPE - {@link ShortConverter}
  • \n *
\n * @param throwException true if the converters should\n * throw an exception when a conversion error occurs, otherwise \n * false if a default value should be used.\n */\n private void registerPrimitives(final boolean throwException) {\n this.register(Boolean.TYPE, throwException ? new BooleanConverter() : new BooleanConverter(Boolean.FALSE));\n this.register(Byte.TYPE, throwException ? new ByteConverter() : new ByteConverter(ConverterBean.ZERO));\n this.register(Character.TYPE, throwException ? new CharacterConverter() : new CharacterConverter(ConverterBean.SPACE));\n this.register(Double.TYPE, throwException ? new DoubleConverter() : new DoubleConverter(ConverterBean.ZERO));\n this.register(Float.TYPE, throwException ? new FloatConverter() : new FloatConverter(ConverterBean.ZERO));\n this.register(Integer.TYPE, throwException ? new IntegerConverter() : new IntegerConverter(ConverterBean.ZERO));\n this.register(Long.TYPE, throwException ? new LongConverter() : new LongConverter(ConverterBean.ZERO));\n this.register(Short.TYPE, throwException ? new ShortConverter() : new ShortConverter(ConverterBean.ZERO));\n }\n\n /**\n * Register the converters for standard types.\n *

\n * This method registers the following converters:\n *
    \n *
  • BigDecimal.class - {@link BigDecimalConverter}
  • \n *
  • BigInteger.class - {@link BigIntegerConverter}
  • \n *
  • Boolean.class - {@link BooleanConverter}
  • \n *
  • Byte.class - {@link ByteConverter}
  • \n *
  • Character.class - {@link CharacterConverter}
  • \n *
  • Double.class - {@link DoubleConverter}
  • \n *
  • Float.class - {@link FloatConverter}
  • \n *
  • Integer.class - {@link IntegerConverter}
  • \n *
  • Long.class - {@link LongConverter}
  • \n *
  • Short.class - {@link ShortConverter}
  • \n *
  • String.class - {@link StringConverter}
  • \n *
\n * @param throwException true if the converters should\n * throw an exception when a conversion error occurs, otherwise \n * false if a default value should be used.\n * @param defaultNull trueif the standard converters\n * (see {@link ConverterBean#registerStandard(boolean, boolean)})\n * should use a default value of null, otherwise false.\n * N.B. This values is ignored if throwException is true\n */\n private void registerStandard(final boolean throwException, final boolean defaultNull) {\n Number defaultNumber = defaultNull ? null : ConverterBean.ZERO;\n BigDecimal bigDecDeflt = defaultNull ? null : new BigDecimal(\"0.0\");\n BigInteger bigIntDeflt = defaultNull ? null : new BigInteger(\"0\");\n Boolean booleanDefault = defaultNull ? null : Boolean.FALSE;\n Character charDefault = defaultNull ? null : ConverterBean.SPACE;\n String stringDefault = defaultNull ? null : \"\";\n //\n this.register(BigDecimal.class, throwException ? new BigDecimalConverter() : new BigDecimalConverter(bigDecDeflt));\n this.register(BigInteger.class, throwException ? new BigIntegerConverter() : new BigIntegerConverter(bigIntDeflt));\n this.register(Boolean.class, throwException ? new BooleanConverter() : new BooleanConverter(booleanDefault));\n this.register(Byte.class, throwException ? new ByteConverter() : new ByteConverter(defaultNumber));\n this.register(Character.class, throwException ? new CharacterConverter() : new CharacterConverter(charDefault));\n this.register(Double.class, throwException ? new DoubleConverter() : new DoubleConverter(defaultNumber));\n this.register(Float.class, throwException ? new FloatConverter() : new FloatConverter(defaultNumber));\n this.register(Integer.class, throwException ? new IntegerConverter() : new IntegerConverter(defaultNumber));\n this.register(Long.class, throwException ? new LongConverter() : new LongConverter(defaultNumber));\n this.register(Short.class, throwException ? new ShortConverter() : new ShortConverter(defaultNumber));\n this.register(String.class, throwException ? new StringConverter() : new StringConverter(stringDefault));\n }\n\n /**\n * Register the converters for other types.\n *

\n * This method registers the following converters:\n *
    \n *
  • Class.class - {@link ClassConverter}
  • \n *
  • java.util.Date.class - {@link DateConverter}
  • \n *
  • java.util.Calendar.class - {@link CalendarConverter}
  • \n *
  • File.class - {@link FileConverter}
  • \n *
  • java.sql.Date.class - {@link SqlDateConverter}
  • \n *
  • java.sql.Time.class - {@link SqlTimeConverter}
  • \n *
  • java.sql.Timestamp.class - {@link SqlTimestampConverter}
  • \n *
  • URL.class - {@link URLConverter}
  • \n *
\n * @param throwException true if the converters should\n * throw an exception when a conversion error occurs, otherwise \n * false if a default value should be used.\n */\n private void registerOther(final boolean throwException) {\n this.register(Class.class, throwException ? new ClassConverter() : new ClassConverter(null));\n this.register(java.util.Date.class, throwException ? new DateConverter() : new DateConverter(null));\n this.register(Calendar.class, throwException ? new CalendarConverter() : new CalendarConverter(null));\n this.register(File.class, throwException ? new FileConverter() : new FileConverter(null));\n this.register(java.sql.Date.class, throwException ? new SqlDateConverter() : new SqlDateConverter(null));\n this.register(java.sql.Time.class, throwException ? new SqlTimeConverter() : new SqlTimeConverter(null));\n this.register(Timestamp.class, throwException ? new SqlTimestampConverter() : new SqlTimestampConverter(null));\n this.register(URL.class, throwException ? new URLConverter() : new URLConverter(null));\n this.register(URI.class, throwException ? new URIConverter() : new URIConverter(null));\n this.register(Enum.class, throwException ? new EnumConverter() : new EnumConverter(null));\n }\n\n /**\n * Register array converters.\n *\n * @param throwException true if the converters should\n * throw an exception when a conversion error occurs, otherwise \n * false if a default value should be used.\n * @param defaultArraySize The size of the default array value for array converters\n * (N.B. This values is ignored if throwException is true).\n * Specifying a value less than zero causes a null value to be used for\n * the default.\n */\n private void registerArrays(final boolean throwException, final int defaultArraySize) {\n // Primitives\n this.registerArrayConverter(Boolean.TYPE, new BooleanConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Byte.TYPE, new ByteConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Character.TYPE, new CharacterConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Double.TYPE, new DoubleConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Float.TYPE, new FloatConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Integer.TYPE, new IntegerConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Long.TYPE, new LongConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Short.TYPE, new ShortConverter(), throwException, defaultArraySize);\n // Standard\n this.registerArrayConverter(BigDecimal.class, new BigDecimalConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(BigInteger.class, new BigIntegerConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Boolean.class, new BooleanConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Byte.class, new ByteConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Character.class, new CharacterConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Double.class, new DoubleConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Float.class, new FloatConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Integer.class, new IntegerConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Long.class, new LongConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Short.class, new ShortConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(String.class, new StringConverter(), throwException, defaultArraySize);\n // Other\n this.registerArrayConverter(Class.class, new ClassConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(java.util.Date.class, new DateConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Calendar.class, new DateConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(File.class, new FileConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(java.sql.Date.class, new SqlDateConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(java.sql.Time.class, new SqlTimeConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(Timestamp.class, new SqlTimestampConverter(), throwException, defaultArraySize);\n this.registerArrayConverter(URL.class, new URLConverter(), throwException, defaultArraySize);\n }\n\n /**\n * Register a new ArrayConverter with the specified element delegate converter\n * that returns a default array of the specified size in the event of conversion errors.\n *\n * @param componentType The component type of the array\n * @param componentConverter The converter to delegate to for the array elements\n * @param throwException Whether a conversion exception should be thrown or a default\n * value used in the event of a conversion error\n * @param defaultArraySize The size of the default array\n */\n private void registerArrayConverter(final Class componentType, final Converter componentConverter, final boolean throwException, final int defaultArraySize) {\n Class arrayType = Array.newInstance(componentType, 0).getClass();\n Converter arrayConverter = null;\n if (throwException) {\n arrayConverter = new ArrayConverter(arrayType, componentConverter);\n } else {\n arrayConverter = new ArrayConverter(arrayType, componentConverter, defaultArraySize);\n }\n this.register(arrayType, arrayConverter);\n }\n\n /** strictly for convenience since it has same parameter order as Map.put */\n private void register(final Class clazz, final Converter converter) {\n this.register(new ConverterFacade(converter), clazz);\n }\n\n /**\n * Remove any registered {@link Converter} for the specified destination\n * Class.\n *\n * @param clazz Class for which to remove a registered Converter\n */\n public void deregister(final Class clazz) {\n this.converters.remove(clazz);\n }\n\n /**\n * Look up and return any registered {@link Converter} for the specified\n * destination class; if there is no registered Converter, return\n * null.\n *\n * @param clazz Class for which to return a registered Converter\n * @return The registered {@link Converter} or null if not found\n */\n public Converter lookup(final Class clazz) {\n Converter conv = (Converter) this.converters.get(clazz);\n if (conv != null) {\n return conv;\n }\n for (Object regType : this.converters.keySet()) {\n if (((Class) regType).isAssignableFrom(clazz)) {\n return (Converter) this.converters.get(regType);\n }\n }\n return null;\n }\n\n /**\n * Look up and return any registered {@link Converter} for the specified\n * source and destination class; if there is no registered Converter,\n * return null.\n *\n * @param sourceType Class of the value being converted\n * @param targetType Class of the value to be converted to\n * @return The registered {@link Converter} or null if not found\n */\n public Converter lookup(final Class sourceType, final Class targetType) {\n if (targetType == null) {\n throw new IllegalArgumentException(\"Target type is missing\");\n }\n if (sourceType == null) {\n return this.lookup(targetType);\n }\n Converter converter = null;\n // Convert --> String\n if (targetType == String.class) {\n converter = this.lookup(sourceType);\n if (converter == null && (sourceType.isArray() || Collection.class.isAssignableFrom(sourceType))) {\n converter = this.lookup(String[].class);\n }\n if (converter == null) {\n converter = this.lookup(String.class);\n }\n return converter;\n }\n // Convert --> String array\n if (targetType == String[].class) {\n if (sourceType.isArray() || Collection.class.isAssignableFrom(sourceType)) {\n converter = this.lookup(sourceType);\n }\n if (converter == null) {\n converter = this.lookup(String[].class);\n }\n return converter;\n }\n return this.lookup(targetType);\n }\n\n /**\n * Register a custom {@link Converter} for the specified destination\n * Class, replacing any previously registered Converter.\n *\n * @param converter Converter to be registered\n * @param clazz Destination class for conversions performed by this\n * Converter\n */\n public void register(final Converter converter, final Class clazz) {\n this.converters.put(clazz, converter);\n }\n}\n", "file_name": "ConverterBean.java", "human_label": "Check whether the specified converter exists in converters. If yes, converter is returned. If no, null is returned.", "level": "class_runnable", "lineno": "472", "name": "lookup", "oracle_context": "{ \"apis\" : \"[get, keySet, isAssignableFrom]\", \"classes\" : \"[Converter]\", \"vars\" : \"[converters]\" }", "package": "net.hasor.utils.convert", "project": "hasor-master" }, { "_id": "636767a41a6d9265ec018572", "all_context": "{ \"class_level\" : \"import java.io.DataInput;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport java.nio.ByteBuffer;\\nimport java.util.ArrayList;\\nimport java.util.List;\\nimport io.protostuff.StringSerializer.STRING;\\nimport static io.protostuff.WireFormat.TAG_TYPE_BITS;\\nimport static io.protostuff.WireFormat.TAG_TYPE_MASK;\\nimport static io.protostuff.WireFormat.WIRETYPE_END_GROUP;\\nimport static io.protostuff.WireFormat.WIRETYPE_LENGTH_DELIMITED;\\nimport static io.protostuff.WireFormat.WIRETYPE_TAIL_DELIMITER;\\nbyte[] buffer;\\nint bufferSize;\\nint bufferSizeAfterLimit;\\nint bufferPos;\\nInputStream input;\\nint lastTag;\\nint packedLimit;\\nint totalBytesRetired;\\nint currentLimit;\\nboolean decodeNestedMessageAsGroup;\\nint sizeLimit;\\nint DEFAULT_SIZE_LIMIT;\\nint DEFAULT_BUFFER_SIZE;\\nnewInstance(byte[] buf);\\nnewInstance(byte[] buf,int off,int len);\\nreadTag();\\ncheckLastTagWas(int value);\\nskipField(int tag);\\nskipMessage();\\nreadDouble();\\nreadFloat();\\nreadUInt64();\\nreadInt64();\\nreadInt32();\\nreadFixed64();\\nreadFixed32();\\nreadBool();\\nreadString();\\nreadBytes(ByteBuffer bb);\\nmergeObject(T value,Schema schema);\\nmergeObjectEncodedAsGroup(T value,Schema schema);\\nreadBytes();\\nreadUInt32();\\nreadEnum();\\nreadSFixed32();\\nreadSFixed64();\\nreadSInt32();\\nreadSInt64();\\nreadRawVarint32();\\nreadRawVarint32(InputStream input);\\nreadRawVarint32(InputStream input,int firstByte);\\nreadRawVarint32(DataInput input,byte firstByte);\\nreadRawVarint64();\\nreadRawLittleEndian32();\\nreadRawLittleEndian64();\\ndecodeZigZag32(int n);\\ndecodeZigZag64(long n);\\nCodedInput(byte[] buffer,int off,int len,boolean decodeNestedMessageAsGroup);\\nCodedInput(InputStream input,boolean decodeNestedMessageAsGroup);\\nCodedInput(InputStream input,byte[] buffer,boolean decodeNestedMessageAsGroup);\\nCodedInput(InputStream input,byte[] buffer,int offset,int limit,boolean decodeNestedMessageAsGroup);\\nsetSizeLimit(int limit);\\nresetSizeCounter();\\nreset();\\npushLimit(int byteLimit);\\nrecomputeBufferSizeAfterLimit();\\npopLimit(int oldLimit);\\ngetBytesUntilLimit();\\nisCurrentFieldPacked();\\nisAtEnd();\\ngetTotalBytesRead();\\nrefillBuffer(boolean mustSucceed);\\nreadRawByte();\\nreadRawBytes(int size);\\nskipRawBytes(int size);\\nreadFieldNumber(Schema schema);\\ncheckIfPackedField();\\nreadByteArray();\\nhandleUnknownField(int fieldNumber,Schema schema);\\ntransferByteRangeTo(Output output,boolean utf8String,int fieldNumber,boolean repeated);\\ngetLastTag();\\nreadByteBuffer();\\nnewInstance(InputStream input);\\n\", \"repo_level\" : \"\" }", "class_name": "CodedInput", "code": "public long readRawVarint64() throws IOException {\n int shift=0;\n long result=0;\n while (shift < 64) {\n final byte b=readRawByte();\n result|=(long)(b & 0x7F) << shift;\n if ((b & 0x80) == 0) {\n return result;\n }\n shift+=7;\n }\n throw ProtobufException.malformedVarint();\n}\n", "docstring": "/** \n * Read a raw Varint from the stream.\n */\n", "end_lineno": "629", "file_content": "//========================================================================\n//Copyright 2007-2009 David Yu dyuproject@gmail.com\n//------------------------------------------------------------------------\n//Licensed under the Apache License, Version 2.0 (the \"License\");\n//you may not use this file except in compliance with the License.\n//You may obtain a copy of the License at \n//http://www.apache.org/licenses/LICENSE-2.0\n//Unless required by applicable law or agreed to in writing, software\n//distributed under the License is distributed on an \"AS IS\" BASIS,\n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//See the License for the specific language governing permissions and\n//limitations under the License.\n//========================================================================\n\n// Protocol Buffers - Google's data interchange format\n// Copyright 2008 Google Inc. All rights reserved.\n// http://code.google.com/p/protobuf/\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\npackage io.protostuff;\n\nimport java.io.DataInput;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport io.protostuff.StringSerializer.STRING;\n\nimport static io.protostuff.WireFormat.TAG_TYPE_BITS;\nimport static io.protostuff.WireFormat.TAG_TYPE_MASK;\nimport static io.protostuff.WireFormat.WIRETYPE_END_GROUP;\nimport static io.protostuff.WireFormat.WIRETYPE_LENGTH_DELIMITED;\nimport static io.protostuff.WireFormat.WIRETYPE_TAIL_DELIMITER;\n\n/**\n * Reads and decodes protocol message fields.\n *

\n * This class contains two kinds of methods: methods that read specific protocol message constructs and field types\n * (e.g. {@link #readTag()} and {@link #readInt32()}) and methods that read low-level values (e.g.\n * {@link #readRawVarint32()} and {@link #readRawBytes}). If you are reading encoded protocol messages, you should use\n * the former methods, but if you are reading some other format of your own design, use the latter.\n *\n * @author kenton@google.com Kenton Varda\n * @author David Yu\n */\npublic final class CodedInput implements Input\n{\n /**\n * Create a new CodedInput wrapping the given InputStream.\n */\n public static CodedInput newInstance(final InputStream input)\n {\n return new CodedInput(input, false);\n }\n\n /**\n * Create a new CodedInput wrapping the given byte array.\n */\n public static CodedInput newInstance(final byte[] buf)\n {\n return newInstance(buf, 0, buf.length);\n }\n\n /**\n * Create a new CodedInput wrapping the given byte array slice.\n */\n public static CodedInput newInstance(final byte[] buf, final int off,\n final int len)\n {\n return new CodedInput(buf, off, len, false);\n }\n\n // -----------------------------------------------------------------\n\n /**\n * Attempt to read a field tag, returning zero if we have reached EOF. Protocol message parsers use this to read\n * tags, since a protocol message may legally end wherever a tag occurs, and zero is not a valid tag number.\n */\n public int readTag() throws IOException\n {\n if (isAtEnd())\n {\n lastTag = 0;\n return 0;\n }\n\n final int tag = readRawVarint32();\n if (tag >>> TAG_TYPE_BITS == 0)\n {\n // If we actually read zero, that's not a valid tag.\n throw ProtobufException.invalidTag();\n }\n lastTag = tag;\n return tag;\n }\n\n /**\n * Verifies that the last call to readTag() returned the given tag value. This is used to verify that a nested group\n * ended with the correct end tag.\n *\n * @throws ProtobufException\n * {@code value} does not match the last tag.\n */\n public void checkLastTagWas(final int value)\n throws ProtobufException\n {\n if (lastTag != value)\n {\n throw ProtobufException.invalidEndTag();\n }\n }\n\n /**\n * Reads and discards a single field, given its tag value.\n *\n * @return {@code false} if the tag is an endgroup tag, in which case nothing is skipped. Otherwise, returns\n * {@code true}.\n */\n public boolean skipField(final int tag) throws IOException\n {\n switch (WireFormat.getTagWireType(tag))\n {\n case WireFormat.WIRETYPE_VARINT:\n readInt32();\n return true;\n case WireFormat.WIRETYPE_FIXED64:\n readRawLittleEndian64();\n return true;\n case WireFormat.WIRETYPE_LENGTH_DELIMITED:\n skipRawBytes(readRawVarint32());\n return true;\n case WireFormat.WIRETYPE_START_GROUP:\n skipMessage();\n checkLastTagWas(WireFormat.makeTag(WireFormat.getTagFieldNumber(tag),\n WireFormat.WIRETYPE_END_GROUP));\n return true;\n case WireFormat.WIRETYPE_END_GROUP:\n return false;\n case WireFormat.WIRETYPE_FIXED32:\n readRawLittleEndian32();\n return true;\n default:\n throw ProtobufException.invalidWireType();\n }\n }\n\n /**\n * Reads and discards an entire message. This will read either until EOF or until an endgroup tag, whichever comes\n * first.\n */\n public void skipMessage() throws IOException\n {\n while (true)\n {\n final int tag = readTag();\n if (tag == 0 || !skipField(tag))\n {\n return;\n }\n }\n }\n\n // -----------------------------------------------------------------\n\n /**\n * Read a {@code double} field value from the stream.\n */\n @Override\n public double readDouble() throws IOException\n {\n checkIfPackedField();\n return Double.longBitsToDouble(readRawLittleEndian64());\n }\n\n /**\n * Read a {@code float} field value from the stream.\n */\n @Override\n public float readFloat() throws IOException\n {\n checkIfPackedField();\n return Float.intBitsToFloat(readRawLittleEndian32());\n }\n\n /**\n * Read a {@code uint64} field value from the stream.\n */\n @Override\n public long readUInt64() throws IOException\n {\n checkIfPackedField();\n return readRawVarint64();\n }\n\n /**\n * Read an {@code int64} field value from the stream.\n */\n @Override\n public long readInt64() throws IOException\n {\n checkIfPackedField();\n return readRawVarint64();\n }\n\n /**\n * Read an {@code int32} field value from the stream.\n */\n @Override\n public int readInt32() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32();\n }\n\n /**\n * Read a {@code fixed64} field value from the stream.\n */\n @Override\n public long readFixed64() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian64();\n }\n\n /**\n * Read a {@code fixed32} field value from the stream.\n */\n @Override\n public int readFixed32() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian32();\n }\n\n /**\n * Read a {@code bool} field value from the stream.\n */\n @Override\n public boolean readBool() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32() != 0;\n }\n\n /**\n * Read a {@code string} field value from the stream.\n */\n @Override\n public String readString() throws IOException\n {\n final int size = readRawVarint32();\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer, so\n // just copy directly from it.\n final String result = STRING.deser(buffer, bufferPos, size);\n bufferPos += size;\n return result;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n return STRING.deser(readRawBytes(size));\n }\n }\n\n /**\n * Read a {@code string} field value from the stream into a ByteBuffer.\n */\n @Override\n public void readBytes(final ByteBuffer bb) throws IOException\n {\n final int size = readRawVarint32();\n\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer, so\n // just copy directly from it.\n bb.limit(size);\n bb.put(buffer, bufferPos, size);\n bufferPos += size;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n bb.put(readRawBytes(size));\n }\n }\n\n @Override\n public T mergeObject(T value, final Schema schema) throws IOException\n {\n if (decodeNestedMessageAsGroup)\n return mergeObjectEncodedAsGroup(value, schema);\n\n final int length = readRawVarint32();\n // if (recursionDepth >= recursionLimit) {\n // throw ProtobufException.recursionLimitExceeded();\n // }\n final int oldLimit = pushLimit(length);\n // ++recursionDepth;\n\n if (value == null)\n {\n value = schema.newMessage();\n }\n schema.mergeFrom(this, value);\n if (!schema.isInitialized(value))\n {\n throw new UninitializedMessageException(value, schema);\n }\n checkLastTagWas(0);\n // --recursionDepth;\n popLimit(oldLimit);\n return value;\n }\n\n /**\n * Reads a message field value from the stream (using the {@code group} encoding).\n */\n private T mergeObjectEncodedAsGroup(T value, final Schema schema) throws IOException\n {\n // if (recursionDepth >= recursionLimit) {\n // throw ProtobufException.recursionLimitExceeded();\n // }\n // ++recursionDepth;\n\n if (value == null)\n {\n value = schema.newMessage();\n }\n schema.mergeFrom(this, value);\n if (!schema.isInitialized(value))\n {\n throw new UninitializedMessageException(value, schema);\n }\n // handling is in #readFieldNumber\n checkLastTagWas(0);\n // --recursionDepth;\n return value;\n }\n\n /*\n * @ Reads a {@code group} field value from the stream and merges it into the given {@link UnknownFieldSet}.\n * \n * @deprecated UnknownFieldSet.Builder now implements MessageLite.Builder, so you can just call {@link #readGroup}.\n */\n /*\n * @Deprecated public void readUnknownGroup(final int fieldNumber, final MessageLite.Builder builder) throws\n * IOException { // We know that UnknownFieldSet will ignore any ExtensionRegistry so it // is safe to pass null\n * here. (We can't call // ExtensionRegistry.getEmptyRegistry() because that would make this // class depend on\n * ExtensionRegistry, which is not part of the lite // library.) readGroup(fieldNumber, builder, null); }\n */\n\n /**\n * Read a {@code bytes} field value from the stream.\n */\n @Override\n public ByteString readBytes() throws IOException\n {\n final int size = readRawVarint32();\n if (size == 0)\n {\n return ByteString.EMPTY;\n }\n\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer, so\n // just copy directly from it.\n final ByteString result = ByteString.copyFrom(buffer, bufferPos, size);\n bufferPos += size;\n return result;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n // return ByteString.copyFrom(readRawBytes(size));\n return ByteString.wrap(readRawBytes(size));\n }\n }\n\n /**\n * Read a {@code uint32} field value from the stream.\n */\n @Override\n public int readUInt32() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32();\n }\n\n /**\n * Read an enum field value from the stream. Caller is responsible for converting the numeric value to an actual\n * enum.\n */\n @Override\n public int readEnum() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32();\n }\n\n /**\n * Read an {@code sfixed32} field value from the stream.\n */\n @Override\n public int readSFixed32() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian32();\n }\n\n /**\n * Read an {@code sfixed64} field value from the stream.\n */\n @Override\n public long readSFixed64() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian64();\n }\n\n /**\n * Read an {@code sint32} field value from the stream.\n */\n @Override\n public int readSInt32() throws IOException\n {\n checkIfPackedField();\n return decodeZigZag32(readRawVarint32());\n }\n\n /**\n * Read an {@code sint64} field value from the stream.\n */\n @Override\n public long readSInt64() throws IOException\n {\n checkIfPackedField();\n return decodeZigZag64(readRawVarint64());\n }\n\n // =================================================================\n\n /**\n * Read a raw Varint from the stream. If larger than 32 bits, discard the upper bits.\n */\n public int readRawVarint32() throws IOException\n {\n byte tmp = readRawByte();\n if (tmp >= 0)\n {\n return tmp;\n }\n int result = tmp & 0x7f;\n if ((tmp = readRawByte()) >= 0)\n {\n result |= tmp << 7;\n }\n else\n {\n result |= (tmp & 0x7f) << 7;\n if ((tmp = readRawByte()) >= 0)\n {\n result |= tmp << 14;\n }\n else\n {\n result |= (tmp & 0x7f) << 14;\n if ((tmp = readRawByte()) >= 0)\n {\n result |= tmp << 21;\n }\n else\n {\n result |= (tmp & 0x7f) << 21;\n result |= (tmp = readRawByte()) << 28;\n if (tmp < 0)\n {\n // Discard upper 32 bits.\n for (int i = 0; i < 5; i++)\n {\n if (readRawByte() >= 0)\n {\n return result;\n }\n }\n throw ProtobufException.malformedVarint();\n }\n }\n }\n }\n return result;\n }\n\n /**\n * Reads a varint from the input one byte at a time, so that it does not read any bytes after the end of the varint.\n * If you simply wrapped the stream in a CodedInput and used {@link #readRawVarint32(InputStream)} then you would\n * probably end up reading past the end of the varint since CodedInput buffers its input.\n */\n static int readRawVarint32(final InputStream input) throws IOException\n {\n final int firstByte = input.read();\n if (firstByte == -1)\n {\n throw ProtobufException.truncatedMessage();\n }\n\n if ((firstByte & 0x80) == 0)\n {\n return firstByte;\n }\n return readRawVarint32(input, firstByte);\n }\n\n /**\n * Reads a varint from the input one byte at a time, so that it does not read any bytes after the end of the varint.\n * If you simply wrapped the stream in a CodedInput and used {@link #readRawVarint32(InputStream)} then you would\n * probably end up reading past the end of the varint since CodedInput buffers its input.\n */\n static int readRawVarint32(final InputStream input, final int firstByte) throws IOException\n {\n int result = firstByte & 0x7f;\n int offset = 7;\n for (; offset < 32; offset += 7)\n {\n final int b = input.read();\n if (b == -1)\n {\n throw ProtobufException.truncatedMessage();\n }\n result |= (b & 0x7f) << offset;\n if ((b & 0x80) == 0)\n {\n return result;\n }\n }\n // Keep reading up to 64 bits.\n for (; offset < 64; offset += 7)\n {\n final int b = input.read();\n if (b == -1)\n {\n throw ProtobufException.truncatedMessage();\n }\n if ((b & 0x80) == 0)\n {\n return result;\n }\n }\n throw ProtobufException.malformedVarint();\n }\n\n /**\n * Reads a varint from the input one byte at a time from a {@link DataInput}, so that it does not read any bytes\n * after the end of the varint.\n */\n static int readRawVarint32(final DataInput input, final byte firstByte) throws IOException\n {\n int result = firstByte & 0x7f;\n int offset = 7;\n for (; offset < 32; offset += 7)\n {\n final byte b = input.readByte();\n result |= (b & 0x7f) << offset;\n if ((b & 0x80) == 0)\n {\n return result;\n }\n }\n // Keep reading up to 64 bits.\n for (; offset < 64; offset += 7)\n {\n final byte b = input.readByte();\n if ((b & 0x80) == 0)\n {\n return result;\n }\n }\n throw ProtobufException.malformedVarint();\n }\n\n /**\n * Read a raw Varint from the stream.\n */\n public long readRawVarint64() throws IOException\n {\n int shift = 0;\n long result = 0;\n while (shift < 64)\n {\n final byte b = readRawByte();\n result |= (long) (b & 0x7F) << shift;\n if ((b & 0x80) == 0)\n {\n return result;\n }\n shift += 7;\n }\n throw ProtobufException.malformedVarint();\n }\n\n /**\n * Read a 32-bit little-endian integer from the stream.\n */\n public int readRawLittleEndian32() throws IOException\n {\n final byte b1 = readRawByte();\n final byte b2 = readRawByte();\n final byte b3 = readRawByte();\n final byte b4 = readRawByte();\n return (((int) b1 & 0xff)) |\n (((int) b2 & 0xff) << 8) |\n (((int) b3 & 0xff) << 16) |\n (((int) b4 & 0xff) << 24);\n }\n\n /**\n * Read a 64-bit little-endian integer from the stream.\n */\n public long readRawLittleEndian64() throws IOException\n {\n final byte b1 = readRawByte();\n final byte b2 = readRawByte();\n final byte b3 = readRawByte();\n final byte b4 = readRawByte();\n final byte b5 = readRawByte();\n final byte b6 = readRawByte();\n final byte b7 = readRawByte();\n final byte b8 = readRawByte();\n return (((long) b1 & 0xff)) |\n (((long) b2 & 0xff) << 8) |\n (((long) b3 & 0xff) << 16) |\n (((long) b4 & 0xff) << 24) |\n (((long) b5 & 0xff) << 32) |\n (((long) b6 & 0xff) << 40) |\n (((long) b7 & 0xff) << 48) |\n (((long) b8 & 0xff) << 56);\n }\n\n /**\n * Decode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers into values that can be efficiently encoded\n * with varint. (Otherwise, negative values must be sign-extended to 64 bits to be varint encoded, thus always\n * taking 10 bytes on the wire.)\n *\n * @param n\n * An unsigned 32-bit integer, stored in a signed int because Java has no explicit unsigned support.\n * @return A signed 32-bit integer.\n */\n public static int decodeZigZag32(final int n)\n {\n return (n >>> 1) ^ -(n & 1);\n }\n\n /**\n * Decode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers into values that can be efficiently encoded\n * with varint. (Otherwise, negative values must be sign-extended to 64 bits to be varint encoded, thus always\n * taking 10 bytes on the wire.)\n *\n * @param n\n * An unsigned 64-bit integer, stored in a signed int because Java has no explicit unsigned support.\n * @return A signed 64-bit integer.\n */\n public static long decodeZigZag64(final long n)\n {\n return (n >>> 1) ^ -(n & 1);\n }\n\n // -----------------------------------------------------------------\n\n private final byte[] buffer;\n private int bufferSize;\n private int bufferSizeAfterLimit;\n private int bufferPos;\n private final InputStream input;\n private int lastTag;\n private int packedLimit = 0;\n\n /**\n * The total number of bytes read before the current buffer. The total bytes read up to the current position can be\n * computed as {@code totalBytesRetired + bufferPos}. This value may be negative if reading started in the middle of\n * the current buffer (e.g. if the constructor that takes a byte array and an offset was used).\n */\n private int totalBytesRetired;\n\n /**\n * The absolute position of the end of the current message.\n */\n private int currentLimit = Integer.MAX_VALUE;\n\n // ** See setRecursionLimit() */\n // private int recursionDepth;\n // private int recursionLimit = DEFAULT_RECURSION_LIMIT;\n\n /**\n * If true, the nested messages are group-encoded\n */\n public final boolean decodeNestedMessageAsGroup;\n\n /**\n * See setSizeLimit()\n */\n private int sizeLimit = DEFAULT_SIZE_LIMIT;\n\n // static final int DEFAULT_RECURSION_LIMIT = 64;\n static final int DEFAULT_SIZE_LIMIT = 64 << 20; // 64MB\n static final int DEFAULT_BUFFER_SIZE = 4096;\n\n public CodedInput(final byte[] buffer, final int off, final int len,\n boolean decodeNestedMessageAsGroup)\n {\n this.buffer = buffer;\n bufferSize = off + len;\n bufferPos = off;\n totalBytesRetired = -off;\n input = null;\n this.decodeNestedMessageAsGroup = decodeNestedMessageAsGroup;\n }\n\n public CodedInput(final InputStream input, boolean decodeNestedMessageAsGroup)\n {\n this(input, new byte[DEFAULT_BUFFER_SIZE], 0, 0, decodeNestedMessageAsGroup);\n }\n\n public CodedInput(final InputStream input, byte[] buffer,\n boolean decodeNestedMessageAsGroup)\n {\n this(input, buffer, 0, 0, decodeNestedMessageAsGroup);\n }\n\n public CodedInput(final InputStream input, byte[] buffer, int offset, int limit,\n boolean decodeNestedMessageAsGroup)\n {\n this.buffer = buffer;\n bufferSize = limit;\n bufferPos = offset;\n totalBytesRetired = -offset;\n this.input = input;\n this.decodeNestedMessageAsGroup = decodeNestedMessageAsGroup;\n }\n\n /*\n * Set the maximum message recursion depth. In order to prevent malicious messages from causing stack overflows,\n * {@code CodedInput} limits how deeply messages may be nested. The default limit is 64.\n * \n * @return the old limit.\n * \n * public int setRecursionLimit(final int limit) { if (limit < 0) { throw new IllegalArgumentException(\n * \"Recursion limit cannot be negative: \" + limit); } final int oldLimit = recursionLimit; recursionLimit = limit;\n * return oldLimit; }\n */\n\n /**\n * Set the maximum message size. In order to prevent malicious messages from exhausting memory or causing integer\n * overflows, {@code CodedInput} limits how large a message may be. The default limit is 64MB. You should set this\n * limit as small as you can without harming your app's functionality. Note that size limits only apply when reading\n * from an {@code InputStream}, not when constructed around a raw byte array.\n *

\n * If you want to read several messages from a single CodedInput, you could call {@link #resetSizeCounter()} after\n * each one to avoid hitting the size limit.\n *\n * @return the old limit.\n */\n public int setSizeLimit(final int limit)\n {\n if (limit < 0)\n {\n throw new IllegalArgumentException(\n \"Size limit cannot be negative: \" + limit);\n }\n final int oldLimit = sizeLimit;\n sizeLimit = limit;\n return oldLimit;\n }\n\n /**\n * Resets the current size counter to zero (see {@link #setSizeLimit(int)}). The field {@code totalBytesRetired}\n * will be negative if the initial position was not zero.\n */\n public void resetSizeCounter()\n {\n totalBytesRetired = -bufferPos;\n }\n\n /**\n * Resets the buffer position and limit to re-use this CodedInput object.\n */\n public void reset()\n {\n this.bufferSize = 0;\n this.bufferPos = 0;\n this.bufferSizeAfterLimit = 0;\n this.currentLimit = Integer.MAX_VALUE;\n this.lastTag = 0;\n this.packedLimit = 0;\n this.sizeLimit = DEFAULT_SIZE_LIMIT;\n resetSizeCounter();\n }\n\n /**\n * Note that {@code pushLimit()} does NOT affect how many bytes the {@code CodedInputStream} reads from an\n * underlying {@code InputStream} when refreshing its buffer. If you need to prevent reading past a certain point in\n * the underlying {@code InputStream} (e.g. because you expect it to contain more data after the end of the message\n * which you need to handle differently) then you must place a wrapper around your {@code InputStream} which limits\n * the amount of data that can be read from it.\n *\n * @return the old limit.\n */\n public int pushLimit(int byteLimit) throws ProtobufException\n {\n if (byteLimit < 0)\n {\n throw ProtobufException.negativeSize();\n }\n byteLimit += totalBytesRetired + bufferPos;\n final int oldLimit = currentLimit;\n if (byteLimit > oldLimit)\n {\n throw ProtobufException.truncatedMessage();\n }\n currentLimit = byteLimit;\n\n recomputeBufferSizeAfterLimit();\n\n return oldLimit;\n }\n\n private void recomputeBufferSizeAfterLimit()\n {\n bufferSize += bufferSizeAfterLimit;\n final int bufferEnd = totalBytesRetired + bufferSize;\n if (bufferEnd > currentLimit)\n {\n // Limit is in current buffer.\n bufferSizeAfterLimit = bufferEnd - currentLimit;\n bufferSize -= bufferSizeAfterLimit;\n }\n else\n {\n bufferSizeAfterLimit = 0;\n }\n }\n\n /**\n * Discards the current limit, returning to the previous limit.\n *\n * @param oldLimit\n * The old limit, as returned by {@code pushLimit}.\n */\n public void popLimit(final int oldLimit)\n {\n currentLimit = oldLimit;\n recomputeBufferSizeAfterLimit();\n }\n\n /**\n * Returns the number of bytes to be read before the current limit. If no limit is set, returns -1.\n */\n public int getBytesUntilLimit()\n {\n if (currentLimit == Integer.MAX_VALUE)\n {\n return -1;\n }\n\n final int currentAbsolutePosition = totalBytesRetired + bufferPos;\n return currentLimit - currentAbsolutePosition;\n }\n\n /**\n * Return true if currently reading packed field\n */\n public boolean isCurrentFieldPacked()\n {\n return packedLimit != 0 && packedLimit != getTotalBytesRead();\n }\n\n /**\n * Returns true if the stream has reached the end of the input. This is the case if either the end of the underlying\n * input source has been reached or if the stream has reached a limit created using {@link #pushLimit(int)}.\n */\n public boolean isAtEnd() throws IOException\n {\n return bufferPos == bufferSize && !refillBuffer(false);\n }\n\n /**\n * The total bytes read up to the current position. Calling {@link #resetSizeCounter()} resets this value to zero.\n */\n public int getTotalBytesRead()\n {\n return totalBytesRetired + bufferPos;\n }\n\n /**\n * Called with {@code this.buffer} is empty to read more bytes from the input. If {@code mustSucceed} is true,\n * refillBuffer() guarantees that either there will be at least one byte in the buffer when it returns or it will\n * throw an exception. If {@code mustSucceed} is false, refillBuffer() returns false if no more bytes were\n * available.\n */\n private boolean refillBuffer(final boolean mustSucceed) throws IOException\n {\n if (bufferPos < bufferSize)\n {\n throw new IllegalStateException(\n \"refillBuffer() called when buffer wasn't empty.\");\n }\n\n if (totalBytesRetired + bufferSize == currentLimit)\n {\n // Oops, we hit a limit.\n if (mustSucceed)\n {\n throw ProtobufException.truncatedMessage();\n }\n else\n {\n return false;\n }\n }\n\n totalBytesRetired += bufferSize;\n\n bufferPos = 0;\n bufferSize = (input == null) ? -1 : input.read(buffer);\n if (bufferSize == 0 || bufferSize < -1)\n {\n throw new IllegalStateException(\n \"InputStream#read(byte[]) returned invalid result: \" + bufferSize +\n \"\\nThe InputStream implementation is buggy.\");\n }\n if (bufferSize == -1)\n {\n bufferSize = 0;\n if (mustSucceed)\n {\n throw ProtobufException.truncatedMessage();\n }\n else\n {\n return false;\n }\n }\n else\n {\n recomputeBufferSizeAfterLimit();\n final int totalBytesRead =\n totalBytesRetired + bufferSize + bufferSizeAfterLimit;\n if (totalBytesRead > sizeLimit || totalBytesRead < 0)\n {\n throw ProtobufException.sizeLimitExceeded();\n }\n return true;\n }\n }\n\n /**\n * Read one byte from the input.\n *\n * @throws ProtobufException\n * The end of the stream or the current limit was reached.\n */\n public byte readRawByte() throws IOException\n {\n if (bufferPos == bufferSize)\n {\n refillBuffer(true);\n }\n return buffer[bufferPos++];\n }\n\n /**\n * Read a fixed size of bytes from the input.\n *\n * @throws ProtobufException\n * The end of the stream or the current limit was reached.\n */\n public byte[] readRawBytes(final int size) throws IOException\n {\n if (size < 0)\n {\n throw ProtobufException.negativeSize();\n }\n\n if (totalBytesRetired + bufferPos + size > currentLimit)\n {\n // Read to the end of the stream anyway.\n skipRawBytes(currentLimit - totalBytesRetired - bufferPos);\n // Then fail.\n throw ProtobufException.truncatedMessage();\n }\n\n if (size <= bufferSize - bufferPos)\n {\n // We have all the bytes we need already.\n final byte[] bytes = new byte[size];\n System.arraycopy(buffer, bufferPos, bytes, 0, size);\n bufferPos += size;\n return bytes;\n }\n else if (size < buffer.length)\n {\n // Reading more bytes than are in the buffer, but not an excessive number\n // of bytes. We can safely allocate the resulting array ahead of time.\n\n // First copy what we have.\n final byte[] bytes = new byte[size];\n int pos = bufferSize - bufferPos;\n System.arraycopy(buffer, bufferPos, bytes, 0, pos);\n bufferPos = bufferSize;\n\n // We want to use refillBuffer() and then copy from the buffer into our\n // byte array rather than reading directly into our byte array because\n // the input may be unbuffered.\n refillBuffer(true);\n\n while (size - pos > bufferSize)\n {\n System.arraycopy(buffer, 0, bytes, pos, bufferSize);\n pos += bufferSize;\n bufferPos = bufferSize;\n refillBuffer(true);\n }\n\n System.arraycopy(buffer, 0, bytes, pos, size - pos);\n bufferPos = size - pos;\n\n return bytes;\n }\n else\n {\n // The size is very large. For security reasons, we can't allocate the\n // entire byte array yet. The size comes directly from the input, so a\n // maliciously-crafted message could provide a bogus very large size in\n // order to trick the app into allocating a lot of memory. We avoid this\n // by allocating and reading only a small chunk at a time, so that the\n // malicious message must actually *be* extremely large to cause\n // problems. Meanwhile, we limit the allowed size of a message elsewhere.\n\n // Remember the buffer markers since we'll have to copy the bytes out of\n // it later.\n final int originalBufferPos = bufferPos;\n final int originalBufferSize = bufferSize;\n\n // Mark the current buffer consumed.\n totalBytesRetired += bufferSize;\n bufferPos = 0;\n bufferSize = 0;\n\n // Read all the rest of the bytes we need.\n int sizeLeft = size - (originalBufferSize - originalBufferPos);\n final List chunks = new ArrayList();\n\n while (sizeLeft > 0)\n {\n final byte[] chunk = new byte[Math.min(sizeLeft, buffer.length)];\n int pos = 0;\n while (pos < chunk.length)\n {\n final int n = (input == null) ? -1 :\n input.read(chunk, pos, chunk.length - pos);\n if (n == -1)\n {\n throw ProtobufException.truncatedMessage();\n }\n totalBytesRetired += n;\n pos += n;\n }\n sizeLeft -= chunk.length;\n chunks.add(chunk);\n }\n\n // OK, got everything. Now concatenate it all into one buffer.\n final byte[] bytes = new byte[size];\n\n // Start by copying the leftover bytes from this.buffer.\n int pos = originalBufferSize - originalBufferPos;\n System.arraycopy(buffer, originalBufferPos, bytes, 0, pos);\n\n // And now all the chunks.\n for (final byte[] chunk : chunks)\n {\n System.arraycopy(chunk, 0, bytes, pos, chunk.length);\n pos += chunk.length;\n }\n\n // Done.\n return bytes;\n }\n }\n\n /**\n * Reads and discards {@code size} bytes.\n *\n * @throws ProtobufException\n * The end of the stream or the current limit was reached.\n */\n public void skipRawBytes(final int size) throws IOException\n {\n if (size < 0)\n {\n throw ProtobufException.negativeSize();\n }\n\n if (totalBytesRetired + bufferPos + size > currentLimit)\n {\n // Read to the end of the stream anyway.\n skipRawBytes(currentLimit - totalBytesRetired - bufferPos);\n // Then fail.\n throw ProtobufException.truncatedMessage();\n }\n\n if (size <= bufferSize - bufferPos)\n {\n // We have all the bytes we need already.\n bufferPos += size;\n }\n else\n {\n // Skipping more bytes than are in the buffer. First skip what we have.\n int pos = bufferSize - bufferPos;\n bufferPos = bufferSize;\n\n // Keep refilling the buffer until we get to the point we wanted to skip\n // to. This has the side effect of ensuring the limits are updated\n // correctly.\n refillBuffer(true);\n while (size - pos > bufferSize)\n {\n pos += bufferSize;\n bufferPos = bufferSize;\n refillBuffer(true);\n }\n\n bufferPos = size - pos;\n }\n }\n\n // START EXTRA\n @Override\n public int readFieldNumber(Schema schema) throws IOException\n {\n if (isAtEnd())\n {\n lastTag = 0;\n return 0;\n }\n\n // are we reading packed field?\n if (isCurrentFieldPacked())\n {\n if (packedLimit < getTotalBytesRead())\n throw ProtobufException.misreportedSize();\n\n // Return field number while reading packed field\n return lastTag >>> TAG_TYPE_BITS;\n }\n\n packedLimit = 0;\n final int tag = readRawVarint32();\n final int fieldNumber = tag >>> TAG_TYPE_BITS;\n if (fieldNumber == 0)\n {\n if (decodeNestedMessageAsGroup && WIRETYPE_TAIL_DELIMITER == (tag & TAG_TYPE_MASK))\n {\n // protostuff's tail delimiter for streaming\n // 2 options: length-delimited or tail-delimited.\n lastTag = 0;\n return 0;\n }\n // If we actually read zero, that's not a valid tag.\n throw ProtobufException.invalidTag();\n }\n if (decodeNestedMessageAsGroup && WIRETYPE_END_GROUP == (tag & TAG_TYPE_MASK))\n {\n lastTag = 0;\n return 0;\n }\n\n lastTag = tag;\n return fieldNumber;\n }\n\n /**\n * Check if this field have been packed into a length-delimited field. If so, update internal state to reflect that\n * packed fields are being read.\n *\n * @throws IOException\n */\n private void checkIfPackedField() throws IOException\n {\n // Do we have the start of a packed field?\n if (packedLimit == 0 && WireFormat.getTagWireType(lastTag) == WIRETYPE_LENGTH_DELIMITED)\n {\n final int length = readRawVarint32();\n if (length < 0)\n throw ProtobufException.negativeSize();\n\n this.packedLimit = getTotalBytesRead() + length;\n }\n }\n\n @Override\n public byte[] readByteArray() throws IOException\n {\n final int size = readRawVarint32();\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer, so\n // just copy directly from it.\n final byte[] copy = new byte[size];\n System.arraycopy(buffer, bufferPos, copy, 0, size);\n bufferPos += size;\n return copy;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n return readRawBytes(size);\n }\n }\n\n @Override\n public void handleUnknownField(int fieldNumber, Schema schema) throws IOException\n {\n skipField(lastTag);\n }\n\n @Override\n public void transferByteRangeTo(Output output, boolean utf8String, int fieldNumber,\n boolean repeated) throws IOException\n {\n final int size = readRawVarint32();\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer\n output.writeByteRange(utf8String, fieldNumber, buffer, bufferPos, size, repeated);\n bufferPos += size;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n output.writeByteRange(utf8String, fieldNumber, readRawBytes(size), 0, size, repeated);\n }\n }\n\n /**\n * Returns the last tag.\n */\n public int getLastTag()\n {\n return lastTag;\n }\n\n /**\n * Reads a byte array/ByteBuffer value.\n */\n @Override\n public ByteBuffer readByteBuffer() throws IOException\n {\n return ByteBuffer.wrap(readByteArray());\n }\n\n // END EXTRA\n}\n", "file_name": "CodedInput.java", "human_label": "Read raw varint", "level": "class_runnable", "lineno": "611", "name": "readRawVarint64", "oracle_context": "{ \"apis\" : \"[readRawByte, malformedVarint]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "io.protostuff", "project": "protostuff-master" }, { "_id": "636767021a6d9265ec0178bb", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static Double[] nullToEmpty(final Double[] array){\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n}\n", "docstring": "/** \n *

Defensive programming technique to change a null reference to an empty one.

This method returns an empty array for a null input array.

As a memory optimizing technique an empty array passed in will be overridden with the empty public static references in this class.

\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n", "end_lineno": "637", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

\n *\n *

This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

\n *\n *

#ThreadSafe#

\n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

\n *\n *

This method can be used to initialize:

\n *
\n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
\n *\n *

This method returns null for a null input array.

\n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

Shallow clones an array returning a typecast result and handling\n * null.

\n *\n *

The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

Produces a new array containing the elements between\n * the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n *

The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

\n *\n *
\n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new long array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new int array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new short array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new char array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new byte array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new double array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new float array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new boolean array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

Any multi-dimensional aspects of the arrays are ignored.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

\n *\n *

If the input array is null, 0 is returned.

\n *\n *
\n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
\n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

\n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

Reverses the order of the given array.

\n *\n *

There is no special handling for multi-dimensional arrays.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given object in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

Finds the index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given object within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the object is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

\n *\n *

The method returns false if a null array\n * is passed in.

\n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Characters to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Character to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive chars to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Longs to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Long to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive longs to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Integers to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Integer to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive ints to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Shorts to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Short to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive shorts to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Bytes to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Bytes to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive bytes to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Doubles to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Doubles to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive doubles to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Floats to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Floats to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive floats to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Booleans to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Booleans to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive booleans to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive longs is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive ints is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive chars is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive floats is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive longs is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive ints is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive chars is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive floats is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

\n *\n *
\n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "If the double type array is null or its length is 0, convert array to EMPTY_CHARACTER_OBJECT_ARRAY. Otherwise, return array itself.", "level": "self_contained", "lineno": "619", "name": "nullToEmpty", "oracle_context": "{ \"apis\" : \"[ArrayUtils]\", \"classes\" : \"[ArrayUtils]\", \"vars\" : \"[length, EMPTY_DOUBLE_OBJECT_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636767021a6d9265ec0178b2", "all_context": "{ \"class_level\" : \"int SAME_FRAME;\\nint SAME_LOCALS_1_STACK_ITEM_FRAME;\\nint RESERVED;\\nint SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED;\\nint CHOP_FRAME;\\nint SAME_FRAME_EXTENDED;\\nint APPEND_FRAME;\\nint FULL_FRAME;\\nint ITEM_TOP;\\nint ITEM_INTEGER;\\nint ITEM_FLOAT;\\nint ITEM_DOUBLE;\\nint ITEM_LONG;\\nint ITEM_NULL;\\nint ITEM_UNINITIALIZED_THIS;\\nint ITEM_OBJECT;\\nint ITEM_UNINITIALIZED;\\nint ITEM_ASM_BOOLEAN;\\nint ITEM_ASM_BYTE;\\nint ITEM_ASM_CHAR;\\nint ITEM_ASM_SHORT;\\nint DIM_SIZE;\\nint KIND_SIZE;\\nint FLAGS_SIZE;\\nint VALUE_SIZE;\\nint DIM_SHIFT;\\nint KIND_SHIFT;\\nint FLAGS_SHIFT;\\nint DIM_MASK;\\nint KIND_MASK;\\nint VALUE_MASK;\\nint ARRAY_OF;\\nint ELEMENT_OF;\\nint CONSTANT_KIND;\\nint REFERENCE_KIND;\\nint UNINITIALIZED_KIND;\\nint LOCAL_KIND;\\nint STACK_KIND;\\nint TOP_IF_LONG_OR_DOUBLE_FLAG;\\nint TOP;\\nint BOOLEAN;\\nint BYTE;\\nint CHAR;\\nint SHORT;\\nint INTEGER;\\nint FLOAT;\\nint LONG;\\nint DOUBLE;\\nint NULL;\\nint UNINITIALIZED_THIS;\\nLabel owner;\\nint[] inputLocals;\\nint[] inputStack;\\nint[] outputLocals;\\nint[] outputStack;\\nshort outputStackStart;\\nshort outputStackTop;\\nint initializationCount;\\nint[] initializations;\\nFrame(Label owner);\\ngetAbstractTypeFromApiFormat(SymbolTable symbolTable,Object type);\\ngetAbstractTypeFromInternalName(SymbolTable symbolTable,String internalName);\\ngetAbstractTypeFromDescriptor(SymbolTable symbolTable,String buffer,int offset);\\nsetInputFrameFromDescriptor(SymbolTable symbolTable,int access,String descriptor,int maxLocals);\\nsetInputFrameFromApiFormat(SymbolTable symbolTable,int numLocal,Object[] local,int numStack,Object[] stack);\\ngetInputStackSize();\\ngetLocal(int localIndex);\\nsetLocal(int localIndex,int abstractType);\\npush(int abstractType);\\npush(SymbolTable symbolTable,String descriptor);\\npop();\\npop(int elements);\\npop(String descriptor);\\naddInitializedType(int abstractType);\\ngetInitializedType(SymbolTable symbolTable,int abstractType);\\nexecute(int opcode,int arg,Symbol argSymbol,SymbolTable symbolTable);\\ngetConcreteOutputType(int abstractOutputType,int numStack);\\nmerge(SymbolTable symbolTable,Frame dstFrame,int catchTypeIndex);\\nmerge(SymbolTable symbolTable,int sourceType,int[] dstTypes,int dstIndex);\\naccept(MethodWriter methodWriter);\\nputAbstractType(SymbolTable symbolTable,int abstractType,ByteVector output);\\ncopyFrom(Frame frame);\\n\", \"repo_level\" : \"\" }", "class_name": "Frame", "code": "private void pop(final String descriptor){\n char firstDescriptorChar=descriptor.charAt(0);\n if (firstDescriptorChar == '(') {\n pop((Type.getArgumentsAndReturnSizes(descriptor) >> 2) - 1);\n }\n else if (firstDescriptorChar == 'J' || firstDescriptorChar == 'D') {\n pop(2);\n }\n else {\n pop(1);\n }\n}\n", "docstring": "/** \n * Pops as many abstract types from the output frame stack as described by the given descriptor.\n * @param descriptor a type or method descriptor (in which case its argument types are popped).\n */\n", "end_lineno": "558", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage net.hasor.utils.asm;\n/**\n * The input and output stack map frames of a basic block.\n *\n *

Stack map frames are computed in two steps:\n *\n *

    \n *
  • During the visit of each instruction in MethodWriter, the state of the frame at the end of\n * the current basic block is updated by simulating the action of the instruction on the\n * previous state of this so called \"output frame\".\n *
  • After all instructions have been visited, a fix point algorithm is used in MethodWriter to\n * compute the \"input frame\" of each basic block (i.e. the stack map frame at the beginning of\n * the basic block). See {@link MethodWriter#computeAllFrames}.\n *
\n *\n *

Output stack map frames are computed relatively to the input frame of the basic block, which\n * is not yet known when output frames are computed. It is therefore necessary to be able to\n * represent abstract types such as \"the type at position x in the input frame locals\" or \"the type\n * at position x from the top of the input frame stack\" or even \"the type at position x in the input\n * frame, with y more (or less) array dimensions\". This explains the rather complicated type format\n * used in this class, explained below.\n *\n *

The local variables and the operand stack of input and output frames contain values called\n * \"abstract types\" hereafter. An abstract type is represented with 4 fields named DIM, KIND, FLAGS\n * and VALUE, packed in a single int value for better performance and memory efficiency:\n *\n *

\n *   =====================================\n *   |...DIM|KIND|.F|...............VALUE|\n *   =====================================\n * 
\n *\n *
    \n *
  • the DIM field, stored in the 6 most significant bits, is a signed number of array\n * dimensions (from -32 to 31, included). It can be retrieved with {@link #DIM_MASK} and a\n * right shift of {@link #DIM_SHIFT}.\n *
  • the KIND field, stored in 4 bits, indicates the kind of VALUE used. These 4 bits can be\n * retrieved with {@link #KIND_MASK} and, without any shift, must be equal to {@link\n * #CONSTANT_KIND}, {@link #REFERENCE_KIND}, {@link #UNINITIALIZED_KIND}, {@link #LOCAL_KIND}\n * or {@link #STACK_KIND}.\n *
  • the FLAGS field, stored in 2 bits, contains up to 2 boolean flags. Currently only one flag\n * is defined, namely {@link #TOP_IF_LONG_OR_DOUBLE_FLAG}.\n *
  • the VALUE field, stored in the remaining 20 bits, contains either\n *
      \n *
    • one of the constants {@link #ITEM_TOP}, {@link #ITEM_ASM_BOOLEAN}, {@link\n * #ITEM_ASM_BYTE}, {@link #ITEM_ASM_CHAR} or {@link #ITEM_ASM_SHORT}, {@link\n * #ITEM_INTEGER}, {@link #ITEM_FLOAT}, {@link #ITEM_LONG}, {@link #ITEM_DOUBLE}, {@link\n * #ITEM_NULL} or {@link #ITEM_UNINITIALIZED_THIS}, if KIND is equal to {@link\n * #CONSTANT_KIND}.\n *
    • the index of a {@link Symbol#TYPE_TAG} {@link Symbol} in the type table of a {@link\n * SymbolTable}, if KIND is equal to {@link #REFERENCE_KIND}.\n *
    • the index of an {@link Symbol#UNINITIALIZED_TYPE_TAG} {@link Symbol} in the type\n * table of a SymbolTable, if KIND is equal to {@link #UNINITIALIZED_KIND}.\n *
    • the index of a local variable in the input stack frame, if KIND is equal to {@link\n * #LOCAL_KIND}.\n *
    • a position relatively to the top of the stack of the input stack frame, if KIND is\n * equal to {@link #STACK_KIND},\n *
    \n *
\n *\n *

Output frames can contain abstract types of any kind and with a positive or negative array\n * dimension (and even unassigned types, represented by 0 - which does not correspond to any valid\n * abstract type value). Input frames can only contain CONSTANT_KIND, REFERENCE_KIND or\n * UNINITIALIZED_KIND abstract types of positive or {@literal null} array dimension. In all cases\n * the type table contains only internal type names (array type descriptors are forbidden - array\n * dimensions must be represented through the DIM field).\n *\n *

The LONG and DOUBLE types are always represented by using two slots (LONG + TOP or DOUBLE +\n * TOP), for local variables as well as in the operand stack. This is necessary to be able to\n * simulate DUPx_y instructions, whose effect would be dependent on the concrete types represented\n * by the abstract types in the stack (which are not always known).\n *\n * @author Eric Bruneton\n */\nclass Frame {\n // Constants used in the StackMapTable attribute.\n // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.4.\n static final int SAME_FRAME = 0;\n static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64;\n static final int RESERVED = 128;\n static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247;\n static final int CHOP_FRAME = 248;\n static final int SAME_FRAME_EXTENDED = 251;\n static final int APPEND_FRAME = 252;\n static final int FULL_FRAME = 255;\n static final int ITEM_TOP = 0;\n static final int ITEM_INTEGER = 1;\n static final int ITEM_FLOAT = 2;\n static final int ITEM_DOUBLE = 3;\n static final int ITEM_LONG = 4;\n static final int ITEM_NULL = 5;\n static final int ITEM_UNINITIALIZED_THIS = 6;\n static final int ITEM_OBJECT = 7;\n static final int ITEM_UNINITIALIZED = 8;\n // Additional, ASM specific constants used in abstract types below.\n private static final int ITEM_ASM_BOOLEAN = 9;\n private static final int ITEM_ASM_BYTE = 10;\n private static final int ITEM_ASM_CHAR = 11;\n private static final int ITEM_ASM_SHORT = 12;\n // The size and offset in bits of each field of an abstract type.\n private static final int DIM_SIZE = 6;\n private static final int KIND_SIZE = 4;\n private static final int FLAGS_SIZE = 2;\n private static final int VALUE_SIZE = 32 - DIM_SIZE - KIND_SIZE - FLAGS_SIZE;\n private static final int DIM_SHIFT = KIND_SIZE + FLAGS_SIZE + VALUE_SIZE;\n private static final int KIND_SHIFT = FLAGS_SIZE + VALUE_SIZE;\n private static final int FLAGS_SHIFT = VALUE_SIZE;\n // Bitmasks to get each field of an abstract type.\n private static final int DIM_MASK = ((1 << DIM_SIZE) - 1) << DIM_SHIFT;\n private static final int KIND_MASK = ((1 << KIND_SIZE) - 1) << KIND_SHIFT;\n private static final int VALUE_MASK = (1 << VALUE_SIZE) - 1;\n // Constants to manipulate the DIM field of an abstract type.\n /** The constant to be added to an abstract type to get one with one more array dimension. */\n private static final int ARRAY_OF = +1 << DIM_SHIFT;\n /** The constant to be added to an abstract type to get one with one less array dimension. */\n private static final int ELEMENT_OF = -1 << DIM_SHIFT;\n // Possible values for the KIND field of an abstract type.\n private static final int CONSTANT_KIND = 1 << KIND_SHIFT;\n private static final int REFERENCE_KIND = 2 << KIND_SHIFT;\n private static final int UNINITIALIZED_KIND = 3 << KIND_SHIFT;\n private static final int LOCAL_KIND = 4 << KIND_SHIFT;\n private static final int STACK_KIND = 5 << KIND_SHIFT;\n // Possible flags for the FLAGS field of an abstract type.\n /**\n * A flag used for LOCAL_KIND and STACK_KIND abstract types, indicating that if the resolved,\n * concrete type is LONG or DOUBLE, TOP should be used instead (because the value has been\n * partially overridden with an xSTORE instruction).\n */\n private static final int TOP_IF_LONG_OR_DOUBLE_FLAG = 1 << FLAGS_SHIFT;\n // Useful predefined abstract types (all the possible CONSTANT_KIND types).\n private static final int TOP = CONSTANT_KIND | ITEM_TOP;\n private static final int BOOLEAN = CONSTANT_KIND | ITEM_ASM_BOOLEAN;\n private static final int BYTE = CONSTANT_KIND | ITEM_ASM_BYTE;\n private static final int CHAR = CONSTANT_KIND | ITEM_ASM_CHAR;\n private static final int SHORT = CONSTANT_KIND | ITEM_ASM_SHORT;\n private static final int INTEGER = CONSTANT_KIND | ITEM_INTEGER;\n private static final int FLOAT = CONSTANT_KIND | ITEM_FLOAT;\n private static final int LONG = CONSTANT_KIND | ITEM_LONG;\n private static final int DOUBLE = CONSTANT_KIND | ITEM_DOUBLE;\n private static final int NULL = CONSTANT_KIND | ITEM_NULL;\n private static final int UNINITIALIZED_THIS = CONSTANT_KIND | ITEM_UNINITIALIZED_THIS;\n // -----------------------------------------------------------------------------------------------\n // Instance fields\n // -----------------------------------------------------------------------------------------------\n /** The basic block to which these input and output stack map frames correspond. */\n Label owner;\n /** The input stack map frame locals. This is an array of abstract types. */\n private int[] inputLocals;\n /** The input stack map frame stack. This is an array of abstract types. */\n private int[] inputStack;\n /** The output stack map frame locals. This is an array of abstract types. */\n private int[] outputLocals;\n /** The output stack map frame stack. This is an array of abstract types. */\n private int[] outputStack;\n /**\n * The start of the output stack, relatively to the input stack. This offset is always negative or\n * null. A null offset means that the output stack must be appended to the input stack. A -n\n * offset means that the first n output stack elements must replace the top n input stack\n * elements, and that the other elements must be appended to the input stack.\n */\n private short outputStackStart;\n /** The index of the top stack element in {@link #outputStack}. */\n private short outputStackTop;\n /** The number of types that are initialized in the basic block. See {@link #initializations}. */\n private int initializationCount;\n /**\n * The abstract types that are initialized in the basic block. A constructor invocation on an\n * UNINITIALIZED or UNINITIALIZED_THIS abstract type must replace every occurrence of this\n * type in the local variables and in the operand stack. This cannot be done during the first step\n * of the algorithm since, during this step, the local variables and the operand stack types are\n * still abstract. It is therefore necessary to store the abstract types of the constructors which\n * are invoked in the basic block, in order to do this replacement during the second step of the\n * algorithm, where the frames are fully computed. Note that this array can contain abstract types\n * that are relative to the input locals or to the input stack.\n */\n private int[] initializations;\n // -----------------------------------------------------------------------------------------------\n // Constructor\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Constructs a new Frame.\n *\n * @param owner the basic block to which these input and output stack map frames correspond.\n */\n Frame(final Label owner) {\n this.owner = owner;\n }\n\n /**\n * Sets this frame to the value of the given frame.\n *\n *

WARNING: after this method is called the two frames share the same data structures. It is\n * recommended to discard the given frame to avoid unexpected side effects.\n *\n * @param frame The new frame value.\n */\n final void copyFrom(final Frame frame) {\n inputLocals = frame.inputLocals;\n inputStack = frame.inputStack;\n outputStackStart = 0;\n outputLocals = frame.outputLocals;\n outputStack = frame.outputStack;\n outputStackTop = frame.outputStackTop;\n initializationCount = frame.initializationCount;\n initializations = frame.initializations;\n }\n // -----------------------------------------------------------------------------------------------\n // Static methods to get abstract types from other type formats\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the abstract type corresponding to the given public API frame element type.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param type a frame element type described using the same format as in {@link\n * MethodVisitor#visitFrame}, i.e. either {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, {@link\n * Opcodes#FLOAT}, {@link Opcodes#LONG}, {@link Opcodes#DOUBLE}, {@link Opcodes#NULL}, or\n * {@link Opcodes#UNINITIALIZED_THIS}, or the internal name of a class, or a Label designating\n * a NEW instruction (for uninitialized types).\n * @return the abstract type corresponding to the given frame element type.\n */\n static int getAbstractTypeFromApiFormat(final SymbolTable symbolTable, final Object type) {\n if (type instanceof Integer) {\n return CONSTANT_KIND | ((Integer) type).intValue();\n } else if (type instanceof String) {\n String descriptor = Type.getObjectType((String) type).getDescriptor();\n return getAbstractTypeFromDescriptor(symbolTable, descriptor, 0);\n } else {\n return UNINITIALIZED_KIND | symbolTable.addUninitializedType(\"\", ((Label) type).bytecodeOffset);\n }\n }\n\n /**\n * Returns the abstract type corresponding to the internal name of a class.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param internalName the internal name of a class. This must not be an array type\n * descriptor.\n * @return the abstract type value corresponding to the given internal name.\n */\n static int getAbstractTypeFromInternalName(final SymbolTable symbolTable, final String internalName) {\n return REFERENCE_KIND | symbolTable.addType(internalName);\n }\n\n /**\n * Returns the abstract type corresponding to the given type descriptor.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param buffer a string ending with a type descriptor.\n * @param offset the start offset of the type descriptor in buffer.\n * @return the abstract type corresponding to the given type descriptor.\n */\n private static int getAbstractTypeFromDescriptor(final SymbolTable symbolTable, final String buffer, final int offset) {\n String internalName;\n switch (buffer.charAt(offset)) {\n case 'V':\n return 0;\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n return INTEGER;\n case 'F':\n return FLOAT;\n case 'J':\n return LONG;\n case 'D':\n return DOUBLE;\n case 'L':\n internalName = buffer.substring(offset + 1, buffer.length() - 1);\n return REFERENCE_KIND | symbolTable.addType(internalName);\n case '[':\n int elementDescriptorOffset = offset + 1;\n while (buffer.charAt(elementDescriptorOffset) == '[') {\n ++elementDescriptorOffset;\n }\n int typeValue;\n switch (buffer.charAt(elementDescriptorOffset)) {\n case 'Z':\n typeValue = BOOLEAN;\n break;\n case 'C':\n typeValue = CHAR;\n break;\n case 'B':\n typeValue = BYTE;\n break;\n case 'S':\n typeValue = SHORT;\n break;\n case 'I':\n typeValue = INTEGER;\n break;\n case 'F':\n typeValue = FLOAT;\n break;\n case 'J':\n typeValue = LONG;\n break;\n case 'D':\n typeValue = DOUBLE;\n break;\n case 'L':\n internalName = buffer.substring(elementDescriptorOffset + 1, buffer.length() - 1);\n typeValue = REFERENCE_KIND | symbolTable.addType(internalName);\n break;\n default:\n throw new IllegalArgumentException();\n }\n return ((elementDescriptorOffset - offset) << DIM_SHIFT) | typeValue;\n default:\n throw new IllegalArgumentException();\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Methods related to the input frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Sets the input frame from the given method description. This method is used to initialize the\n * first frame of a method, which is implicit (i.e. not stored explicitly in the StackMapTable\n * attribute).\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param access the method's access flags.\n * @param descriptor the method descriptor.\n * @param maxLocals the maximum number of local variables of the method.\n */\n final void setInputFrameFromDescriptor(final SymbolTable symbolTable, final int access, final String descriptor, final int maxLocals) {\n inputLocals = new int[maxLocals];\n inputStack = new int[0];\n int inputLocalIndex = 0;\n if ((access & Opcodes.ACC_STATIC) == 0) {\n if ((access & Constants.ACC_CONSTRUCTOR) == 0) {\n inputLocals[inputLocalIndex++] = REFERENCE_KIND | symbolTable.addType(symbolTable.getClassName());\n } else {\n inputLocals[inputLocalIndex++] = UNINITIALIZED_THIS;\n }\n }\n for (Type argumentType : Type.getArgumentTypes(descriptor)) {\n int abstractType = getAbstractTypeFromDescriptor(symbolTable, argumentType.getDescriptor(), 0);\n inputLocals[inputLocalIndex++] = abstractType;\n if (abstractType == LONG || abstractType == DOUBLE) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n }\n while (inputLocalIndex < maxLocals) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n }\n\n /**\n * Sets the input frame from the given public API frame description.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param numLocal the number of local variables.\n * @param local the local variable types, described using the same format as in {@link\n * MethodVisitor#visitFrame}.\n * @param numStack the number of operand stack elements.\n * @param stack the operand stack types, described using the same format as in {@link\n * MethodVisitor#visitFrame}.\n */\n final void setInputFrameFromApiFormat(final SymbolTable symbolTable, final int numLocal, final Object[] local, final int numStack, final Object[] stack) {\n int inputLocalIndex = 0;\n for (int i = 0; i < numLocal; ++i) {\n inputLocals[inputLocalIndex++] = getAbstractTypeFromApiFormat(symbolTable, local[i]);\n if (local[i] == Opcodes.LONG || local[i] == Opcodes.DOUBLE) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n }\n while (inputLocalIndex < inputLocals.length) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n int numStackTop = 0;\n for (int i = 0; i < numStack; ++i) {\n if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) {\n ++numStackTop;\n }\n }\n inputStack = new int[numStack + numStackTop];\n int inputStackIndex = 0;\n for (int i = 0; i < numStack; ++i) {\n inputStack[inputStackIndex++] = getAbstractTypeFromApiFormat(symbolTable, stack[i]);\n if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) {\n inputStack[inputStackIndex++] = TOP;\n }\n }\n outputStackTop = 0;\n initializationCount = 0;\n }\n\n final int getInputStackSize() {\n return inputStack.length;\n }\n // -----------------------------------------------------------------------------------------------\n // Methods related to the output frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the abstract type stored at the given local variable index in the output frame.\n *\n * @param localIndex the index of the local variable whose value must be returned.\n * @return the abstract type stored at the given local variable index in the output frame.\n */\n private int getLocal(final int localIndex) {\n if (outputLocals == null || localIndex >= outputLocals.length) {\n // If this local has never been assigned in this basic block, it is still equal to its value\n // in the input frame.\n return LOCAL_KIND | localIndex;\n } else {\n int abstractType = outputLocals[localIndex];\n if (abstractType == 0) {\n // If this local has never been assigned in this basic block, so it is still equal to its\n // value in the input frame.\n abstractType = outputLocals[localIndex] = LOCAL_KIND | localIndex;\n }\n return abstractType;\n }\n }\n\n /**\n * Replaces the abstract type stored at the given local variable index in the output frame.\n *\n * @param localIndex the index of the output frame local variable that must be set.\n * @param abstractType the value that must be set.\n */\n private void setLocal(final int localIndex, final int abstractType) {\n // Create and/or resize the output local variables array if necessary.\n if (outputLocals == null) {\n outputLocals = new int[10];\n }\n int outputLocalsLength = outputLocals.length;\n if (localIndex >= outputLocalsLength) {\n int[] newOutputLocals = new int[Math.max(localIndex + 1, 2 * outputLocalsLength)];\n System.arraycopy(outputLocals, 0, newOutputLocals, 0, outputLocalsLength);\n outputLocals = newOutputLocals;\n }\n // Set the local variable.\n outputLocals[localIndex] = abstractType;\n }\n\n /**\n * Pushes the given abstract type on the output frame stack.\n *\n * @param abstractType an abstract type.\n */\n private void push(final int abstractType) {\n // Create and/or resize the output stack array if necessary.\n if (outputStack == null) {\n outputStack = new int[10];\n }\n int outputStackLength = outputStack.length;\n if (outputStackTop >= outputStackLength) {\n int[] newOutputStack = new int[Math.max(outputStackTop + 1, 2 * outputStackLength)];\n System.arraycopy(outputStack, 0, newOutputStack, 0, outputStackLength);\n outputStack = newOutputStack;\n }\n // Pushes the abstract type on the output stack.\n outputStack[outputStackTop++] = abstractType;\n // Updates the maximum size reached by the output stack, if needed (note that this size is\n // relative to the input stack size, which is not known yet).\n short outputStackSize = (short) (outputStackStart + outputStackTop);\n if (outputStackSize > owner.outputStackMax) {\n owner.outputStackMax = outputStackSize;\n }\n }\n\n /**\n * Pushes the abstract type corresponding to the given descriptor on the output frame stack.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param descriptor a type or method descriptor (in which case its return type is pushed).\n */\n private void push(final SymbolTable symbolTable, final String descriptor) {\n int typeDescriptorOffset = descriptor.charAt(0) == '(' ? Type.getReturnTypeOffset(descriptor) : 0;\n int abstractType = getAbstractTypeFromDescriptor(symbolTable, descriptor, typeDescriptorOffset);\n if (abstractType != 0) {\n push(abstractType);\n if (abstractType == LONG || abstractType == DOUBLE) {\n push(TOP);\n }\n }\n }\n\n /**\n * Pops an abstract type from the output frame stack and returns its value.\n *\n * @return the abstract type that has been popped from the output frame stack.\n */\n private int pop() {\n if (outputStackTop > 0) {\n return outputStack[--outputStackTop];\n } else {\n // If the output frame stack is empty, pop from the input stack.\n return STACK_KIND | -(--outputStackStart);\n }\n }\n\n /**\n * Pops the given number of abstract types from the output frame stack.\n *\n * @param elements the number of abstract types that must be popped.\n */\n private void pop(final int elements) {\n if (outputStackTop >= elements) {\n outputStackTop -= elements;\n } else {\n // If the number of elements to be popped is greater than the number of elements in the output\n // stack, clear it, and pop the remaining elements from the input stack.\n outputStackStart -= elements - outputStackTop;\n outputStackTop = 0;\n }\n }\n\n /**\n * Pops as many abstract types from the output frame stack as described by the given descriptor.\n *\n * @param descriptor a type or method descriptor (in which case its argument types are popped).\n */\n private void pop(final String descriptor) {\n char firstDescriptorChar = descriptor.charAt(0);\n if (firstDescriptorChar == '(') {\n pop((Type.getArgumentsAndReturnSizes(descriptor) >> 2) - 1);\n } else if (firstDescriptorChar == 'J' || firstDescriptorChar == 'D') {\n pop(2);\n } else {\n pop(1);\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Methods to handle uninitialized types\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Adds an abstract type to the list of types on which a constructor is invoked in the basic\n * block.\n *\n * @param abstractType an abstract type on a which a constructor is invoked.\n */\n private void addInitializedType(final int abstractType) {\n // Create and/or resize the initializations array if necessary.\n if (initializations == null) {\n initializations = new int[2];\n }\n int initializationsLength = initializations.length;\n if (initializationCount >= initializationsLength) {\n int[] newInitializations = new int[Math.max(initializationCount + 1, 2 * initializationsLength)];\n System.arraycopy(initializations, 0, newInitializations, 0, initializationsLength);\n initializations = newInitializations;\n }\n // Store the abstract type.\n initializations[initializationCount++] = abstractType;\n }\n\n /**\n * Returns the \"initialized\" abstract type corresponding to the given abstract type.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param abstractType an abstract type.\n * @return the REFERENCE_KIND abstract type corresponding to abstractType if it is\n * UNINITIALIZED_THIS or an UNINITIALIZED_KIND abstract type for one of the types on which a\n * constructor is invoked in the basic block. Otherwise returns abstractType.\n */\n private int getInitializedType(final SymbolTable symbolTable, final int abstractType) {\n if (abstractType == UNINITIALIZED_THIS || (abstractType & (DIM_MASK | KIND_MASK)) == UNINITIALIZED_KIND) {\n for (int i = 0; i < initializationCount; ++i) {\n int initializedType = initializations[i];\n int dim = initializedType & DIM_MASK;\n int kind = initializedType & KIND_MASK;\n int value = initializedType & VALUE_MASK;\n if (kind == LOCAL_KIND) {\n initializedType = dim + inputLocals[value];\n } else if (kind == STACK_KIND) {\n initializedType = dim + inputStack[inputStack.length - value];\n }\n if (abstractType == initializedType) {\n if (abstractType == UNINITIALIZED_THIS) {\n return REFERENCE_KIND | symbolTable.addType(symbolTable.getClassName());\n } else {\n return REFERENCE_KIND | symbolTable.addType(symbolTable.getType(abstractType & VALUE_MASK).value);\n }\n }\n }\n }\n return abstractType;\n }\n // -----------------------------------------------------------------------------------------------\n // Main method, to simulate the execution of each instruction on the output frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Simulates the action of the given instruction on the output stack frame.\n *\n * @param opcode the opcode of the instruction.\n * @param arg the numeric operand of the instruction, if any.\n * @param argSymbol the Symbol operand of the instruction, if any.\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n */\n void execute(final int opcode, final int arg, final Symbol argSymbol, final SymbolTable symbolTable) {\n // Abstract types popped from the stack or read from local variables.\n int abstractType1;\n int abstractType2;\n int abstractType3;\n int abstractType4;\n switch (opcode) {\n case Opcodes.NOP:\n case Opcodes.INEG:\n case Opcodes.LNEG:\n case Opcodes.FNEG:\n case Opcodes.DNEG:\n case Opcodes.I2B:\n case Opcodes.I2C:\n case Opcodes.I2S:\n case Opcodes.GOTO:\n case Opcodes.RETURN:\n break;\n case Opcodes.ACONST_NULL:\n push(NULL);\n break;\n case Opcodes.ICONST_M1:\n case Opcodes.ICONST_0:\n case Opcodes.ICONST_1:\n case Opcodes.ICONST_2:\n case Opcodes.ICONST_3:\n case Opcodes.ICONST_4:\n case Opcodes.ICONST_5:\n case Opcodes.BIPUSH:\n case Opcodes.SIPUSH:\n case Opcodes.ILOAD:\n push(INTEGER);\n break;\n case Opcodes.LCONST_0:\n case Opcodes.LCONST_1:\n case Opcodes.LLOAD:\n push(LONG);\n push(TOP);\n break;\n case Opcodes.FCONST_0:\n case Opcodes.FCONST_1:\n case Opcodes.FCONST_2:\n case Opcodes.FLOAD:\n push(FLOAT);\n break;\n case Opcodes.DCONST_0:\n case Opcodes.DCONST_1:\n case Opcodes.DLOAD:\n push(DOUBLE);\n push(TOP);\n break;\n case Opcodes.LDC:\n switch (argSymbol.tag) {\n case Symbol.CONSTANT_INTEGER_TAG:\n push(INTEGER);\n break;\n case Symbol.CONSTANT_LONG_TAG:\n push(LONG);\n push(TOP);\n break;\n case Symbol.CONSTANT_FLOAT_TAG:\n push(FLOAT);\n break;\n case Symbol.CONSTANT_DOUBLE_TAG:\n push(DOUBLE);\n push(TOP);\n break;\n case Symbol.CONSTANT_CLASS_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/Class\"));\n break;\n case Symbol.CONSTANT_STRING_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/String\"));\n break;\n case Symbol.CONSTANT_METHOD_TYPE_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/invoke/MethodType\"));\n break;\n case Symbol.CONSTANT_METHOD_HANDLE_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/invoke/MethodHandle\"));\n break;\n case Symbol.CONSTANT_DYNAMIC_TAG:\n push(symbolTable, argSymbol.value);\n break;\n default:\n throw new AssertionError();\n }\n break;\n case Opcodes.ALOAD:\n push(getLocal(arg));\n break;\n case Opcodes.LALOAD:\n case Opcodes.D2L:\n pop(2);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.DALOAD:\n case Opcodes.L2D:\n pop(2);\n push(DOUBLE);\n push(TOP);\n break;\n case Opcodes.AALOAD:\n pop(1);\n abstractType1 = pop();\n push(abstractType1 == NULL ? abstractType1 : ELEMENT_OF + abstractType1);\n break;\n case Opcodes.ISTORE:\n case Opcodes.FSTORE:\n case Opcodes.ASTORE:\n abstractType1 = pop();\n setLocal(arg, abstractType1);\n if (arg > 0) {\n int previousLocalType = getLocal(arg - 1);\n if (previousLocalType == LONG || previousLocalType == DOUBLE) {\n setLocal(arg - 1, TOP);\n } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND || (previousLocalType & KIND_MASK) == STACK_KIND) {\n // The type of the previous local variable is not known yet, but if it later appears\n // to be LONG or DOUBLE, we should then use TOP instead.\n setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG);\n }\n }\n break;\n case Opcodes.LSTORE:\n case Opcodes.DSTORE:\n pop(1);\n abstractType1 = pop();\n setLocal(arg, abstractType1);\n setLocal(arg + 1, TOP);\n if (arg > 0) {\n int previousLocalType = getLocal(arg - 1);\n if (previousLocalType == LONG || previousLocalType == DOUBLE) {\n setLocal(arg - 1, TOP);\n } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND || (previousLocalType & KIND_MASK) == STACK_KIND) {\n // The type of the previous local variable is not known yet, but if it later appears\n // to be LONG or DOUBLE, we should then use TOP instead.\n setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG);\n }\n }\n break;\n case Opcodes.IASTORE:\n case Opcodes.BASTORE:\n case Opcodes.CASTORE:\n case Opcodes.SASTORE:\n case Opcodes.FASTORE:\n case Opcodes.AASTORE:\n pop(3);\n break;\n case Opcodes.LASTORE:\n case Opcodes.DASTORE:\n pop(4);\n break;\n case Opcodes.POP:\n case Opcodes.IFEQ:\n case Opcodes.IFNE:\n case Opcodes.IFLT:\n case Opcodes.IFGE:\n case Opcodes.IFGT:\n case Opcodes.IFLE:\n case Opcodes.IRETURN:\n case Opcodes.FRETURN:\n case Opcodes.ARETURN:\n case Opcodes.TABLESWITCH:\n case Opcodes.LOOKUPSWITCH:\n case Opcodes.ATHROW:\n case Opcodes.MONITORENTER:\n case Opcodes.MONITOREXIT:\n case Opcodes.IFNULL:\n case Opcodes.IFNONNULL:\n pop(1);\n break;\n case Opcodes.POP2:\n case Opcodes.IF_ICMPEQ:\n case Opcodes.IF_ICMPNE:\n case Opcodes.IF_ICMPLT:\n case Opcodes.IF_ICMPGE:\n case Opcodes.IF_ICMPGT:\n case Opcodes.IF_ICMPLE:\n case Opcodes.IF_ACMPEQ:\n case Opcodes.IF_ACMPNE:\n case Opcodes.LRETURN:\n case Opcodes.DRETURN:\n pop(2);\n break;\n case Opcodes.DUP:\n abstractType1 = pop();\n push(abstractType1);\n push(abstractType1);\n break;\n case Opcodes.DUP_X1:\n abstractType1 = pop();\n abstractType2 = pop();\n push(abstractType1);\n push(abstractType2);\n push(abstractType1);\n break;\n case Opcodes.DUP_X2:\n abstractType1 = pop();\n abstractType2 = pop();\n abstractType3 = pop();\n push(abstractType1);\n push(abstractType3);\n push(abstractType2);\n push(abstractType1);\n break;\n case Opcodes.DUP2:\n abstractType1 = pop();\n abstractType2 = pop();\n push(abstractType2);\n push(abstractType1);\n push(abstractType2);\n push(abstractType1);\n break;\n case Opcodes.DUP2_X1:\n abstractType1 = pop();\n abstractType2 = pop();\n abstractType3 = pop();\n push(abstractType2);\n push(abstractType1);\n push(abstractType3);\n push(abstractType2);\n push(abstractType1);\n break;\n case Opcodes.DUP2_X2:\n abstractType1 = pop();\n abstractType2 = pop();\n abstractType3 = pop();\n abstractType4 = pop();\n push(abstractType2);\n push(abstractType1);\n push(abstractType4);\n push(abstractType3);\n push(abstractType2);\n push(abstractType1);\n break;\n case Opcodes.SWAP:\n abstractType1 = pop();\n abstractType2 = pop();\n push(abstractType1);\n push(abstractType2);\n break;\n case Opcodes.IALOAD:\n case Opcodes.BALOAD:\n case Opcodes.CALOAD:\n case Opcodes.SALOAD:\n case Opcodes.IADD:\n case Opcodes.ISUB:\n case Opcodes.IMUL:\n case Opcodes.IDIV:\n case Opcodes.IREM:\n case Opcodes.IAND:\n case Opcodes.IOR:\n case Opcodes.IXOR:\n case Opcodes.ISHL:\n case Opcodes.ISHR:\n case Opcodes.IUSHR:\n case Opcodes.L2I:\n case Opcodes.D2I:\n case Opcodes.FCMPL:\n case Opcodes.FCMPG:\n pop(2);\n push(INTEGER);\n break;\n case Opcodes.LADD:\n case Opcodes.LSUB:\n case Opcodes.LMUL:\n case Opcodes.LDIV:\n case Opcodes.LREM:\n case Opcodes.LAND:\n case Opcodes.LOR:\n case Opcodes.LXOR:\n pop(4);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.FALOAD:\n case Opcodes.FADD:\n case Opcodes.FSUB:\n case Opcodes.FMUL:\n case Opcodes.FDIV:\n case Opcodes.FREM:\n case Opcodes.L2F:\n case Opcodes.D2F:\n pop(2);\n push(FLOAT);\n break;\n case Opcodes.DADD:\n case Opcodes.DSUB:\n case Opcodes.DMUL:\n case Opcodes.DDIV:\n case Opcodes.DREM:\n pop(4);\n push(DOUBLE);\n push(TOP);\n break;\n case Opcodes.LSHL:\n case Opcodes.LSHR:\n case Opcodes.LUSHR:\n pop(3);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.IINC:\n setLocal(arg, INTEGER);\n break;\n case Opcodes.I2L:\n case Opcodes.F2L:\n pop(1);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.I2F:\n pop(1);\n push(FLOAT);\n break;\n case Opcodes.I2D:\n case Opcodes.F2D:\n pop(1);\n push(DOUBLE);\n push(TOP);\n break;\n case Opcodes.F2I:\n case Opcodes.ARRAYLENGTH:\n case Opcodes.INSTANCEOF:\n pop(1);\n push(INTEGER);\n break;\n case Opcodes.LCMP:\n case Opcodes.DCMPL:\n case Opcodes.DCMPG:\n pop(4);\n push(INTEGER);\n break;\n case Opcodes.JSR:\n case Opcodes.RET:\n throw new IllegalArgumentException(\"JSR/RET are not supported with computeFrames option\");\n case Opcodes.GETSTATIC:\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.PUTSTATIC:\n pop(argSymbol.value);\n break;\n case Opcodes.GETFIELD:\n pop(1);\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.PUTFIELD:\n pop(argSymbol.value);\n pop();\n break;\n case Opcodes.INVOKEVIRTUAL:\n case Opcodes.INVOKESPECIAL:\n case Opcodes.INVOKESTATIC:\n case Opcodes.INVOKEINTERFACE:\n pop(argSymbol.value);\n if (opcode != Opcodes.INVOKESTATIC) {\n abstractType1 = pop();\n if (opcode == Opcodes.INVOKESPECIAL && argSymbol.name.charAt(0) == '<') {\n addInitializedType(abstractType1);\n }\n }\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.INVOKEDYNAMIC:\n pop(argSymbol.value);\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.NEW:\n push(UNINITIALIZED_KIND | symbolTable.addUninitializedType(argSymbol.value, arg));\n break;\n case Opcodes.NEWARRAY:\n pop();\n switch (arg) {\n case Opcodes.T_BOOLEAN:\n push(ARRAY_OF | BOOLEAN);\n break;\n case Opcodes.T_CHAR:\n push(ARRAY_OF | CHAR);\n break;\n case Opcodes.T_BYTE:\n push(ARRAY_OF | BYTE);\n break;\n case Opcodes.T_SHORT:\n push(ARRAY_OF | SHORT);\n break;\n case Opcodes.T_INT:\n push(ARRAY_OF | INTEGER);\n break;\n case Opcodes.T_FLOAT:\n push(ARRAY_OF | FLOAT);\n break;\n case Opcodes.T_DOUBLE:\n push(ARRAY_OF | DOUBLE);\n break;\n case Opcodes.T_LONG:\n push(ARRAY_OF | LONG);\n break;\n default:\n throw new IllegalArgumentException();\n }\n break;\n case Opcodes.ANEWARRAY:\n String arrayElementType = argSymbol.value;\n pop();\n if (arrayElementType.charAt(0) == '[') {\n push(symbolTable, '[' + arrayElementType);\n } else {\n push(ARRAY_OF | REFERENCE_KIND | symbolTable.addType(arrayElementType));\n }\n break;\n case Opcodes.CHECKCAST:\n String castType = argSymbol.value;\n pop();\n if (castType.charAt(0) == '[') {\n push(symbolTable, castType);\n } else {\n push(REFERENCE_KIND | symbolTable.addType(castType));\n }\n break;\n case Opcodes.MULTIANEWARRAY:\n pop(arg);\n push(symbolTable, argSymbol.value);\n break;\n default:\n throw new IllegalArgumentException();\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Frame merging methods, used in the second step of the stack map frame computation algorithm\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Computes the concrete output type corresponding to a given abstract output type.\n *\n * @param abstractOutputType an abstract output type.\n * @param numStack the size of the input stack, used to resolve abstract output types of\n * STACK_KIND kind.\n * @return the concrete output type corresponding to 'abstractOutputType'.\n */\n private int getConcreteOutputType(final int abstractOutputType, final int numStack) {\n int dim = abstractOutputType & DIM_MASK;\n int kind = abstractOutputType & KIND_MASK;\n if (kind == LOCAL_KIND) {\n // By definition, a LOCAL_KIND type designates the concrete type of a local variable at\n // the beginning of the basic block corresponding to this frame (which is known when\n // this method is called, but was not when the abstract type was computed).\n int concreteOutputType = dim + inputLocals[abstractOutputType & VALUE_MASK];\n if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0 && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) {\n concreteOutputType = TOP;\n }\n return concreteOutputType;\n } else if (kind == STACK_KIND) {\n // By definition, a STACK_KIND type designates the concrete type of a local variable at\n // the beginning of the basic block corresponding to this frame (which is known when\n // this method is called, but was not when the abstract type was computed).\n int concreteOutputType = dim + inputStack[numStack - (abstractOutputType & VALUE_MASK)];\n if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0 && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) {\n concreteOutputType = TOP;\n }\n return concreteOutputType;\n } else {\n return abstractOutputType;\n }\n }\n\n /**\n * Merges the input frame of the given {@link Frame} with the input and output frames of this\n * {@link Frame}. Returns {@literal true} if the given frame has been changed by this operation\n * (the input and output frames of this {@link Frame} are never changed).\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param dstFrame the {@link Frame} whose input frame must be updated. This should be the frame\n * of a successor, in the control flow graph, of the basic block corresponding to this frame.\n * @param catchTypeIndex if 'frame' corresponds to an exception handler basic block, the type\n * table index of the caught exception type, otherwise 0.\n * @return {@literal true} if the input frame of 'frame' has been changed by this operation.\n */\n final boolean merge(final SymbolTable symbolTable, final Frame dstFrame, final int catchTypeIndex) {\n boolean frameChanged = false;\n // Compute the concrete types of the local variables at the end of the basic block corresponding\n // to this frame, by resolving its abstract output types, and merge these concrete types with\n // those of the local variables in the input frame of dstFrame.\n int numLocal = inputLocals.length;\n int numStack = inputStack.length;\n if (dstFrame.inputLocals == null) {\n dstFrame.inputLocals = new int[numLocal];\n frameChanged = true;\n }\n for (int i = 0; i < numLocal; ++i) {\n int concreteOutputType;\n if (outputLocals != null && i < outputLocals.length) {\n int abstractOutputType = outputLocals[i];\n if (abstractOutputType == 0) {\n // If the local variable has never been assigned in this basic block, it is equal to its\n // value at the beginning of the block.\n concreteOutputType = inputLocals[i];\n } else {\n concreteOutputType = getConcreteOutputType(abstractOutputType, numStack);\n }\n } else {\n // If the local variable has never been assigned in this basic block, it is equal to its\n // value at the beginning of the block.\n concreteOutputType = inputLocals[i];\n }\n // concreteOutputType might be an uninitialized type from the input locals or from the input\n // stack. However, if a constructor has been called for this class type in the basic block,\n // then this type is no longer uninitialized at the end of basic block.\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputLocals, i);\n }\n // If dstFrame is an exception handler block, it can be reached from any instruction of the\n // basic block corresponding to this frame, in particular from the first one. Therefore, the\n // input locals of dstFrame should be compatible (i.e. merged) with the input locals of this\n // frame (and the input stack of dstFrame should be compatible, i.e. merged, with a one\n // element stack containing the caught exception type).\n if (catchTypeIndex > 0) {\n for (int i = 0; i < numLocal; ++i) {\n frameChanged |= merge(symbolTable, inputLocals[i], dstFrame.inputLocals, i);\n }\n if (dstFrame.inputStack == null) {\n dstFrame.inputStack = new int[1];\n frameChanged = true;\n }\n frameChanged |= merge(symbolTable, catchTypeIndex, dstFrame.inputStack, 0);\n return frameChanged;\n }\n // Compute the concrete types of the stack operands at the end of the basic block corresponding\n // to this frame, by resolving its abstract output types, and merge these concrete types with\n // those of the stack operands in the input frame of dstFrame.\n int numInputStack = inputStack.length + outputStackStart;\n if (dstFrame.inputStack == null) {\n dstFrame.inputStack = new int[numInputStack + outputStackTop];\n frameChanged = true;\n }\n // First, do this for the stack operands that have not been popped in the basic block\n // corresponding to this frame, and which are therefore equal to their value in the input\n // frame (except for uninitialized types, which may have been initialized).\n for (int i = 0; i < numInputStack; ++i) {\n int concreteOutputType = inputStack[i];\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputStack, i);\n }\n // Then, do this for the stack operands that have pushed in the basic block (this code is the\n // same as the one above for local variables).\n for (int i = 0; i < outputStackTop; ++i) {\n int abstractOutputType = outputStack[i];\n int concreteOutputType = getConcreteOutputType(abstractOutputType, numStack);\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputStack, numInputStack + i);\n }\n return frameChanged;\n }\n\n /**\n * Merges the type at the given index in the given abstract type array with the given type.\n * Returns {@literal true} if the type array has been modified by this operation.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param sourceType the abstract type with which the abstract type array element must be merged.\n * This type should be of {@link #CONSTANT_KIND}, {@link #REFERENCE_KIND} or {@link\n * #UNINITIALIZED_KIND} kind, with positive or {@literal null} array dimensions.\n * @param dstTypes an array of abstract types. These types should be of {@link #CONSTANT_KIND},\n * {@link #REFERENCE_KIND} or {@link #UNINITIALIZED_KIND} kind, with positive or {@literal\n * null} array dimensions.\n * @param dstIndex the index of the type that must be merged in dstTypes.\n * @return {@literal true} if the type array has been modified by this operation.\n */\n private static boolean merge(final SymbolTable symbolTable, final int sourceType, final int[] dstTypes, final int dstIndex) {\n int dstType = dstTypes[dstIndex];\n if (dstType == sourceType) {\n // If the types are equal, merge(sourceType, dstType) = dstType, so there is no change.\n return false;\n }\n int srcType = sourceType;\n if ((sourceType & ~DIM_MASK) == NULL) {\n if (dstType == NULL) {\n return false;\n }\n srcType = NULL;\n }\n if (dstType == 0) {\n // If dstTypes[dstIndex] has never been assigned, merge(srcType, dstType) = srcType.\n dstTypes[dstIndex] = srcType;\n return true;\n }\n int mergedType;\n if ((dstType & DIM_MASK) != 0 || (dstType & KIND_MASK) == REFERENCE_KIND) {\n // If dstType is a reference type of any array dimension.\n if (srcType == NULL) {\n // If srcType is the NULL type, merge(srcType, dstType) = dstType, so there is no change.\n return false;\n } else if ((srcType & (DIM_MASK | KIND_MASK)) == (dstType & (DIM_MASK | KIND_MASK))) {\n // If srcType has the same array dimension and the same kind as dstType.\n if ((dstType & KIND_MASK) == REFERENCE_KIND) {\n // If srcType and dstType are reference types with the same array dimension,\n // merge(srcType, dstType) = dim(srcType) | common super class of srcType and dstType.\n mergedType = (srcType & DIM_MASK) | REFERENCE_KIND | symbolTable.addMergedType(srcType & VALUE_MASK, dstType & VALUE_MASK);\n } else {\n // If srcType and dstType are array types of equal dimension but different element types,\n // merge(srcType, dstType) = dim(srcType) - 1 | java/lang/Object.\n int mergedDim = ELEMENT_OF + (srcType & DIM_MASK);\n mergedType = mergedDim | REFERENCE_KIND | symbolTable.addType(\"java/lang/Object\");\n }\n } else if ((srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND) {\n // If srcType is any other reference or array type,\n // merge(srcType, dstType) = min(srcDdim, dstDim) | java/lang/Object\n // where srcDim is the array dimension of srcType, minus 1 if srcType is an array type\n // with a non reference element type (and similarly for dstDim).\n int srcDim = srcType & DIM_MASK;\n if (srcDim != 0 && (srcType & KIND_MASK) != REFERENCE_KIND) {\n srcDim = ELEMENT_OF + srcDim;\n }\n int dstDim = dstType & DIM_MASK;\n if (dstDim != 0 && (dstType & KIND_MASK) != REFERENCE_KIND) {\n dstDim = ELEMENT_OF + dstDim;\n }\n mergedType = Math.min(srcDim, dstDim) | REFERENCE_KIND | symbolTable.addType(\"java/lang/Object\");\n } else {\n // If srcType is any other type, merge(srcType, dstType) = TOP.\n mergedType = TOP;\n }\n } else if (dstType == NULL) {\n // If dstType is the NULL type, merge(srcType, dstType) = srcType, or TOP if srcType is not a\n // an array type or a reference type.\n mergedType = (srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND ? srcType : TOP;\n } else {\n // If dstType is any other type, merge(srcType, dstType) = TOP whatever srcType.\n mergedType = TOP;\n }\n if (mergedType != dstType) {\n dstTypes[dstIndex] = mergedType;\n return true;\n }\n return false;\n }\n // -----------------------------------------------------------------------------------------------\n // Frame output methods, to generate StackMapFrame attributes\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Makes the given {@link MethodWriter} visit the input frame of this {@link Frame}. The visit is\n * done with the {@link MethodWriter#visitFrameStart}, {@link MethodWriter#visitAbstractType} and\n * {@link MethodWriter#visitFrameEnd} methods.\n *\n * @param methodWriter the {@link MethodWriter} that should visit the input frame of this {@link\n * Frame}.\n */\n final void accept(final MethodWriter methodWriter) {\n // Compute the number of locals, ignoring TOP types that are just after a LONG or a DOUBLE, and\n // all trailing TOP types.\n int[] localTypes = inputLocals;\n int numLocal = 0;\n int numTrailingTop = 0;\n int i = 0;\n while (i < localTypes.length) {\n int localType = localTypes[i];\n i += (localType == LONG || localType == DOUBLE) ? 2 : 1;\n if (localType == TOP) {\n numTrailingTop++;\n } else {\n numLocal += numTrailingTop + 1;\n numTrailingTop = 0;\n }\n }\n // Compute the stack size, ignoring TOP types that are just after a LONG or a DOUBLE.\n int[] stackTypes = inputStack;\n int numStack = 0;\n i = 0;\n while (i < stackTypes.length) {\n int stackType = stackTypes[i];\n i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1;\n numStack++;\n }\n // Visit the frame and its content.\n int frameIndex = methodWriter.visitFrameStart(owner.bytecodeOffset, numLocal, numStack);\n i = 0;\n while (numLocal-- > 0) {\n int localType = localTypes[i];\n i += (localType == LONG || localType == DOUBLE) ? 2 : 1;\n methodWriter.visitAbstractType(frameIndex++, localType);\n }\n i = 0;\n while (numStack-- > 0) {\n int stackType = stackTypes[i];\n i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1;\n methodWriter.visitAbstractType(frameIndex++, stackType);\n }\n methodWriter.visitFrameEnd();\n }\n\n /**\n * Put the given abstract type in the given ByteVector, using the JVMS verification_type_info\n * format used in StackMapTable attributes.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param abstractType an abstract type, restricted to {@link Frame#CONSTANT_KIND}, {@link\n * Frame#REFERENCE_KIND} or {@link Frame#UNINITIALIZED_KIND} types.\n * @param output where the abstract type must be put.\n * @see JVMS\n * 4.7.4\n */\n static void putAbstractType(final SymbolTable symbolTable, final int abstractType, final ByteVector output) {\n int arrayDimensions = (abstractType & Frame.DIM_MASK) >> DIM_SHIFT;\n if (arrayDimensions == 0) {\n int typeValue = abstractType & VALUE_MASK;\n switch (abstractType & KIND_MASK) {\n case CONSTANT_KIND:\n output.putByte(typeValue);\n break;\n case REFERENCE_KIND:\n output.putByte(ITEM_OBJECT).putShort(symbolTable.addConstantClass(symbolTable.getType(typeValue).value).index);\n break;\n case UNINITIALIZED_KIND:\n output.putByte(ITEM_UNINITIALIZED).putShort((int) symbolTable.getType(typeValue).data);\n break;\n default:\n throw new AssertionError();\n }\n } else {\n // Case of an array type, we need to build its descriptor first.\n StringBuilder typeDescriptor = new StringBuilder();\n while (arrayDimensions-- > 0) {\n typeDescriptor.append('[');\n }\n if ((abstractType & KIND_MASK) == REFERENCE_KIND) {\n typeDescriptor.append('L').append(symbolTable.getType(abstractType & VALUE_MASK).value).append(';');\n } else {\n switch (abstractType & VALUE_MASK) {\n case Frame.ITEM_ASM_BOOLEAN:\n typeDescriptor.append('Z');\n break;\n case Frame.ITEM_ASM_BYTE:\n typeDescriptor.append('B');\n break;\n case Frame.ITEM_ASM_CHAR:\n typeDescriptor.append('C');\n break;\n case Frame.ITEM_ASM_SHORT:\n typeDescriptor.append('S');\n break;\n case Frame.ITEM_INTEGER:\n typeDescriptor.append('I');\n break;\n case Frame.ITEM_FLOAT:\n typeDescriptor.append('F');\n break;\n case Frame.ITEM_LONG:\n typeDescriptor.append('J');\n break;\n case Frame.ITEM_DOUBLE:\n typeDescriptor.append('D');\n break;\n default:\n throw new AssertionError();\n }\n }\n output.putByte(ITEM_OBJECT).putShort(symbolTable.addConstantClass(typeDescriptor.toString()).index);\n }\n }\n}\n", "file_name": "Frame.java", "human_label": "Pop the various value according to the first character of the descriptor.", "level": "class_runnable", "lineno": "544", "name": "pop", "oracle_context": "{ \"apis\" : \"[charAt, getArgumentsAndReturnSizes]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils.asm", "project": "hasor-master" }, { "_id": "636766f91a6d9265ec01776e", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.io.OutputStream;\\nimport java.io.Writer;\\nbyte[] buf;\\nchar[] chars;\\nint count;\\nint encCount;\\nint totalCharsWritten;\\nWriter writer;\\nchar[] CA;\\nBase64OutputStream(int size,Writer writer);\\nwrite(byte b,int off,int len);\\nwrite(byte b);\\nclose();\\nfinish();\\ngetTotalCharsWritten();\\nencodePendingBytes(boolean pad);\\ndrainCharBuffer();\\nwrite(int b);\\n\", \"repo_level\" : \"\" }", "class_name": "Base64OutputStream", "code": "@Override public void write(final byte b[],final int off,final int len) throws IOException {\n if (off < 0 || off > b.length || len < 0 || off + len > b.length || off + len < 0) {\n throw new IndexOutOfBoundsException();\n }\n else if (len == 0) {\n return;\n }\n if (this.count + len > this.buf.length) {\n this.encodePendingBytes(false);\n }\n System.arraycopy(b,off,this.buf,this.count,len);\n this.count+=len;\n}\n", "docstring": "/** \n * Writes len bytes from the specified byte array starting at offset off to this byte array output stream.\n * @param b the data.\n * @param off the start offset in the data.\n * @param len the number of bytes to write.\n */\n", "end_lineno": "129", "file_content": "/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.\n *\n * The contents of this file are subject to the terms of either the GNU\n * General Public License Version 2 only (\"GPL\") or the Common Development\n * and Distribution License(\"CDDL\") (collectively, the \"License\"). You\n * may not use this file except in compliance with the License. You can obtain\n * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html\n * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific\n * language governing permissions and limitations under the License.\n *\n * When distributing the software, include this License Header Notice in each\n * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.\n * Sun designates this particular file as subject to the \"Classpath\" exception\n * as provided by Sun in the GPL Version 2 section of the License file that\n * accompanied this code. If applicable, add the following below the License\n * Header, with the fields enclosed by brackets [] replaced by your own\n * identifying information: \"Portions Copyrighted [year]\n * [name of copyright owner]\"\n *\n * Contributor(s):\n *\n * If you wish your version of this file to be governed by only the CDDL or\n * only the GPL Version 2, indicate your decision by adding \"[Contributor]\n * elects to include this software in this distribution under the [CDDL or GPL\n * Version 2] license.\" If you don't indicate a single choice of license, a\n * recipient has the option to distribute your version of this file under\n * either the CDDL, the GPL Version 2 or to extend the choice of license to\n * its licensees as provided above. However, if you add GPL Version 2 code\n * and therefore, elected the GPL Version 2 license, then the option applies\n * only if the new code is made subject to such option by the copyright\n * holder.\n */\n/*\n * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com)\n * All rights reserved.\n */\npackage net.hasor.utils.io.output;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.Writer;\n\n/**\n *

Provides a mechanism to accept and Base64 encode bytes into\n * chars which will be flushed to the provided writer as the\n * internal buffer fills.

\n */\npublic class Base64OutputStream extends OutputStream {\n /**\n * The buffer where data is stored. \n */\n private byte[] buf;\n /**\n *

The Base64 encoded bytes as chars; essentially the output\n * buffer

\n */\n private char[] chars;\n /**\n * The number of valid bytes in the buffer. \n */\n private int count;\n /**\n *

The current position within chars\n */\n private int encCount;\n /**\n *

Tracks the total number of characters written.

\n */\n private int totalCharsWritten;\n /**\n * The writer we'll flush the bytes to instead of growing\n * the array.\n */\n private Writer writer;\n private static final char[] CA = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".toCharArray();\n\n /**\n * Creates a new byte array output stream, with a buffer capacity of\n * the specified size, in bytes.\n *\n * @param size the initial size.\n * @param writer the writer we'll flush to once\n * we reach our capacity\n *\n * @throws IllegalArgumentException if size is negative.\n */\n public Base64OutputStream(final int size, final Writer writer) {\n if (size < 0) {\n throw new IllegalArgumentException(\"Negative initial size: \" + size);\n }\n this.buf = new byte[size];\n this.chars = new char[size];\n this.totalCharsWritten = 0;\n this.writer = writer;\n }\n\n /**\n * Writes the specified byte to this byte array output stream.\n *\n * @param b the byte to be written.\n */\n @Override\n public void write(final int b) throws IOException {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Writes len bytes from the specified byte array\n * starting at offset off to this byte array output stream.\n *\n * @param b the data.\n * @param off the start offset in the data.\n * @param len the number of bytes to write.\n */\n @Override\n public void write(final byte b[], final int off, final int len) throws IOException {\n if (off < 0 || off > b.length || len < 0 || off + len > b.length || off + len < 0) {\n throw new IndexOutOfBoundsException();\n } else if (len == 0) {\n return;\n }\n if (this.count + len > this.buf.length) {\n this.encodePendingBytes(false);\n }\n System.arraycopy(b, off, this.buf, this.count, len);\n this.count += len;\n }\n\n /**\n *

Calls through to {@link #write(byte[], int, int)}/

\n * @param b the bytes to write\n * @throws IOException if an error occurs\n */\n @Override\n public void write(final byte b[]) throws IOException {\n this.write(b, 0, b.length);\n }\n\n /** Closing Base64OutputStreamWriter does nothing. */\n @Override\n public void close() throws IOException {\n }\n\n /**\n *

Encodes the remaining bytes and flushes the char[]\n * to the wrapped Writer.

\n *\n * @throws IOException if an error occurs writing the remaining bytes\n */\n public void finish() throws IOException {\n this.encodePendingBytes(true);\n }\n\n /**\n * @return the total number of characters written\n */\n public int getTotalCharsWritten() {\n return this.totalCharsWritten;\n }\n\n /**\n *

Base64 encode any bytes found in buf and \n * store the result as characters in chars. This method\n * will automatically write the contents of chars when\n * necessary.\n * @param pad flag to signal we're finalizing the encoding processes.\n * @throws IOException if an error occurs \n */\n private void encodePendingBytes(final boolean pad) throws IOException {\n int eLen = this.count / 3 * 3; // Length of even 24-bits.\n for (int s = 0; s < eLen; ) {\n // Copy next three bytes into lower 24 bits of int, paying attension to sign.\n int i = (this.buf[s++] & 0xff) << 16 | (this.buf[s++] & 0xff) << 8 | this.buf[s++] & 0xff;\n if (this.encCount + 4 > this.chars.length) {\n // we're full, so write the encoded chars\n // and reset the pointer\n this.drainCharBuffer();\n }\n // Encode the int into four chars \n this.chars[this.encCount++] = Base64OutputStream.CA[i >>> 18 & 0x3f];\n this.chars[this.encCount++] = Base64OutputStream.CA[i >>> 12 & 0x3f];\n this.chars[this.encCount++] = Base64OutputStream.CA[i >>> 6 & 0x3f];\n this.chars[this.encCount++] = Base64OutputStream.CA[i & 0x3f];\n }\n int left = this.count - eLen;\n if (!pad) {\n // push the non-encoded bytes to the beginning of the byte array\n // and set count to the end of those bytes\n System.arraycopy(this.buf, eLen, this.buf, 0, left);\n this.count = left;\n } else {\n this.drainCharBuffer();\n // pad if necessary\n if (left > 0) {\n // Prepare the int\n int i = (this.buf[eLen] & 0xff) << 10 | (left == 2 ? (this.buf[this.count - 1] & 0xff) << 2 : 0);\n // write last four chars\n this.writer.write(Base64OutputStream.CA[i >> 12]);\n this.writer.write(Base64OutputStream.CA[i >>> 6 & 0x3f]);\n this.writer.write(left == 2 ? Base64OutputStream.CA[i & 0x3f] : '=');\n this.writer.write('=');\n }\n }\n }\n\n /**\n *

Write the contents of chars to the\n * wrapped Writer and reset encCount\n * to zero.

\n * @throws IOException if an error occurs\n */\n private void drainCharBuffer() throws IOException {\n this.writer.write(this.chars, 0, this.encCount);\n this.totalCharsWritten += this.encCount;\n this.encCount = 0;\n }\n // Test Case: com.sun.faces.io.TestIO\n} // END Base64OutputStreamWriter\n", "file_name": "Base64OutputStream.java", "human_label": "Write bytes of length len from a byte array", "level": "class_runnable", "lineno": "109", "name": "write", "oracle_context": "{ \"apis\" : \"[encodePendingBytes, arraycopy]\", \"classes\" : \"[]\", \"vars\" : \"[length, count, buf]\" }", "package": "net.hasor.utils.io.output", "project": "hasor-master" }, { "_id": "636767551a6d9265ec017f3f", "all_context": "{ \"class_level\" : \"ArrayUtil();\\nreverse(int[] arr,int from,int to);\\nswap(V[] arr,int i,int j);\\nreverse(V[] arr,int from,int to);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtil", "code": "public static final void swap(V[] arr,int i,int j){\n V tmp=arr[j];\n arr[j]=arr[i];\n arr[i]=tmp;\n}\n", "docstring": "/** \n * Swaps the two elements at the specified indices in the given array.\n * @param < V > the type of elements in the array\n * @param arr the array\n * @param i the index of the first element\n * @param j the index of the second element\n */\n", "end_lineno": "76", "file_content": "/*\n * (C) Copyright 2021-2021, by Hannes Wellmann and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.util;\n\n/**\n * Utility class to simplify handling of arrays.\n *\n * @author Hannes Wellmann\n *\n */\npublic class ArrayUtil\n{\n private ArrayUtil()\n { // static use only\n }\n\n /**\n * Reverses the order of the elements in the specified range within the given array.\n *\n * @param the type of elements in the array\n * @param arr the array\n * @param from the index of the first element (inclusive) inside the range to reverse\n * @param to the index of the last element (inclusive) inside the range to reverse\n */\n public static final void reverse(V[] arr, int from, int to)\n {\n for (int i = from, j = to; i < j; ++i, --j) {\n swap(arr, i, j);\n }\n }\n\n /**\n * Reverses the order of the elements in the specified range within the given array.\n *\n * @param arr the array\n * @param from the index of the first element (inclusive) inside the range to reverse\n * @param to the index of the last element (inclusive) inside the range to reverse\n */\n public static final void reverse(int[] arr, int from, int to)\n {\n for (int i = from, j = to; i < j; ++i, --j) {\n int tmp = arr[j];\n arr[j] = arr[i];\n arr[i] = tmp;\n }\n }\n\n /**\n * Swaps the two elements at the specified indices in the given array.\n *\n * @param the type of elements in the array\n * @param arr the array\n * @param i the index of the first element\n * @param j the index of the second element\n */\n public static final void swap(V[] arr, int i, int j)\n {\n V tmp = arr[j];\n arr[j] = arr[i];\n arr[i] = tmp;\n }\n}\n", "file_name": "ArrayUtil.java", "human_label": "Swap values at indexes i and j in arr", "level": "self_contained", "lineno": "63", "name": "swap", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[V]\", \"vars\" : \"[]\" }", "package": "org.jgrapht.util", "project": "jgrapht-master" }, { "_id": "636766ae1a6d9265ec0175dc", "all_context": "{ \"class_level\" : \"import java.util.List;\\nimport java.util.Map;\\nimport java.util.concurrent.ConcurrentHashMap;\\nimport java.util.logging.Logger;\\nimport javax.enterprise.context.RequestScoped;\\nimport javax.inject.Inject;\\nimport javax.ws.rs.container.ContainerResponseContext;\\nimport javax.ws.rs.container.ResourceInfo;\\nimport javax.ws.rs.core.HttpHeaders;\\nimport javax.ws.rs.core.UriInfo;\\nimport org.demoiselle.jee.crud.AbstractDAO;\\nimport org.demoiselle.jee.crud.CrudUtilHelper;\\nimport org.demoiselle.jee.crud.DemoiselleRequestContext;\\nimport org.demoiselle.jee.crud.ReservedHTTPHeaders;\\nimport org.demoiselle.jee.crud.ReservedKeyWords;\\nimport org.demoiselle.jee.crud.Search;\\nUriInfo uriInfo;\\nResourceInfo resourceInfo;\\nDemoiselleRequestContext drc;\\nPaginationHelperMessage message;\\nPaginationHelperConfig paginationConfig;\\nLogger logger;\\nPaginationHelper();\\nPaginationHelper(ResourceInfo resourceInfo,UriInfo uriInfo,PaginationHelperConfig paginationConfig,DemoiselleRequestContext drc,PaginationHelperMessage message);\\nfillObjects(ResourceInfo resourceInfo,UriInfo uriInfo);\\nisPaginationEnabled();\\nisRequestPagination();\\ncheckAndFillRangeValues();\\ngetDefaultNumberPagination();\\nhasSearchAnnotation();\\nisPartialContentResponse();\\nlogInvalidRangeParameters(String range);\\nbuildContentRange();\\nbuildAcceptRange();\\nbuildHeaders(ResourceInfo resourceInfo,UriInfo uriInfo);\\nbuildLinkHeader();\\nisFirstPage();\\nbuildAcceptRangeWithResponse(ContainerResponseContext response);\\nexecute(ResourceInfo resourceInfo,UriInfo uriInfo);\\n\", \"repo_level\" : \"public interface AbstractDAO {abstract EntityManager getEntityManager();\\npublic T persist(T entity);\\npublic T mergeHalf(I id,T entity);\\npublic T mergeFull(T entity);\\npublic void remove(I id);\\npublic T find(I id);\\npublic Result find();\\nprotected void configureCriteriaQuery(CriteriaBuilder criteriaBuilder,CriteriaQuery criteriaQuery);\\nprotected void configureOrder(CriteriaBuilder criteriaBuilder,CriteriaQuery criteriaQuery,Root root);\\nprotected Predicate[] buildPredicates(CriteriaBuilder criteriaBuilder,CriteriaQuery criteriaQuery,Root root);\\nprotected Boolean isEnumFilter(String key,String value,TreeNodeField tnf);\\nprotected Boolean isUUIDFilter(String key,String value,TreeNodeField tnf);\\nprotected Integer convertEnumToInt(String key,String value,TreeNodeField tnf);\\nprotected Boolean isLikeFilter(String value);\\nprotected Predicate buildLikePredicate(CriteriaBuilder criteriaBuilder,CriteriaQuery criteriaQuery,From root,String key,String value);\\nprotected Integer getMaxResult();\\npublic Long count();\\nprotected Predicate[] extractPredicates(MultivaluedMap queryParameters,CriteriaBuilder criteriaBuilder,Root root);\\npublic PaginationHelperConfig getPaginationConfig();\\npublic DemoiselleRequestContext getDrc();\\npublic Class getEntityClass();\\n }\\npublic interface CrudUtilHelper {static Class getTargetClass(Class targetClass);\\nstatic void checkIfExistField(Class targetClass,String field);\\nstatic List getAllFields(List fields,Class type);\\nstatic Field getField(Class targetClass,String name);\\nstatic List extractFields(String fields);\\nstatic TreeNodeField> extractFieldsFromSearchAnnotation(ResourceInfo resourceInfo);\\nstatic void fillLeafTreeNodeField(TreeNodeField tnf,String field,Set value);\\nstatic void validateFields(TreeNodeField tnf,ResourceInfo resourceInfo,CrudMessage crudMessage);\\nstatic String getMethodAnnotatedWithID(Class targetClass);\\n }\\npublic interface DemoiselleRequestContext { Integer getLimit();\\n void setLimit(Integer limit);\\n Integer getOffset();\\n void setOffset(Integer offset);\\n Long getCount();\\n void setCount(Long count);\\n Class getEntityClass();\\n void setEntityClass(Class entityClass);\\n TreeNodeField> getFilters();\\n void setFilters(TreeNodeField filters);\\n List getSorts();\\n void setSorts(List sorts);\\n TreeNodeField> getFields();\\n void setFields(TreeNodeField fields);\\n Boolean isPaginationEnabled();\\n void setPaginationEnabled(Boolean isPaginationEnabled);\\n }\\n\" }", "class_name": "PaginationHelper", "code": "public Boolean isPartialContentResponse(){\n Integer limit=drc.getLimit() == null ? 0 : drc.getLimit();\n Long count=drc.getCount() == null ? 0 : drc.getCount();\n return !((limit + 1) >= count);\n}\n", "docstring": "/** \n * Check if the actual response is a Partial Content (HTTP 206 code)\n * @return is partial content or not\n */\n", "end_lineno": "219", "file_content": "/*\n * Demoiselle Framework\n *\n * License: GNU Lesser General Public License (LGPL), version 3 or later.\n * See the lgpl.txt file in the root directory or .\n */\npackage org.demoiselle.jee.crud.pagination;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.logging.Logger;\n\nimport javax.enterprise.context.RequestScoped;\nimport javax.inject.Inject;\nimport javax.ws.rs.container.ContainerResponseContext;\nimport javax.ws.rs.container.ResourceInfo;\nimport javax.ws.rs.core.HttpHeaders;\nimport javax.ws.rs.core.UriInfo;\n\nimport org.demoiselle.jee.crud.AbstractDAO;\nimport org.demoiselle.jee.crud.CrudUtilHelper;\nimport org.demoiselle.jee.crud.DemoiselleRequestContext;\nimport org.demoiselle.jee.crud.ReservedHTTPHeaders;\nimport org.demoiselle.jee.crud.ReservedKeyWords;\nimport org.demoiselle.jee.crud.Search;\n\n/**\n * Class responsible for managing the 'range' parameter comes from Url Query\n * String.\n *\n * Ex:\n *\n * Given a request\n *
\n * GET @{literal http://localhost:8080/api/users?range=0-10}\n * 
\n *\n * This class will processing the request above and parse the range parameters\n * to {@link DemoiselleRequestContext} object.\n *\n * This object will be use on {@link AbstractDAO} class to execute the\n * pagination on database.\n *\n */\n@RequestScoped\npublic class PaginationHelper {\n\n private UriInfo uriInfo;\n\n private ResourceInfo resourceInfo;\n\n @Inject\n private DemoiselleRequestContext drc;\n\n @Inject\n private PaginationHelperMessage message;\n\n @Inject\n private PaginationHelperConfig paginationConfig;\n\n private static final Logger logger = Logger.getLogger(PaginationHelper.class.getName());\n\n public PaginationHelper() {\n }\n\n public PaginationHelper(ResourceInfo resourceInfo, UriInfo uriInfo, PaginationHelperConfig paginationConfig, DemoiselleRequestContext drc, PaginationHelperMessage message) {\n this.resourceInfo = resourceInfo;\n this.uriInfo = uriInfo;\n this.paginationConfig = paginationConfig;\n this.drc = drc;\n this.message = message;\n }\n\n /**\n * Open the request query string to extract values from 'range' parameter\n * and fill the {@link DemoiselleRequestContext#setOffset(Integer)} and\n * {@link DemoiselleRequestContext#setLimit(Integer)}\n *\n * @param resourceInfo ResourceInfo\n * @param uriInfo UriInfo\n */\n public void execute(ResourceInfo resourceInfo, UriInfo uriInfo) {\n fillObjects(resourceInfo, uriInfo);\n\n drc.setPaginationEnabled(isPaginationEnabled());\n\n if (drc.isPaginationEnabled()) {\n\n if (isRequestPagination()) {\n checkAndFillRangeValues();\n }\n\n if (hasSearchAnnotation() && !isRequestPagination()) {\n drc.setLimit(getDefaultNumberPagination() - 1);\n drc.setOffset(new Integer(0));\n }\n }\n\n if (hasSearchAnnotation() && isRequestPagination()) {\n Search searchAnnotation = resourceInfo.getResourceMethod().getAnnotation(Search.class);\n // Pagination @Search.withPagination is disabled but the request parameter has 'range' parameter\n if (searchAnnotation.withPagination() == Boolean.FALSE) {\n throw new IllegalArgumentException(message.paginationIsNotEnabled());\n }\n }\n }\n\n private void fillObjects(ResourceInfo resourceInfo, UriInfo uriInfo) {\n this.resourceInfo = resourceInfo == null ? this.resourceInfo : resourceInfo;\n this.uriInfo = uriInfo == null ? this.uriInfo : uriInfo;\n }\n\n /**\n * Check the pagination is enabled\n *\n * @return pagination enabled/disabled\n */\n private Boolean isPaginationEnabled() {\n if (paginationConfig.getIsGlobalEnabled() == Boolean.FALSE) {\n return Boolean.FALSE;\n }\n\n if (hasSearchAnnotation()) {\n Search searchAnnotation = resourceInfo.getResourceMethod().getAnnotation(Search.class);\n return searchAnnotation.withPagination();\n }\n\n return paginationConfig.getIsGlobalEnabled();\n }\n\n /**\n * Check if the actual request has the 'range' parameter on query string\n *\n * @return is request pagination or not\n */\n private Boolean isRequestPagination() {\n // Verify if contains 'range' in url\n if (uriInfo.getQueryParameters().containsKey(ReservedKeyWords.DEFAULT_RANGE_KEY.getKey())) {\n return Boolean.TRUE;\n }\n return Boolean.FALSE;\n }\n\n /**\n * Check if the value of 'range' parameter is valid using the rules:\n *\n * - Value formatted like offset-limit (range=0-10); - The 'offset' and\n * 'limit' should be a integer; - The 'offset' should be less than or equals\n * 'limit';\n *\n *\n * @throws IllegalArgumentException The format is invalid\n */\n private void checkAndFillRangeValues() throws IllegalArgumentException {\n List rangeList = uriInfo.getQueryParameters().get(ReservedKeyWords.DEFAULT_RANGE_KEY.getKey());\n if (!rangeList.isEmpty()) {\n String range[] = rangeList.get(0).split(\"-\");\n if (range.length == 2) {\n String offset = range[0];\n String limit = range[1];\n\n try {\n drc.setOffset(new Integer(offset));\n drc.setLimit(new Integer(limit));\n\n if (drc.getOffset() > drc.getLimit()) {\n logInvalidRangeParameters(rangeList.get(0));\n throw new IllegalArgumentException(this.message.invalidRangeParameters());\n }\n\n if (((drc.getLimit() - drc.getOffset()) + 1) > getDefaultNumberPagination()) {\n logger.warning(message.defaultPaginationNumberExceed(getDefaultNumberPagination()) + \", [\" + drc.toString() + \"]\");\n throw new IllegalArgumentException(message.defaultPaginationNumberExceed(getDefaultNumberPagination()));\n }\n\n } catch (NumberFormatException nfe) {\n logInvalidRangeParameters(rangeList.get(0));\n throw new IllegalArgumentException(message.invalidRangeParameters());\n }\n } else {\n logInvalidRangeParameters(rangeList.get(0));\n throw new IllegalArgumentException(message.invalidRangeParameters());\n }\n }\n\n }\n\n /**\n * Get default pagination number, if the target method is annotated with\n * Search annotation the default annotation will be\n * {@link Search#quantityPerPage()} otherwise the default pagination will be\n * {@link PaginationHelperConfig#getDefaultPagination()} value;\n *\n * @return Number per page\n */\n private Integer getDefaultNumberPagination() {\n if (hasSearchAnnotation()) {\n Search searchAnnotation = resourceInfo.getResourceMethod().getAnnotation(Search.class);\n return searchAnnotation.quantityPerPage();\n }\n\n return paginationConfig.getDefaultPagination();\n }\n\n private Boolean hasSearchAnnotation() {\n return resourceInfo.getResourceMethod().isAnnotationPresent(Search.class);\n }\n\n /**\n * Check if the actual response is a Partial Content (HTTP 206 code)\n *\n * @return is partial content or not\n */\n public Boolean isPartialContentResponse() {\n Integer limit = drc.getLimit() == null ? 0 : drc.getLimit();\n Long count = drc.getCount() == null ? 0 : drc.getCount();\n return !((limit + 1) >= count);\n }\n\n private void logInvalidRangeParameters(String range) {\n logger.warning(message.invalidRangeParameters() + \", [params: \" + range + \"]\");\n }\n\n /**\n * Build the 'Content-Range' HTTP Header value.\n *\n * @return 'Content-Range' value\n */\n private String buildContentRange() {\n Integer limit = drc.getLimit() == null ? getDefaultNumberPagination() - 1 : drc.getLimit();\n Integer offset = drc.getOffset() == null ? 0 : drc.getOffset();\n Long count = drc.getCount() == null ? 0 : drc.getCount();\n return offset + \"-\" + (limit.equals(0) ? count - 1 : limit) + \"/\" + count;\n }\n\n /**\n * Build the 'Accept-Range' HTTP Header value.\n *\n * @return 'Accept-Range' value\n */\n public String buildAcceptRange() {\n String resource = \"\";\n\n if (drc.getEntityClass() != null) {\n resource = drc.getEntityClass().getSimpleName().toLowerCase();\n } else {\n if (resourceInfo != null && resourceInfo.getResourceClass() != null) {\n Class targetClass = CrudUtilHelper.getTargetClass(resourceInfo.getResourceClass());\n if (targetClass != null) {\n resource = targetClass.getSimpleName().toLowerCase();\n }\n }\n }\n\n if (!resource.isEmpty()) {\n return resource + \" \" + getDefaultNumberPagination();\n }\n\n return null;\n }\n\n /**\n * Set the 'Content-Range', 'Accept-Range', 'Link' and\n * 'Access-Control-Expose-Headers' HTTP headers;\n *\n * @param resourceInfo ResourceInfo\n * @param uriInfo UriInfo\n *\n * @return A map with HTTP headers\n */\n public Map buildHeaders(ResourceInfo resourceInfo, UriInfo uriInfo) {\n fillObjects(resourceInfo, uriInfo);\n Map headers = new ConcurrentHashMap<>();\n\n if (drc.isPaginationEnabled()) {\n headers.putIfAbsent(ReservedHTTPHeaders.HTTP_HEADER_CONTENT_RANGE.getKey(), buildContentRange());\n headers.putIfAbsent(ReservedHTTPHeaders.HTTP_HEADER_ACCEPT_RANGE.getKey(), buildAcceptRange());\n String linkHeader = buildLinkHeader();\n\n if (!linkHeader.isEmpty()) {\n headers.putIfAbsent(HttpHeaders.LINK, linkHeader);\n }\n }\n\n return headers;\n }\n\n /**\n * Build the 'Link' HTTP header value\n *\n * @return 'Link' value\n */\n private String buildLinkHeader() {\n StringBuffer sb = new StringBuffer();\n String url = uriInfo.getRequestUri().toString();\n url = url.replaceFirst(\".range=([^&]*)\", \"\");\n\n if (drc.getOffset() == null) {\n drc.setOffset(new Integer(0));\n }\n\n if (drc.getLimit() == null) {\n drc.setLimit(getDefaultNumberPagination() - 1);\n }\n\n Integer offset = drc.getOffset() + 1;\n Integer limit = drc.getLimit() + 1;\n Integer quantityPerPage = (limit - offset) + 1;\n\n if (uriInfo.getQueryParameters().isEmpty()\n || (uriInfo.getQueryParameters().size() == 1 && uriInfo.getQueryParameters().containsKey(ReservedKeyWords.DEFAULT_RANGE_KEY.getKey()))) {\n url += \"?\" + ReservedKeyWords.DEFAULT_RANGE_KEY.getKey() + \"=\";\n } else {\n url += \"&\" + ReservedKeyWords.DEFAULT_RANGE_KEY.getKey() + \"=\";\n }\n\n if (!isFirstPage()) {\n Integer prevPageRangeInit = (drc.getOffset() - quantityPerPage) < 0 ? 0 : (drc.getOffset() - quantityPerPage);\n Integer firstRange2 = quantityPerPage - 1 < drc.getOffset() - 1 ? quantityPerPage - 1 : drc.getOffset() - 1;\n\n String firstPage = url + 0 + \"-\" + firstRange2;\n String prevPage = url + prevPageRangeInit + \"-\" + (drc.getOffset() - 1);\n\n sb.append(\"<\").append(firstPage).append(\">; rel=\\\"first\\\",\");\n sb.append(\"<\").append(prevPage).append(\">; rel=\\\"prev\\\",\");\n }\n\n if (isPartialContentResponse()) {\n String nextPage = url + (drc.getOffset() + quantityPerPage) + \"-\" + (2 * quantityPerPage + drc.getOffset() - 1);\n String lastPage = url + (drc.getCount() - quantityPerPage) + \"-\" + (drc.getCount() - 1);\n\n if (offset + quantityPerPage >= drc.getCount() - 1) {\n nextPage = lastPage;\n }\n\n sb.append(\"<\").append(nextPage).append(\">; rel=\\\"next\\\",\");\n sb.append(\"<\").append(lastPage).append(\">; rel=\\\"last\\\"\");\n }\n\n return sb.toString();\n }\n\n private Boolean isFirstPage() {\n return drc.getOffset().equals(0);\n }\n\n public void buildAcceptRangeWithResponse(ContainerResponseContext response) {\n if (response != null) {\n String acceptRangeHeader = buildAcceptRange();\n if (acceptRangeHeader != null) {\n response.getHeaders().putSingle(ReservedHTTPHeaders.HTTP_HEADER_ACCEPT_RANGE.getKey(), acceptRangeHeader);\n }\n }\n\n }\n\n}\n", "file_name": "PaginationHelper.java", "human_label": "Determine whether the actual response is a Partial Content", "level": "plib_runnable", "lineno": "210", "name": "isPartialContentResponse", "oracle_context": "{ \"apis\" : \"[getLimit, getCount]\", \"classes\" : \"[Integer, Long]\", \"vars\" : \"[drc]\" }", "package": "org.demoiselle.jee.crud.pagination", "project": "framework-master" }, { "_id": "636766f01a6d9265ec01762e", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static boolean isEmpty(final double[] array){\n return array == null || array.length == 0;\n}\n", "docstring": "/** \n *

Checks if an array of primitive doubles is empty or null.

\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n", "end_lineno": "3130", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

\n *\n *

This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

\n *\n *

#ThreadSafe#

\n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

\n *\n *

This method can be used to initialize:

\n *
\n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
\n *\n *

This method returns null for a null input array.

\n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

Shallow clones an array returning a typecast result and handling\n * null.

\n *\n *

The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

Produces a new array containing the elements between\n * the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n *

The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

\n *\n *
\n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new long array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new int array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new short array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new char array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new byte array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new double array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new float array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new boolean array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

Any multi-dimensional aspects of the arrays are ignored.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

\n *\n *

If the input array is null, 0 is returned.

\n *\n *
\n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
\n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

\n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

Reverses the order of the given array.

\n *\n *

There is no special handling for multi-dimensional arrays.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given object in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

Finds the index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given object within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the object is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

\n *\n *

The method returns false if a null array\n * is passed in.

\n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Characters to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Character to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive chars to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Longs to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Long to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive longs to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Integers to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Integer to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive ints to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Shorts to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Short to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive shorts to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Bytes to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Bytes to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive bytes to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Doubles to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Doubles to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive doubles to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Floats to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Floats to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive floats to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Booleans to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Booleans to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive booleans to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive longs is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive ints is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive chars is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive floats is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive longs is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive ints is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive chars is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive floats is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

\n *\n *
\n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Check whether the array of the double type is empty.", "level": "self_contained", "lineno": "3121", "name": "isEmpty", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[length]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "6367667e1a6d9265ec01743a", "all_context": "{ \"class_level\" : \"import org.atmosphere.cpr.ApplicationConfig;\\nimport org.atmosphere.cpr.AsyncIOWriter;\\nimport org.atmosphere.cpr.AtmosphereConfig;\\nimport org.atmosphere.cpr.AtmosphereInterceptorWriter;\\nimport org.atmosphere.cpr.AtmosphereRequest;\\nimport org.atmosphere.cpr.AtmosphereRequestImpl;\\nimport org.atmosphere.cpr.AtmosphereResource;\\nimport org.atmosphere.cpr.AtmosphereResourceImpl;\\nimport org.atmosphere.cpr.AtmosphereResponse;\\nimport org.atmosphere.cpr.KeepOpenStreamAware;\\nimport org.atmosphere.util.ByteArrayAsyncWriter;\\nimport org.slf4j.Logger;\\nimport org.slf4j.LoggerFactory;\\nimport java.io.IOException;\\nimport java.nio.Buffer;\\nimport java.nio.ByteBuffer;\\nimport java.nio.CharBuffer;\\nimport java.nio.charset.StandardCharsets;\\nimport java.util.Map;\\nimport java.util.concurrent.ConcurrentHashMap;\\nimport java.util.concurrent.atomic.AtomicBoolean;\\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_ERROR;\\nLogger logger;\\nString WEBSOCKET_INITIATED;\\nString WEBSOCKET_SUSPEND;\\nString WEBSOCKET_RESUME;\\nString WEBSOCKET_ACCEPT_DONE;\\nString NOT_SUPPORTED;\\nString CLEAN_CLOSE;\\nAtmosphereResource r;\\nlong lastWrite;\\nboolean binaryWrite;\\nAtomicBoolean firstWrite;\\nAtmosphereConfig config;\\nWebSocketHandler webSocketHandler;\\nByteBuffer bb;\\nCharBuffer cb;\\nString uuid;\\nMap attributesAtWebSocketOpen;\\nObject attachment;\\nWebSocket(AtmosphereConfig config);\\nconfig();\\nwebSocketHandler(WebSocketHandler webSocketHandler);\\nwebSocketHandler();\\nresource(AtmosphereResource r);\\nshiftAttributes();\\nattributes();\\nresource();\\nlastWriteTimeStampInMilliseconds();\\ntransform(byte[] b,int offset,int length);\\ntransform(AtmosphereResponse response,byte[] b,int offset,int length);\\nwrite(AtmosphereResponse r,String data);\\nwrite(AtmosphereResponse r,byte[] data);\\nwrite(AtmosphereResponse r,byte[] b,int offset,int length);\\nbroadcast(Object o);\\nwriteError(AtmosphereResponse r,int errorCode,String message);\\nredirect(AtmosphereResponse r,String location);\\nclose(AtmosphereResponse r);\\nflush(AtmosphereResponse r);\\nisOpen();\\nwrite(String s);\\nwrite(byte[] b,int offset,int length);\\nwrite(byte[] b);\\nclose();\\nclose(int statusCode,String reasonText);\\nuuid();\\nnotSupported(AtmosphereRequest request,AtmosphereResponse response);\\nsendPing(byte[] payload);\\nsendPong(byte[] payload);\\nattachment(Object attachment);\\nattachment();\\nbinaryWrite(boolean binaryWrite);\\n\", \"repo_level\" : \"public interface ApplicationConfig { }\\npublic interface AsyncIOWriter { AsyncIOWriter redirect(AtmosphereResponse r,String location);\\n AsyncIOWriter writeError(AtmosphereResponse r,int errorCode,String message);\\n AsyncIOWriter write(AtmosphereResponse r,String data);\\n AsyncIOWriter write(AtmosphereResponse r,byte[] data);\\n AsyncIOWriter write(AtmosphereResponse r,byte[] data,int offset,int length);\\n void close(AtmosphereResponse r);\\n AsyncIOWriter flush(AtmosphereResponse r);\\n }\\npublic interface AtmosphereConfig {public List getAtmosphereHandlerConfig();\\npublic AtmosphereFramework framework();\\npublic ServletConfig getServletConfig();\\npublic ServletContext getServletContext();\\npublic String getWebServerName();\\npublic Map handlers();\\npublic String getInitParameter(String name);\\npublic Enumeration getInitParameterNames();\\npublic boolean isSupportSession();\\npublic void setSupportSession(boolean supportSession);\\npublic boolean isSessionTimeoutRemovalAllowed();\\npublic void setSessionTimeoutRemovalAllowed(boolean sessionTimeoutRemovalAllowed);\\npublic boolean isThrowExceptionOnCloned();\\npublic void setThrowExceptionOnCloned(boolean throwExceptionOnCloned);\\npublic BroadcasterFactory getBroadcasterFactory();\\npublic Map properties();\\nprotected void destroy();\\nprotected void initComplete();\\npublic AtmosphereConfig shutdownHook(ShutdownHook s);\\npublic AtmosphereConfig startupHook(StartupHook s);\\npublic String getInitParameter(String key,String defaultValue);\\npublic boolean getInitParameter(String key,boolean defaultValue);\\npublic int getInitParameter(String key,int defaultValue);\\npublic AtmosphereResourceFactory resourcesFactory();\\npublic MetaBroadcaster metaBroadcaster();\\npublic AtmosphereResourceSessionFactory sessionFactory();\\npublic UUIDProvider uuidProvider();\\npublic WebSocketFactory websocketFactory();\\n void shutdown();\\n void started(AtmosphereFramework framework);\\npublic AtmosphereConfig populate(AtmosphereConfig config);\\n }\\npublic interface AtmosphereInterceptorWriter {public AsyncIOWriter redirect(AtmosphereResponse response,String location);\\npublic AsyncIOWriter writeError(AtmosphereResponse response,int errorCode,String message);\\npublic AsyncIOWriter write(AtmosphereResponse response,String data);\\npublic AsyncIOWriter write(AtmosphereResponse response,byte[] data);\\npublic AsyncIOWriter write(AtmosphereResponse response,byte[] data,int offset,int length);\\nprotected void invokeInterceptor(AtmosphereResponse response,byte[] data,int offset,int length);\\nprotected void writeReady(AtmosphereResponse response,byte[] responseDraft);\\npublic void close(AtmosphereResponse response);\\npublic AsyncIOWriter flush(AtmosphereResponse response);\\npublic AtmosphereInterceptorWriter interceptor(AsyncIOInterceptor filter);\\npublic AtmosphereInterceptorWriter interceptor(AsyncIOInterceptor filter,int index);\\npublic LinkedList filters();\\n }\\npublic interface AtmosphereRequest { boolean destroyed();\\n AtmosphereRequest destroyable(boolean destroyable);\\n String getPathInfo();\\n String getPathTranslated();\\n String getQueryString();\\n String getRemoteUser();\\n String getRequestedSessionId();\\n String getMethod();\\n Part getPart(String name);\\n Collection getParts();\\n String getContentType();\\n DispatcherType getDispatcherType();\\n String getServletPath();\\n String getRequestURI();\\n StringBuffer getRequestURL();\\n Enumeration getHeaders(String name);\\n int getIntHeader(String name);\\n Enumeration getHeaderNames();\\n boolean authenticate(HttpServletResponse response);\\n String getAuthType();\\n String getContextPath();\\n Cookie[] getCookies();\\n long getDateHeader(String name);\\n String getHeader(String s);\\n HttpServletRequest wrappedRequest();\\n String getHeader(String s,boolean checkCase);\\n String getParameter(String s);\\n Map getParameterMap();\\n Enumeration getParameterNames();\\n String[] getParameterValues(String s);\\n String getProtocol();\\n ServletInputStream getInputStream();\\n BufferedReader getReader();\\n String getRealPath(String path);\\n AtmosphereRequest headers(Map headers);\\n AtmosphereRequest header(String name,String value);\\n AtmosphereRequest queryString(String qs);\\n Map headersMap();\\n Map queryStringsMap();\\n AtmosphereRequest method(String m);\\n AtmosphereRequest contentType(String m);\\n AtmosphereRequest body(String body);\\n AtmosphereRequest body(byte[] bytes);\\n AtmosphereRequest body(InputStream body);\\n AtmosphereRequest body(Reader body);\\n AtmosphereRequestImpl.Body body();\\n AtmosphereRequest servletPath(String servletPath);\\n AtmosphereRequest contextPath(String contextPath);\\n AtmosphereRequest requestURI(String requestURI);\\n void setAttribute(String s,Object o);\\n void setCharacterEncoding(String env);\\n AsyncContext startAsync();\\n AsyncContext startAsync(ServletRequest request,ServletResponse response);\\n AsyncContext getAsyncContext();\\n Object getAttribute(String s);\\n void removeAttribute(String name);\\n LocalAttributes attributes();\\n HttpSession getSession();\\n HttpSession getSession(boolean create);\\n Principal getUserPrincipal();\\n boolean isRequestedSessionIdFromCookie();\\n boolean isRequestedSessionIdFromUrl();\\n boolean isRequestedSessionIdFromURL();\\n boolean isRequestedSessionIdValid();\\n boolean isUserInRole(String role);\\n void login(String username,String password);\\n void logout();\\n String getRemoteAddr();\\n String getRemoteHost();\\n int getRemotePort();\\n RequestDispatcher getRequestDispatcher(String path);\\n String getScheme();\\n String getServerName();\\n int getServerPort();\\n ServletContext getServletContext();\\n boolean isAsyncStarted();\\n boolean isAsyncSupported();\\n boolean isSecure();\\n String getLocalName();\\n int getLocalPort();\\n String getLocalAddr();\\n Locale getLocale();\\n AtmosphereResource resource();\\n Enumeration getLocales();\\n boolean dispatchRequestAsynchronously();\\n boolean isDestroyable();\\n AtmosphereRequest pathInfo(String pathInfo);\\n Enumeration getAttributeNames();\\n LocalAttributes localAttributes();\\n String getCharacterEncoding();\\n int getContentLength();\\n String uuid();\\n void destroy();\\n void destroy(boolean force);\\n void setRequest(ServletRequest request);\\n String toString();\\n String requestURL();\\npublic LocalAttributes put(String s,Object o);\\npublic Object get(String s);\\npublic Object remove(String name);\\npublic Map unmodifiableMap();\\npublic void clear();\\npublic boolean containsKey(String key);\\n Builder destroyable(boolean destroyable);\\n Builder headers(Map headers);\\n Builder cookies(Set cookies);\\n Builder dispatchRequestAsynchronously(boolean dispatchRequestAsynchronously);\\n Builder remoteAddr(String remoteAddr);\\n Builder remoteHost(String remoteHost);\\n Builder remotePort(int remotePort);\\n Builder localAddr(String localAddr);\\n Builder localName(String localName);\\n Builder localPort(int localPort);\\n Builder remoteInetSocketAddress(Callable remoteAddr);\\n Builder localInetSocketAddress(Callable localAddr);\\n Builder attributes(Map attributes);\\n Builder request(HttpServletRequest request);\\n Builder servletPath(String servletPath);\\n Builder requestURI(String requestURI);\\n Builder requestURL(String requestURL);\\n Builder pathInfo(String pathInfo);\\n Builder queryString(String queryString);\\n Builder body(byte[] dataBytes);\\n Builder body(byte[] dataBytes,int offset,int length);\\n Builder encoding(String encoding);\\n Builder method(String methodType);\\n Builder contentType(String contentType);\\n Builder contentLength(Long contentLength);\\n Builder body(String data);\\n Builder inputStream(InputStream inputStream);\\n Builder reader(Reader reader);\\n AtmosphereRequest build();\\n Builder queryStrings(Map queryStrings);\\n Builder contextPath(String contextPath);\\n Builder serverName(String serverName);\\n Builder serverPort(int serverPort);\\n Builder session(HttpSession session);\\n Builder principal(Principal principal);\\n Builder authType(String authType);\\n Builder isSSecure(boolean isSecure);\\n Builder locale(Locale locale);\\n Builder userPrincipal(Principal userPrincipal);\\n }\\npublic interface AtmosphereRequestImpl {public boolean destroyed();\\npublic AtmosphereRequest destroyable(boolean destroyable);\\npublic String getPathInfo();\\npublic String getPathTranslated();\\npublic String getQueryString();\\npublic String getRemoteUser();\\npublic String getRequestedSessionId();\\npublic String getMethod();\\npublic Part getPart(String name);\\npublic Collection getParts();\\npublic String getContentType();\\npublic DispatcherType getDispatcherType();\\npublic String getServletPath();\\npublic String getRequestURI();\\npublic StringBuffer getRequestURL();\\npublic Enumeration getHeaders(String name);\\npublic int getIntHeader(String name);\\npublic Enumeration getHeaderNames();\\npublic boolean authenticate(HttpServletResponse response);\\npublic String getAuthType();\\npublic String getContextPath();\\npublic Cookie[] getCookies();\\npublic long getDateHeader(String name);\\npublic String getHeader(String s);\\npublic HttpServletRequest wrappedRequest();\\npublic String getHeader(String s,boolean checkCase);\\npublic String getParameter(String s);\\npublic Map getParameterMap();\\npublic Enumeration getParameterNames();\\npublic String[] getParameterValues(String s);\\npublic String getProtocol();\\npublic ServletInputStream getInputStream();\\npublic BufferedReader getReader();\\npublic String getRealPath(String path);\\npublic AtmosphereRequest headers(Map headers);\\npublic AtmosphereRequest header(String name,String value);\\npublic AtmosphereRequest queryString(String qs);\\npublic Map headersMap();\\npublic Map queryStringsMap();\\npublic AtmosphereRequest method(String m);\\npublic AtmosphereRequest contentType(String m);\\npublic AtmosphereRequest body(String body);\\npublic AtmosphereRequest body(byte[] bytes);\\npublic AtmosphereRequest body(InputStream body);\\npublic AtmosphereRequest body(Reader body);\\npublic Body body();\\npublic AtmosphereRequest servletPath(String servletPath);\\npublic AtmosphereRequest contextPath(String contextPath);\\npublic AtmosphereRequest requestURI(String requestURI);\\npublic int read();\\npublic void setAttribute(String s,Object o);\\npublic void setCharacterEncoding(String env);\\npublic AsyncContext startAsync();\\npublic AsyncContext startAsync(ServletRequest request,ServletResponse response);\\npublic AsyncContext getAsyncContext();\\npublic Object getAttribute(String s);\\npublic void removeAttribute(String name);\\npublic LocalAttributes attributes();\\npublic HttpSession getSession();\\npublic HttpSession getSession(boolean create);\\npublic Principal getUserPrincipal();\\npublic boolean isRequestedSessionIdFromCookie();\\npublic boolean isRequestedSessionIdFromUrl();\\npublic boolean isRequestedSessionIdFromURL();\\npublic boolean isRequestedSessionIdValid();\\npublic boolean isUserInRole(String role);\\npublic void login(String username,String password);\\npublic void logout();\\npublic String getRemoteAddr();\\npublic String getRemoteHost();\\npublic int getRemotePort();\\npublic RequestDispatcher getRequestDispatcher(String path);\\npublic String getScheme();\\npublic String getServerName();\\npublic int getServerPort();\\npublic ServletContext getServletContext();\\npublic boolean isAsyncStarted();\\npublic boolean isAsyncSupported();\\npublic boolean isSecure();\\npublic String getLocalName();\\npublic int getLocalPort();\\npublic String getLocalAddr();\\npublic Locale getLocale();\\npublic AtmosphereResource resource();\\npublic Enumeration getLocales();\\npublic boolean dispatchRequestAsynchronously();\\npublic boolean isDestroyable();\\npublic AtmosphereRequest pathInfo(String pathInfo);\\npublic Enumeration getAttributeNames();\\npublic LocalAttributes localAttributes();\\npublic String getCharacterEncoding();\\npublic int getContentLength();\\npublic String uuid();\\npublic void destroy();\\npublic void destroy(boolean force);\\npublic void setRequest(ServletRequest request);\\npublic Builder destroyable(boolean destroyable);\\npublic Builder headers(Map headers);\\npublic Builder cookies(Set cookies);\\npublic Builder dispatchRequestAsynchronously(boolean dispatchRequestAsynchronously);\\npublic Builder remoteAddr(String remoteAddr);\\npublic Builder remoteHost(String remoteHost);\\npublic Builder remotePort(int remotePort);\\npublic Builder localAddr(String localAddr);\\npublic Builder localName(String localName);\\npublic Builder localPort(int localPort);\\npublic Builder remoteInetSocketAddress(Callable remoteAddr);\\npublic Builder localInetSocketAddress(Callable localAddr);\\npublic Builder attributes(Map attributes);\\npublic Builder request(HttpServletRequest request);\\npublic Builder servletPath(String servletPath);\\npublic Builder requestURI(String requestURI);\\npublic Builder requestURL(String requestURL);\\npublic Builder pathInfo(String pathInfo);\\npublic Builder queryString(String queryString);\\npublic Builder body(byte[] dataBytes);\\npublic Builder body(byte[] dataBytes,int offset,int length);\\npublic Builder encoding(String encoding);\\npublic Builder method(String methodType);\\npublic Builder contentType(String contentType);\\npublic Builder contentLength(Long contentLength);\\npublic Builder body(String data);\\npublic Builder inputStream(InputStream inputStream);\\npublic Builder reader(Reader reader);\\npublic AtmosphereRequest build();\\npublic Builder queryStrings(Map queryStrings);\\npublic Builder contextPath(String contextPath);\\npublic Builder serverName(String serverName);\\npublic Builder serverPort(int serverPort);\\npublic Builder session(HttpSession session);\\npublic Builder principal(Principal principal);\\npublic Builder authType(String authType);\\npublic Builder isSSecure(boolean isSecure);\\npublic Builder locale(Locale locale);\\npublic Builder userPrincipal(Principal userPrincipal);\\npublic boolean hasString();\\npublic boolean hasBytes();\\npublic String asString();\\npublic byte[] asBytes();\\npublic int byteOffset();\\npublic int byteLength();\\npublic boolean isEmpty();\\npublic int read();\\npublic int read(byte[] bytes);\\npublic int read(byte[] bytes,int i,int i1);\\npublic long skip(long l);\\npublic int available();\\npublic void close();\\nsynchronized void mark(int i);\\nsynchronized void reset();\\npublic boolean markSupported();\\nstatic AtmosphereRequest newInstance();\\nstatic AtmosphereRequest wrap(HttpServletRequest request);\\nstatic AtmosphereRequest cloneRequest(HttpServletRequest request,boolean loadInMemory,boolean copySession,boolean isDestroyable,boolean createSession);\\npublic boolean authenticate(HttpServletResponse response);\\npublic String getAuthType();\\npublic String getContextPath();\\npublic Cookie[] getCookies();\\npublic long getDateHeader(String name);\\npublic String getHeader(String name);\\npublic Enumeration getHeaderNames();\\npublic Enumeration getHeaders(String name);\\npublic int getIntHeader(String name);\\npublic String getMethod();\\npublic Part getPart(String name);\\npublic Collection getParts();\\npublic String getPathInfo();\\npublic String getPathTranslated();\\npublic String getQueryString();\\npublic String getRemoteUser();\\npublic String getRequestedSessionId();\\npublic String getRequestURI();\\npublic StringBuffer getRequestURL();\\npublic String getServletPath();\\npublic HttpSession getSession();\\npublic HttpSession getSession(boolean create);\\npublic void invalidate();\\npublic Principal getUserPrincipal();\\npublic boolean isRequestedSessionIdFromCookie();\\npublic boolean isRequestedSessionIdFromUrl();\\npublic boolean isRequestedSessionIdFromURL();\\npublic boolean isRequestedSessionIdValid();\\npublic boolean isUserInRole(String role);\\npublic void login(String username,String password);\\npublic void logout();\\npublic AsyncContext getAsyncContext();\\npublic Object getAttribute(String name);\\npublic Enumeration getAttributeNames();\\npublic String getCharacterEncoding();\\npublic int getContentLength();\\npublic String getContentType();\\npublic DispatcherType getDispatcherType();\\npublic ServletInputStream getInputStream();\\npublic Locale getLocale();\\npublic Enumeration getLocales();\\npublic String getLocalName();\\npublic int getLocalPort();\\npublic String getLocalAddr();\\npublic String getParameter(String name);\\npublic Map getParameterMap();\\npublic Enumeration getParameterNames();\\npublic String[] getParameterValues(String name);\\npublic String getProtocol();\\npublic BufferedReader getReader();\\npublic String getRealPath(String path);\\npublic String getRemoteAddr();\\npublic String getRemoteHost();\\npublic int getRemotePort();\\npublic RequestDispatcher getRequestDispatcher(String path);\\npublic String getScheme();\\npublic String getServerName();\\npublic int getServerPort();\\npublic ServletContext getServletContext();\\npublic boolean isAsyncStarted();\\npublic boolean isAsyncSupported();\\npublic boolean isSecure();\\npublic void removeAttribute(String name);\\npublic void setAttribute(String name,Object o);\\npublic void setCharacterEncoding(String env);\\npublic AsyncContext startAsync();\\npublic AsyncContext startAsync(ServletRequest request,ServletResponse response);\\npublic InetSocketAddress address();\\npublic int getPort();\\npublic String getHostAddress();\\npublic String getHostName();\\npublic void addListener(AsyncListener listener);\\npublic void addListener(AsyncListener listener,ServletRequest request,ServletResponse response);\\npublic void complete();\\npublic T createListener(Class clazz);\\npublic void dispatch();\\npublic void dispatch(ServletContext servletContext,String path);\\npublic void dispatch(String path);\\npublic ServletRequest getRequest();\\npublic ServletResponse getResponse();\\npublic long getTimeout();\\npublic boolean hasOriginalRequestAndResponse();\\npublic void setTimeout(long timeoutMilliseconds);\\npublic void start(Runnable run);\\npublic void addListener(AsyncListener listener);\\npublic void addListener(AsyncListener listener,ServletRequest request,ServletResponse response);\\npublic void complete();\\npublic T createListener(Class clazz);\\npublic void dispatch();\\npublic void dispatch(ServletContext servletContext,String path);\\npublic void dispatch(String path);\\npublic ServletRequest getRequest();\\npublic ServletResponse getResponse();\\npublic long getTimeout();\\npublic boolean hasOriginalRequestAndResponse();\\npublic void setTimeout(long timeout);\\npublic void start(Runnable run);\\npublic String toString();\\npublic String requestURL();\\n }\\npublic interface AtmosphereResource { TRANSPORT transport();\\n AtmosphereResource resumeOnBroadcast(boolean resumeOnBroadcast);\\n boolean isSuspended();\\n boolean resumeOnBroadcast();\\n boolean isResumed();\\n boolean isCancelled();\\n AtmosphereResource resume();\\n AtmosphereResource suspend();\\n AtmosphereResource suspend(long timeout);\\n AtmosphereResource suspend(long timeout,TimeUnit timeunit);\\n AtmosphereRequest getRequest();\\n AtmosphereResponse getResponse();\\n AtmosphereConfig getAtmosphereConfig();\\n Broadcaster getBroadcaster();\\n List broadcasters();\\n AtmosphereResource removeFromAllBroadcasters();\\n AtmosphereResource setBroadcaster(Broadcaster broadcaster);\\n AtmosphereResource addBroadcaster(Broadcaster broadcaster);\\n AtmosphereResource removeBroadcaster(Broadcaster broadcaster);\\n AtmosphereResource setSerializer(Serializer s);\\n AtmosphereResource write(String s);\\n AtmosphereResource write(byte[] s);\\n Serializer getSerializer();\\n AtmosphereResourceEvent getAtmosphereResourceEvent();\\n AtmosphereHandler getAtmosphereHandler();\\n AtmosphereResource writeOnTimeout(Object o);\\n Object writeOnTimeout();\\n String uuid();\\n AtmosphereResource addEventListener(AtmosphereResourceEventListener e);\\n AtmosphereResource removeEventListener(AtmosphereResourceEventListener e);\\n AtmosphereResource removeEventListeners();\\n AtmosphereResource notifyListeners(AtmosphereResourceEvent e);\\n AtmosphereResource notifyListeners();\\n HttpSession session();\\n HttpSession session(boolean create);\\n void close();\\n AtmosphereResource forceBinaryWrite(boolean force);\\n boolean forceBinaryWrite();\\npublic AtmosphereResource initialize(AtmosphereConfig config,Broadcaster broadcaster,AtmosphereRequest req,AtmosphereResponse response,AsyncSupport asyncSupport,AtmosphereHandler atmosphereHandler);\\n }\\npublic interface AtmosphereResourceImpl {public AtmosphereResource initialize(AtmosphereConfig config,Broadcaster broadcaster,AtmosphereRequest req,AtmosphereResponse response,AsyncSupport asyncSupport,AtmosphereHandler atmosphereHandler);\\nprotected void setUUID(String uuid);\\nprotected void register();\\npublic AtmosphereResourceEventImpl getAtmosphereResourceEvent();\\npublic AtmosphereHandler getAtmosphereHandler();\\npublic AtmosphereResource writeOnTimeout(Object o);\\npublic Object writeOnTimeout();\\npublic String uuid();\\npublic TRANSPORT transport();\\npublic AtmosphereResourceImpl transport(TRANSPORT transport);\\npublic AtmosphereResource resumeOnBroadcast(boolean resumeOnBroadcast);\\npublic boolean isSuspended();\\npublic boolean resumeOnBroadcast();\\npublic AtmosphereResource resume();\\npublic AtmosphereResource suspend();\\npublic AtmosphereResource suspend(long timeout,TimeUnit timeunit);\\npublic AtmosphereResource suspend(long timeout);\\npublic AtmosphereRequest getRequest(boolean enforceScope);\\npublic AtmosphereResponse getResponse(boolean enforceScope);\\npublic AtmosphereRequest getRequest();\\npublic AtmosphereResponse getResponse();\\npublic Broadcaster getBroadcaster();\\npublic List broadcasters();\\nprotected Broadcaster getBroadcaster(boolean autoCreate);\\npublic AtmosphereResource setBroadcaster(Broadcaster broadcaster);\\npublic AtmosphereResource addBroadcaster(Broadcaster broadcaster);\\npublic AtmosphereResource removeBroadcaster(Broadcaster broadcaster);\\nprotected AtmosphereResource uniqueBroadcaster(Broadcaster newB);\\npublic AtmosphereConfig getAtmosphereConfig();\\npublic Action action();\\npublic void reset();\\npublic void setIsInScope(boolean isInScope);\\npublic boolean isInScope();\\npublic AtmosphereResource setSerializer(Serializer s);\\npublic boolean isResumed();\\npublic boolean isCancelled();\\npublic AtmosphereResource write(String s);\\npublic AtmosphereResource write(byte[] o);\\npublic Serializer getSerializer();\\npublic AtmosphereResource addEventListener(AtmosphereResourceEventListener e);\\npublic AtmosphereResource removeEventListener(AtmosphereResourceEventListener e);\\npublic AtmosphereResource removeEventListeners();\\npublic AtmosphereResource notifyListeners();\\npublic AtmosphereResource notifyListeners(AtmosphereResourceEvent event);\\npublic AtmosphereResource removeFromAllBroadcasters();\\npublic void onThrowable(Throwable t);\\n void onThrowable(AtmosphereResourceEvent e);\\n void onHeartbeat(AtmosphereResourceEvent e);\\n void onSuspend(AtmosphereResourceEvent e);\\n void onPreSuspend(AtmosphereResourceEvent e);\\n void onResume(AtmosphereResourceEvent e);\\n void onDisconnect(AtmosphereResourceEvent e);\\n void onBroadcast(AtmosphereResourceEvent e);\\n void onClose(AtmosphereResourceEvent e);\\npublic ConcurrentLinkedQueue atmosphereResourceEventListener();\\npublic AtmosphereResourceImpl atmosphereHandler(AtmosphereHandler atmosphereHandler);\\npublic void cancel();\\npublic void _destroy();\\npublic String toString();\\npublic AtmosphereResourceImpl disableSuspend(boolean disableSuspend);\\npublic HttpSession session(boolean create);\\npublic void close();\\npublic void dirtyClose();\\npublic AtmosphereResource forceBinaryWrite(boolean forceBinaryWrite);\\npublic boolean forceBinaryWrite();\\npublic HttpSession session();\\npublic AtmosphereResourceImpl session(HttpSession session);\\npublic AtmosphereResourceImpl cloneState(AtmosphereResource r);\\npublic ConcurrentLinkedQueue listeners();\\npublic AtmosphereResourceImpl disableSuspendEvent(boolean disableSuspendEvent);\\npublic boolean disableSuspendEvent();\\npublic WebSocket webSocket();\\npublic AtmosphereResourceImpl webSocket(WebSocket webSocket);\\npublic boolean equals(Object o);\\npublic int hashCode();\\npublic boolean getAndSetInClosingPhase();\\npublic boolean isPendingClose();\\npublic boolean getAndSetPendingClose();\\n }\\npublic interface AtmosphereResponse { void destroy();\\n void destroy(boolean force);\\n boolean destroyed();\\n void addCookie(Cookie cookie);\\n boolean containsHeader(String name);\\n String encodeURL(String url);\\n String encodeRedirectURL(String url);\\n String encodeUrl(String url);\\n String encodeRedirectUrl(String url);\\n AtmosphereResponse delegateToNativeResponse(boolean delegateToNativeResponse);\\n void sendError(int sc,String msg);\\n void sendError(int sc);\\n void sendRedirect(String location);\\n void setDateHeader(String name,long date);\\n void addDateHeader(String name,long date);\\n void setHeader(String name,String value);\\n void addHeader(String name,String value);\\n void setIntHeader(String name,int value);\\n void addIntHeader(String name,int value);\\n void setStatus(int status);\\n void setStatus(int status,String statusMessage);\\n int getStatus();\\n ServletResponse getResponse();\\n String getStatusMessage();\\n Map headers();\\n String getHeader(String name);\\n Collection getHeaders(String name);\\n Collection getHeaderNames();\\n void setCharacterEncoding(String charSet);\\n void flushBuffer();\\n int getBufferSize();\\n String getCharacterEncoding();\\n boolean isDestroyable();\\n AtmosphereResponse destroyable(boolean destroyable);\\n ServletOutputStream getOutputStream();\\n PrintWriter getWriter();\\n void setContentLength(int len);\\n void setContentType(String contentType);\\n String getContentType();\\n boolean isCommitted();\\n void reset();\\n void resetBuffer();\\n void setBufferSize(int size);\\n void setLocale(Locale locale);\\n Locale getLocale();\\n AsyncIOWriter getAsyncIOWriter();\\n AtmosphereResponse asyncIOWriter(AsyncIOWriter asyncIOWriter);\\n AtmosphereRequest request();\\n AtmosphereResponse request(AtmosphereRequest atmosphereRequest);\\n void close();\\n void closeStreamOrWriter();\\n AtmosphereResponse write(String data);\\n AtmosphereResponse write(String data,boolean writeUsingOriginalResponse);\\n AtmosphereResponse write(byte[] data);\\n AtmosphereResponse write(byte[] data,boolean writeUsingOriginalResponse);\\n AtmosphereResponse write(byte[] data,int offset,int length);\\n AtmosphereResponse write(byte[] data,int offset,int length,boolean writeUsingOriginalResponse);\\n AtmosphereResource resource();\\n void setResponse(ServletResponse response);\\n String uuid();\\n String toString();\\n Builder destroyable(boolean isRecyclable);\\n Builder asyncIOWriter(AsyncIOWriter asyncIOWriter);\\n Builder status(int status);\\n Builder statusMessage(String statusMessage);\\n Builder request(AtmosphereRequest atmosphereRequest);\\n AtmosphereResponse build();\\n Builder header(String name,String value);\\n Builder writeHeader(boolean writeStatusAndHeader);\\n Builder response(HttpServletResponse res);\\n }\\npublic interface KeepOpenStreamAware { }\\npublic interface ByteArrayAsyncWriter {public AsyncIOWriter write(AtmosphereResponse r,String data);\\npublic AsyncIOWriter write(AtmosphereResponse r,byte[] data);\\npublic AsyncIOWriter write(AtmosphereResponse r,byte[] data,int offset,int length);\\npublic ByteArrayOutputStream stream();\\npublic void close(AtmosphereResponse r);\\n }\\n\" }", "class_name": "WebSocket", "code": "public long lastWriteTimeStampInMilliseconds(){\n return lastWrite == -1 ? System.currentTimeMillis() : lastWrite;\n}\n", "docstring": "/** \n * The last time, in milliseconds, a write operation occurred.\n * @return this\n */\n", "end_lineno": "166", "file_content": "/*\n* Copyright 2008-2022 Async-IO.org\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n* use this file except in compliance with the License. You may obtain a copy of\n* the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n* License for the specific language governing permissions and limitations under\n* the License.\n*/\npackage org.atmosphere.websocket;\n\nimport org.atmosphere.cpr.ApplicationConfig;\nimport org.atmosphere.cpr.AsyncIOWriter;\nimport org.atmosphere.cpr.AtmosphereConfig;\nimport org.atmosphere.cpr.AtmosphereInterceptorWriter;\nimport org.atmosphere.cpr.AtmosphereRequest;\nimport org.atmosphere.cpr.AtmosphereRequestImpl;\nimport org.atmosphere.cpr.AtmosphereResource;\nimport org.atmosphere.cpr.AtmosphereResourceImpl;\nimport org.atmosphere.cpr.AtmosphereResponse;\nimport org.atmosphere.cpr.KeepOpenStreamAware;\nimport org.atmosphere.util.ByteArrayAsyncWriter;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.io.IOException;\nimport java.nio.Buffer;\nimport java.nio.ByteBuffer;\nimport java.nio.CharBuffer;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_ERROR;\n\n/**\n * Represent a portable WebSocket implementation which can be used to write message.\n *\n * @author Jeanfrancois Arcand\n */\npublic abstract class WebSocket extends AtmosphereInterceptorWriter implements KeepOpenStreamAware {\n\n protected static final Logger logger = LoggerFactory.getLogger(WebSocket.class);\n public final static String WEBSOCKET_INITIATED = WebSocket.class.getName() + \".initiated\";\n public final static String WEBSOCKET_SUSPEND = WebSocket.class.getName() + \".suspend\";\n public final static String WEBSOCKET_RESUME = WebSocket.class.getName() + \".resume\";\n public final static String WEBSOCKET_ACCEPT_DONE = WebSocket.class.getName() + \".acceptDone\";\n public final static String NOT_SUPPORTED = \"Websocket protocol not supported\";\n public final static String CLEAN_CLOSE = \"Clean_Close\";\n\n private AtmosphereResource r;\n protected long lastWrite;\n protected boolean binaryWrite;\n private final AtomicBoolean firstWrite = new AtomicBoolean(false);\n private final AtmosphereConfig config;\n private WebSocketHandler webSocketHandler;\n protected ByteBuffer bb;\n protected CharBuffer cb;\n protected String uuid = \"NUll\";\n private Map attributesAtWebSocketOpen;\n private Object attachment;\n\n public WebSocket(AtmosphereConfig config) {\n String s = config.getInitParameter(ApplicationConfig.WEBSOCKET_BINARY_WRITE);\n if (Boolean.parseBoolean(s)) {\n binaryWrite = true;\n } else {\n binaryWrite = false;\n }\n\n int bufferSize = 8192;\n String bufferSizeParam = config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE);\n if (bufferSizeParam != null) {\n bufferSize = Integer.parseInt(bufferSizeParam);\n }\n bb = ByteBuffer.allocate(bufferSize);\n cb = CharBuffer.allocate(bufferSize);\n\n this.config = config;\n }\n\n public AtmosphereConfig config() {\n return config;\n }\n\n protected WebSocket webSocketHandler(WebSocketHandler webSocketHandler) {\n this.webSocketHandler = webSocketHandler;\n return this;\n }\n\n /**\n * Switch to binary write, or go back to text write. Default is false.\n *\n * @param binaryWrite true to switch to binary write.\n * @return WebSocket\n */\n public WebSocket binaryWrite(boolean binaryWrite) {\n this.binaryWrite = binaryWrite;\n return this;\n }\n\n public WebSocketHandler webSocketHandler() {\n return webSocketHandler;\n }\n\n /**\n * Associate an {@link AtmosphereResource} to this WebSocket\n *\n * @param r an {@link AtmosphereResource} to this WebSocket\n * @return this\n */\n public WebSocket resource(AtmosphereResource r) {\n\n // Make sure we carry what was set at the onOpen stage.\n if (this.r != null && r != null) {\n // TODO: This is all over the place and quite ugly (the cast). Need to fix this in 1.1\n ((AtmosphereResourceImpl) r).cloneState(this.r);\n }\n this.r = r;\n if (r != null) uuid = r.uuid();\n return this;\n }\n\n /**\n * Copy {@link AtmosphereRequestImpl#localAttributes()} that where set when the websocket was opened.\n *\n */\n public synchronized void shiftAttributes() {\n attributesAtWebSocketOpen = new ConcurrentHashMap<>();\n attributesAtWebSocketOpen.putAll(((AtmosphereResourceImpl) r).getRequest(false).localAttributes().unmodifiableMap());\n }\n\n /**\n * Return the attribute that was set during the websocket's open operation.\n *\n * @return Map\n */\n public Map attributes() {\n return attributesAtWebSocketOpen;\n }\n\n /**\n * Return the an {@link AtmosphereResource} used by this WebSocket, or null if the WebSocket has been closed\n * before the WebSocket message has been processed.\n *\n * @return {@link AtmosphereResource}\n */\n public AtmosphereResource resource() {\n return r;\n }\n\n /**\n * The last time, in milliseconds, a write operation occurred.\n *\n * @return this\n */\n public long lastWriteTimeStampInMilliseconds() {\n return lastWrite == -1 ? System.currentTimeMillis() : lastWrite;\n }\n\n protected byte[] transform(byte[] b, int offset, int length) throws IOException {\n return transform(r.getResponse(), b, offset, length);\n }\n\n protected byte[] transform(AtmosphereResponse response, byte[] b, int offset, int length) throws IOException {\n AsyncIOWriter a = response.getAsyncIOWriter();\n // NOTE #1961 for now, create a new buffer par transform call and release it after the transform call.\n // Alternatively, we may cache the buffer in thread-local and use it while this thread invokes\n // multiple writes and release it when this thread invokes the close method.\n ByteArrayAsyncWriter buffer = new ByteArrayAsyncWriter();\n try {\n response.asyncIOWriter(buffer);\n invokeInterceptor(response, b, offset, length);\n return buffer.stream().toByteArray();\n } finally {\n buffer.close(null);\n response.asyncIOWriter(a);\n }\n }\n\n @Override\n public WebSocket write(AtmosphereResponse r, String data) throws IOException {\n firstWrite.set(true);\n if (data == null) {\n logger.error(\"Cannot write null value for {}\", resource());\n return this;\n }\n\n if (!isOpen()) throw new IOException(\"Connection remotely closed for \" + uuid);\n logger.trace(\"WebSocket.write() {}\", data);\n\n boolean transform = !filters.isEmpty() && r.getStatus() < 400;\n if (binaryWrite) {\n byte[] b = data.getBytes(resource().getResponse().getCharacterEncoding());\n if (transform) {\n b = transform(r, b, 0, b.length);\n }\n\n if (b != null) {\n write(b, 0, b.length);\n }\n } else {\n if (transform) {\n byte[] b = data.getBytes(resource().getResponse().getCharacterEncoding());\n data = new String(transform(r, b, 0, b.length), r.getCharacterEncoding());\n }\n\n write(data);\n }\n lastWrite = System.currentTimeMillis();\n return this;\n }\n\n @Override\n public WebSocket write(AtmosphereResponse r, byte[] data) throws IOException {\n if (data == null) {\n logger.error(\"Cannot write null value for {}\", resource());\n return this;\n }\n return write(r, data, 0, data.length);\n }\n\n @Override\n public WebSocket write(AtmosphereResponse r, byte[] b, int offset, int length) throws IOException {\n firstWrite.set(true);\n if (b == null) {\n logger.error(\"Cannot write null value for {}\", resource());\n return this;\n }\n if (!isOpen()) throw new IOException(\"Connection remotely closed for \" + uuid);\n\n if (logger.isTraceEnabled()) {\n logger.trace(\"WebSocket.write() {}\", new String(b, offset, length, StandardCharsets.UTF_8));\n }\n\n boolean transform = !filters.isEmpty() && r.getStatus() < 400;\n if (binaryWrite || resource().forceBinaryWrite()) {\n if (transform) {\n b = transform(r, b, offset, length);\n }\n\n if (b != null) {\n write(b, 0, b.length);\n }\n } else {\n String data;\n String charset = r.getCharacterEncoding() == null ? \"UTF-8\" : r.getCharacterEncoding();\n if (transform) {\n data = new String(transform(r, b, offset, length), charset);\n } else {\n data = new String(b, offset, length, charset);\n }\n\n write(data);\n }\n lastWrite = System.currentTimeMillis();\n return this;\n }\n\n /**\n * Broadcast, using the {@link org.atmosphere.cpr.AtmosphereResource#getBroadcaster()} the object to all\n * {@link WebSocket} associated with the {@link org.atmosphere.cpr.Broadcaster}. This method does the same as\n * websocket.resource().getBroadcaster().broadcast(o).\n *\n * @param o An object to broadcast to all WebSockets.\n */\n public WebSocket broadcast(Object o) {\n if (r != null) {\n r.getBroadcaster().broadcast(o);\n } else {\n logger.debug(\"No AtmosphereResource Associated with this WebSocket.\");\n }\n return this;\n }\n\n @Override\n public WebSocket writeError(AtmosphereResponse r, int errorCode, String message) throws IOException {\n super.writeError(r, errorCode, message);\n if (!firstWrite.get()) {\n logger.debug(\"The WebSocket handshake succeeded but the dispatched URI failed with status {} : {} \" +\n \"The WebSocket connection is still open and client can continue sending messages.\", errorCode + \" \" + message, uuid());\n } else {\n logger.warn(\"Unable to write {} {}\", errorCode, message);\n }\n\n return this;\n }\n\n @Override\n public WebSocket redirect(AtmosphereResponse r, String location) throws IOException {\n logger.error(\"WebSocket Redirect not supported\");\n return this;\n }\n\n\n @Override\n public void close(AtmosphereResponse r) throws IOException {\n logger.trace(\"WebSocket.close() for {}\", uuid);\n\n try {\n // Never trust underlying server.\n // https://github.com/Atmosphere/atmosphere/issues/1633\n if (r.request() != null && r.request().getAttribute(CLEAN_CLOSE) == null) {\n close();\n }\n } catch (Exception ex) {\n logger.trace(\"\", ex);\n }\n\n try {\n ((Buffer)bb).clear();\n ((Buffer)cb).clear();\n // NOTE #1961 if the buffer is cached at thread-local, it needs to be released here.\n } catch (Exception ex) {\n logger.trace(\"\", ex);\n }\n }\n\n @Override\n public WebSocket flush(AtmosphereResponse r) throws IOException {\n return this;\n }\n\n /**\n * Is the underlying WebSocket open.\n *\n * @return true is opened\n */\n abstract public boolean isOpen();\n\n /**\n * Use the underlying container's websocket to write the String.\n *\n * @param s a websocket String message\n * @return this\n */\n abstract public WebSocket write(String s) throws IOException;\n\n /**\n * Use the underlying container's websocket to write the byte.\n *\n * @param b a websocket byte message\n * @param offset start\n * @param length end\n * @return this\n */\n abstract public WebSocket write(byte[] b, int offset, int length) throws IOException;\n\n /**\n * Use the underlying container's websocket to write the byte.\n *\n * @param b a websocket byte message\n * @return WebSocket\n */\n public WebSocket write(byte[] b) throws IOException {\n return write(b, 0, b.length);\n }\n\n /**\n * Close the underlying WebSocket\n */\n abstract public void close();\n\n /**\n * Allow the underlying WebSocket to close with a code and a reason.\n */\n public void close(int statusCode, String reasonText) {\n }\n\n public String uuid() {\n return uuid;\n }\n\n public static void notSupported(AtmosphereRequest request, AtmosphereResponse response) throws IOException {\n response.addHeader(X_ATMOSPHERE_ERROR, WebSocket.NOT_SUPPORTED);\n response.sendError(501, WebSocket.NOT_SUPPORTED);\n logger.trace(\"{} for request {}\", WebSocket.NOT_SUPPORTED, request);\n }\n\n /**\n * Send a WebSocket Ping\n *\n * @param payload the bytes to send\n * @return this\n */\n public WebSocket sendPing(byte[] payload) {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Send a WebSocket Pong\n *\n * @param payload the bytes to send\n * @return this\n */\n public WebSocket sendPong(byte[] payload) {\n throw new UnsupportedOperationException();\n }\n\n /**\n * Attach an object. Be careful when attaching an object as it can cause memory leak\n *\n * @oaram object\n */\n public WebSocket attachment(Object attachment) {\n this.attachment = attachment;\n return this;\n }\n\n /**\n * Return the attachment\n */\n public Object attachment() {\n return attachment;\n }\n}\n", "file_name": "WebSocket.java", "human_label": "Check whether lastwrite is - 1. If yes, return - 1. Otherwise, return System.currentTimeMillis().", "level": "class_runnable", "lineno": "159", "name": "lastWriteTimeStampInMilliseconds", "oracle_context": "{ \"apis\" : \"[currentTimeMillis]\", \"classes\" : \"[]\", \"vars\" : \"[lastWrite]\" }", "package": "org.atmosphere.websocket", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767601a6d9265ec0180fd", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.alg.util.*;\\nimport org.jgrapht.graph.*;\\nimport java.util.*;\\nimport java.util.function.*;\\nlong serialVersionUID;\\nMap,Set> touchingVerticesToEdgeMap;\\nFastLookupDirectedSpecifics(Graph graph,Map vertexMap,Map touchingVerticesToEdgeMap,EdgeSetFactory edgeSetFactory);\\ngetAllEdges(V sourceVertex,V targetVertex);\\ngetEdge(V sourceVertex,V targetVertex);\\naddEdgeToTouchingVertices(V sourceVertex,V targetVertex,E e);\\naddEdgeToTouchingVerticesIfAbsent(V sourceVertex,V targetVertex,E e);\\ncreateEdgeToTouchingVerticesIfAbsent(V sourceVertex,V targetVertex,Supplier edgeSupplier);\\nremoveEdgeFromTouchingVertices(V sourceVertex,V targetVertex,E e);\\nremoveFromIndex(V sourceVertex,V targetVertex,E e);\\n\", \"repo_level\" : \"\" }", "class_name": "FastLookupDirectedSpecifics", "code": "protected void addToIndex(V sourceVertex,V targetVertex,E e){\n Pair vertexPair=new Pair<>(sourceVertex,targetVertex);\n Set edgeSet=touchingVerticesToEdgeMap.get(vertexPair);\n if (edgeSet != null) edgeSet.add(e);\n else {\n edgeSet=edgeSetFactory.createEdgeSet(sourceVertex);\n edgeSet.add(e);\n touchingVerticesToEdgeMap.put(vertexPair,edgeSet);\n }\n}\n", "docstring": "/** \n * Add an edge to the index.\n * @param sourceVertex the source vertex\n * @param targetVertex the target vertex\n * @param e the edge\n */\n", "end_lineno": "159", "file_content": "/*\n * (C) Copyright 2015-2021, by Joris Kinable and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.graph.specifics;\n\nimport org.jgrapht.*;\nimport org.jgrapht.alg.util.*;\nimport org.jgrapht.graph.*;\n\nimport java.util.*;\nimport java.util.function.*;\n\n/**\n * Fast implementation of DirectedSpecifics. This class uses additional data structures to improve\n * the performance of methods which depend on edge retrievals, e.g. getEdge(V u, V v),\n * containsEdge(V u, V v),addEdge(V u, V v). A disadvantage is an increase in memory consumption. If\n * memory utilization is an issue, use a {@link DirectedSpecifics} instead.\n *\n * @param the graph vertex type\n * @param the graph edge type\n *\n * @author Joris Kinable\n */\npublic class FastLookupDirectedSpecifics\n extends\n DirectedSpecifics\n{\n private static final long serialVersionUID = 4089085208843722263L;\n\n /**\n * Maps a pair of vertices <u,v> to a set of edges {(u,v)}. In case of a multigraph, all\n * edges which touch both u and v are included in the set.\n */\n protected Map, Set> touchingVerticesToEdgeMap;\n\n /**\n * Construct a new fast lookup directed specifics.\n * \n * @param graph the graph for which these specifics are for\n * @param vertexMap map for the storage of vertex edge sets. Needs to have a predictable\n * iteration order.\n * @param touchingVerticesToEdgeMap Additional map for caching. No need for a predictable\n * iteration order.\n * @param edgeSetFactory factory for the creation of vertex edge sets\n */\n public FastLookupDirectedSpecifics(\n Graph graph, Map> vertexMap,\n Map, Set> touchingVerticesToEdgeMap, EdgeSetFactory edgeSetFactory)\n {\n super(graph, vertexMap, edgeSetFactory);\n this.touchingVerticesToEdgeMap = Objects.requireNonNull(touchingVerticesToEdgeMap);\n }\n\n @Override\n public Set getAllEdges(V sourceVertex, V targetVertex)\n {\n if (graph.containsVertex(sourceVertex) && graph.containsVertex(targetVertex)) {\n Set edges = touchingVerticesToEdgeMap.get(new Pair<>(sourceVertex, targetVertex));\n if (edges == null) {\n return Collections.emptySet();\n } else {\n Set edgeSet = edgeSetFactory.createEdgeSet(sourceVertex);\n edgeSet.addAll(edges);\n return edgeSet;\n }\n } else {\n return null;\n }\n }\n\n @Override\n public E getEdge(V sourceVertex, V targetVertex)\n {\n Set edges = touchingVerticesToEdgeMap.get(new Pair<>(sourceVertex, targetVertex));\n if (edges == null || edges.isEmpty())\n return null;\n else {\n return edges.iterator().next();\n }\n }\n\n @Override\n public boolean addEdgeToTouchingVertices(V sourceVertex, V targetVertex, E e)\n {\n if (!super.addEdgeToTouchingVertices(sourceVertex, targetVertex, e)) {\n return false;\n }\n addToIndex(sourceVertex, targetVertex, e);\n return true;\n }\n\n @Override\n public boolean addEdgeToTouchingVerticesIfAbsent(V sourceVertex, V targetVertex, E e)\n {\n // first lookup using our own index\n E edge = getEdge(sourceVertex, targetVertex);\n if (edge != null) {\n return false;\n }\n\n return addEdgeToTouchingVertices(sourceVertex, targetVertex, e);\n }\n\n @Override\n public E createEdgeToTouchingVerticesIfAbsent(\n V sourceVertex, V targetVertex, Supplier edgeSupplier)\n {\n // first lookup using our own index\n E edge = getEdge(sourceVertex, targetVertex);\n if (edge != null) {\n return null;\n }\n\n E e = edgeSupplier.get();\n addEdgeToTouchingVertices(sourceVertex, targetVertex, e);\n return e;\n }\n\n @Override\n public void removeEdgeFromTouchingVertices(V sourceVertex, V targetVertex, E e)\n {\n super.removeEdgeFromTouchingVertices(sourceVertex, targetVertex, e);\n\n removeFromIndex(sourceVertex, targetVertex, e);\n }\n\n /**\n * Add an edge to the index.\n * \n * @param sourceVertex the source vertex\n * @param targetVertex the target vertex\n * @param e the edge\n */\n protected void addToIndex(V sourceVertex, V targetVertex, E e)\n {\n Pair vertexPair = new Pair<>(sourceVertex, targetVertex);\n Set edgeSet = touchingVerticesToEdgeMap.get(vertexPair);\n if (edgeSet != null)\n edgeSet.add(e);\n else {\n edgeSet = edgeSetFactory.createEdgeSet(sourceVertex);\n edgeSet.add(e);\n touchingVerticesToEdgeMap.put(vertexPair, edgeSet);\n }\n }\n\n /**\n * Remove an edge from the index.\n * \n * @param sourceVertex the source vertex\n * @param targetVertex the target vertex\n * @param e the edge\n */\n protected void removeFromIndex(V sourceVertex, V targetVertex, E e)\n {\n Pair vertexPair = new Pair<>(sourceVertex, targetVertex);\n Set edgeSet = touchingVerticesToEdgeMap.get(vertexPair);\n if (edgeSet != null) {\n edgeSet.remove(e);\n if (edgeSet.isEmpty()) {\n touchingVerticesToEdgeMap.remove(vertexPair);\n }\n }\n }\n\n}\n", "file_name": "FastLookupDirectedSpecifics.java", "human_label": "Add an edge whose start point is sourceVertex and end point is targetVertex to touchingVerticesToEdgeMap.", "level": "class_runnable", "lineno": "141", "name": "addToIndex", "oracle_context": "{ \"apis\" : \"[get, add, createEdgeSet, put]\", \"classes\" : \"[Pair, Set]\", \"vars\" : \"[touchingVerticesToEdgeMap]\" }", "package": "org.jgrapht.graph.specifics", "project": "jgrapht-master" }, { "_id": "636766821a6d9265ec0174c9", "all_context": "{ \"class_level\" : \"import org.slf4j.Logger;\\nimport org.slf4j.LoggerFactory;\\nimport java.io.DataInputStream;\\nimport java.io.File;\\nimport java.io.FileInputStream;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport java.util.zip.ZipFile;\\nLogger logger;\\nFileIterator fileIterator;\\nString[] pkgNameFilter;\\nZipFileIterator zipIterator;\\nboolean isFile;\\nInputStreamIterator inputStreamIterator;\\nClassFileIterator();\\nClassFileIterator(File[] filesOrDirectories,String[] pkgNameFilter);\\nClassFileIterator(InputStream[] filesOrDirectories,String[] pkgNameFilter);\\ngetName();\\nnext();\\nisZipFile(File file);\\nclassPath();\\nendsWithIgnoreCase(String value,String suffix);\\nisFile();\\n\", \"repo_level\" : \"\" }", "class_name": "ClassFileIterator", "code": "private static File[] classPath(){\n final String[] fileNames=System.getProperty(\"java.class.path\").split(File.pathSeparator);\n final File[] files=new File[fileNames.length];\n for (int i=0; i < files.length; ++i) {\n files[i]=new File(fileNames[i]);\n }\n return files;\n}\n", "docstring": "/** \n * Returns the class path of the current JVM instance as an array of {@link File} objects.\n */\n", "end_lineno": "205", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n/* ClassFileIterator.java\n *\n * Created: 2011-10-10 (Year-Month-Day)\n * Character encoding: UTF-8\n *\n ****************************************** LICENSE *******************************************\n *\n * Copyright (c) 2011 - 2018 XIAM Solutions B.V. (http://www.xiam.nl)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.atmosphere.util.annotation;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.io.DataInputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.zip.ZipFile;\n\n/**\n * {@code ClassFileIterator} is used to iterate over all Java ClassFile files available within\n * a specific context.\n *

\n * For every Java ClassFile ({@code .class}) an {@link InputStream} is returned.\n *\n * @author Ronald K. Muller\n * @since annotation-detector 3.0.0\n */\nfinal class ClassFileIterator {\n private final Logger logger = LoggerFactory.getLogger(AnnotationDetector.class);\n\n private final FileIterator fileIterator;\n private final String[] pkgNameFilter;\n private ZipFileIterator zipIterator;\n private boolean isFile;\n private final InputStreamIterator inputStreamIterator;\n\n /**\n * Create a new {@code ClassFileIterator} returning all Java ClassFile files available\n * from the class path ({@code System.getProperty(\"java.class.path\")}).\n */\n ClassFileIterator() throws IOException {\n this(classPath(), null);\n }\n\n /**\n * Create a new {@code ClassFileIterator} returning all Java ClassFile files available\n * from the specified files and/or directories, including sub directories.\n *

\n * If the (optional) package filter is defined, only class files staring with one of the\n * defined package names are returned.\n * NOTE: package names must be defined in the native format (using '/' instead of '.').\n */\n ClassFileIterator(final File[] filesOrDirectories, final String[] pkgNameFilter) {\n\n this.fileIterator = new FileIterator(filesOrDirectories);\n this.pkgNameFilter = pkgNameFilter;\n this.inputStreamIterator = null;\n }\n\n /**\n * Create a new {@code ClassFileIterator} returning all Java ClassFile files available\n * from the specified files and/or directories, including sub directories.\n *

\n * If the (optional) package filter is defined, only class files staring with one of the\n * defined package names are returned.\n * NOTE: package names must be defined in the native format (using '/' instead of '.').\n */\n ClassFileIterator(final InputStream[] filesOrDirectories, final String[] pkgNameFilter) {\n\n this.fileIterator = null;\n this.pkgNameFilter = pkgNameFilter;\n this.inputStreamIterator = new InputStreamIterator(filesOrDirectories);\n }\n\n /**\n * Return the name of the Java ClassFile returned from the last call to {@link #next()}.\n * The name is either the path name of a file or the name of an ZIP/JAR file entry.\n */\n public String getName() {\n // Both getPath() and getName() are very light weight method calls\n return zipIterator == null ?\n fileIterator.getFile().getPath() :\n zipIterator.getEntry().getName();\n }\n\n /**\n * Return {@code true} if the current {@link InputStream} is reading from a plain\n * {@link File}. Return {@code false} if the current {@link InputStream} is reading from a\n * ZIP File Entry.\n */\n public boolean isFile() {\n return isFile;\n }\n\n /**\n * Return the next Java ClassFile as an {@code InputStream}.\n *

\n * NOTICE: Client code MUST close the returned {@code InputStream}!\n */\n public InputStream next() throws IOException {\n try {\n while (true) {\n if (fileIterator != null) {\n if (zipIterator == null) {\n final File file = fileIterator.next();\n if (file == null) {\n return null;\n } else {\n final String name = file.getName();\n if (name.endsWith(\".class\")) {\n isFile = true;\n return new FileInputStream(file);\n } else if (fileIterator.isRootFile() && (endsWithIgnoreCase(name, \".jar\") || isZipFile(file)) && file.exists()) {\n try {\n zipIterator = new ZipFileIterator(new ZipFile(file), pkgNameFilter);\n } catch (Exception ex) {\n logger.debug(\"Unable to construct file {}\", file);\n return null;\n }\n } // else just ignore\n }\n } else {\n final InputStream is = zipIterator.next();\n if (is == null) {\n zipIterator = null;\n } else {\n isFile = false;\n return is;\n }\n }\n } else {\n return inputStreamIterator.next();\n }\n }\n } catch (Exception ex) {\n logger.error(\"Unable to scan classes\", ex);\n return null;\n }\n }\n\n // private\n\n private boolean isZipFile(File file) throws IOException {\n DataInputStream in = null;\n try {\n in = new DataInputStream(new FileInputStream(file));\n int n = in.readInt();\n in.close();\n return n == 0x504b0304;\n } catch (Exception ex) {\n if (in != null) in.close();\n return false;\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (IOException ex) {\n // ignore\n }\n }\n }\n }\n\n /**\n * Returns the class path of the current JVM instance as an array of {@link File} objects.\n */\n private static File[] classPath() {\n final String[] fileNames = System.getProperty(\"java.class.path\")\n .split(File.pathSeparator);\n final File[] files = new File[fileNames.length];\n for (int i = 0; i < files.length; ++i) {\n files[i] = new File(fileNames[i]);\n }\n return files;\n }\n\n private static boolean endsWithIgnoreCase(final String value, final String suffix) {\n final int n = suffix.length();\n return value.regionMatches(true, value.length() - n, suffix, 0, n);\n }\n\n}", "file_name": "ClassFileIterator.java", "human_label": "Creates an array of the file type based on all file names in java.class.path and returns the array.", "level": "slib_runnable", "lineno": "194", "name": "classPath", "oracle_context": "{ \"apis\" : \"[split, getProperty]\", \"classes\" : \"[String[], File[], File]\", \"vars\" : \"[pathSeparator, length]\" }", "package": "org.atmosphere.util.annotation", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767041a6d9265ec0178f8", "all_context": "{ \"class_level\" : \"import net.hasor.utils.BeanUtils;\\nimport net.hasor.utils.convert.ConversionException;\\nimport net.hasor.utils.convert.Converter;\\nString[] trueStrings;\\nString[] falseStrings;\\nBooleanConverter();\\nBooleanConverter(Object defaultValue);\\nBooleanConverter(String[] trueStrings,String[] falseStrings);\\nBooleanConverter(String[] trueStrings,String[] falseStrings,Object defaultValue);\\ngetDefaultType();\\ncopyStrings(String[] src);\\nconvertToType(Class type,Object value);\\n\", \"repo_level\" : \"public interface BeanUtils {static Object getDefaultValue(Class returnType);\\nstatic Object[] getDefaultValue(Class[] paramArray);\\nstatic Object invokeMethod(Object target,String methodName,Object objects);\\nstatic List findALLFields(Class target);\\nstatic List findALLMethods(Class target);\\nstatic List getFields(Class type);\\nstatic List getMethods(Class type);\\nstatic Field getField(String fieldName,Class type);\\nstatic Method getMethod(Class atClass,String name,Class[] paramType);\\nstatic List getPropertiesAndFields(Class target);\\nstatic List getProperties(Class target);\\nstatic PropertyDescriptor[] getPropertyDescriptors(Class defineType);\\nstatic Method getReadMethod(String property,Class target);\\nstatic Method getWriteMethod(String property,Class target);\\nstatic boolean hasProperty(String propertyName,Class target);\\nstatic boolean hasField(String propertyName,Class target);\\nstatic boolean hasPropertyOrField(String name,Class target);\\nstatic boolean canReadProperty(String propertyName,Class target);\\nstatic boolean canReadPropertyOrField(String propertyName,Class target);\\nstatic boolean canWriteProperty(String propertyName,Class target);\\nstatic boolean canWriteField(String propertyName,Class target);\\nstatic boolean canWritePropertyOrField(String propertyName,Class target);\\nstatic boolean writeProperty(Object object,String attName,Object value);\\nstatic boolean writeField(Object object,String fieldName,Object value);\\nstatic boolean writePropertyOrField(Object object,String attName,Object value);\\nstatic Object readProperty(Object object,String attName);\\nstatic Object readField(Object object,String fieldName);\\nstatic Object readPropertyOrField(Object object,String attName);\\nstatic Class getPropertyType(Class defineType,String attName);\\nstatic Class getFieldType(Class defineType,String attName);\\nstatic Class getPropertyOrFieldType(Class defineType,String attName);\\nstatic void copyProperties(Object dest,Object orig);\\nstatic void copyProperty(Object dest,Object orig,String propertyName);\\n }\\npublic interface ConversionException {public Throwable getCause();\\n }\\npublic interface Converter {public Object convert(Class type,Object value);\\n }\\n\" }", "class_name": "BooleanConverter", "code": "private static String[] copyStrings(final String[] src){\n String[] dst=new String[src.length];\n for (int i=0; i < src.length; ++i) {\n dst[i]=src[i].toLowerCase();\n }\n return dst;\n}\n", "docstring": "/** \n * This method creates a copy of the provided array, and ensures that all the strings in the newly created array contain only lower-case letters.

Using this method to copy string arrays means that changes to the src array do not modify the dst array.\n */\n", "end_lineno": "215", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.convert.convert;\nimport net.hasor.utils.BeanUtils;\nimport net.hasor.utils.convert.ConversionException;\nimport net.hasor.utils.convert.Converter;\n\n/**\n * {@link Converter} implementaion that handles conversion\n * to and from Boolean objects.\n * {@link Converter} implementaion that\n * handles conversion to and from java.lang.Boolean objects.\n *

\n * Can be configured to either return a default value or throw a\n * ConversionException if a conversion error occurs.\n *

\n * By default any object whose string representation is one of the values\n * {\"yes\", \"y\", \"true\", \"on\", \"1\"} is converted to Boolean.TRUE, and\n * string representations {\"no\", \"n\", \"false\", \"off\", \"0\"} are converted\n * to Boolean.FALSE. The recognised true/false strings can be changed by:\n *

\n *  String[] trueStrings = {\"oui\", \"o\", \"1\"};\n *  String[] falseStrings = {\"non\", \"n\", \"0\"};\n *  Converter bc = new BooleanConverter(trueStrings, falseStrings);\n *  ConvertUtils.register(bc, Boolean.class);\n *  ConvertUtils.register(bc, Boolean.TYPE);\n * 
\n * In addition, it is recommended that the BooleanArrayConverter also be\n * modified to recognise the same set of values:\n *
\n *   Converter bac = new BooleanArrayConverter(bc, BooleanArrayConverter.NO_DEFAULT);\n *   ConvertUtils.register(bac, bac.MODEL);\n * 
\n *

\n *\n *

Case is ignored when converting values to true or false.

\n *\n * @author Craig R. McClanahan\n * @version $Revision: 801644 $ $Date: 2009-08-06 14:38:56 +0100 (Thu, 06 Aug 2009) $\n * @since 1.3\n */\npublic final class BooleanConverter extends AbstractConverter {\n // ----------------------------------------------------------- Constructors\n\n /**\n * Create a {@link Converter} that will throw a {@link ConversionException}\n * if a conversion error occurs, ie the string value being converted is\n * not one of the known true strings, nor one of the known false strings.\n */\n public BooleanConverter() {\n super();\n }\n\n /**\n * Create a {@link Converter} that will return the specified default value\n * if a conversion error occurs, ie the string value being converted is\n * not one of the known true strings, nor one of the known false strings.\n *\n * @param defaultValue The default value to be returned if the value\n * being converted is not recognised. This value may be null, in which\n * case null will be returned on conversion failure. When non-null, it is\n * expected that this value will be either Boolean.TRUE or Boolean.FALSE.\n * The special value BooleanConverter.NO_DEFAULT can also be passed here,\n * in which case this constructor acts like the no-argument one.\n */\n public BooleanConverter(final Object defaultValue) {\n super();\n this.setDefaultValue(defaultValue);\n }\n\n /**\n * Create a {@link Converter} that will throw a {@link ConversionException}\n * if a conversion error occurs, ie the string value being converted is\n * not one of the known true strings, nor one of the known false strings.\n *

\n * The provided string arrays are copied, so that changes to the elements\n * of the array after this call is made do not affect this object.\n *\n * @param trueStrings is the set of strings which should convert to the\n * value Boolean.TRUE. The value null must not be present. Case is\n * ignored.\n *\n * @param falseStrings is the set of strings which should convert to the\n * value Boolean.TRUE. The value null must not be present. Case is\n * ignored.\n * @since 1.8.0\n */\n public BooleanConverter(final String[] trueStrings, final String[] falseStrings) {\n super();\n this.trueStrings = BooleanConverter.copyStrings(trueStrings);\n this.falseStrings = BooleanConverter.copyStrings(falseStrings);\n }\n\n /**\n * Create a {@link Converter} that will return\n * the specified default value if a conversion error occurs.\n *

\n * The provided string arrays are copied, so that changes to the elements\n * of the array after this call is made do not affect this object.\n *\n * @param trueStrings is the set of strings which should convert to the\n * value Boolean.TRUE. The value null must not be present. Case is\n * ignored.\n *\n * @param falseStrings is the set of strings which should convert to the\n * value Boolean.TRUE. The value null must not be present. Case is\n * ignored.\n *\n * @param defaultValue The default value to be returned if the value\n * being converted is not recognised. This value may be null, in which\n * case null will be returned on conversion failure. When non-null, it is\n * expected that this value will be either Boolean.TRUE or Boolean.FALSE.\n * The special value BooleanConverter.NO_DEFAULT can also be passed here,\n * in which case an exception will be thrown on conversion failure.\n * @since 1.8.0\n */\n public BooleanConverter(final String[] trueStrings, final String[] falseStrings, final Object defaultValue) {\n super();\n this.trueStrings = BooleanConverter.copyStrings(trueStrings);\n this.falseStrings = BooleanConverter.copyStrings(falseStrings);\n this.setDefaultValue(defaultValue);\n }\n // ----------------------------------------------------- Instance Variables\n /**\n * The set of strings that are known to map to Boolean.TRUE.\n */\n private String[] trueStrings = { \"true\", \"yes\", \"y\", \"on\", \"1\" };\n /**\n * The set of strings that are known to map to Boolean.FALSE.\n */\n private String[] falseStrings = { \"false\", \"no\", \"n\", \"off\", \"0\" };\n // --------------------------------------------------------- Protected Methods\n\n /**\n * Return the default type this Converter handles.\n *\n * @return The default type this Converter handles.\n * @since 1.8.0\n */\n @Override\n protected Class getDefaultType() {\n return Boolean.class;\n }\n\n /**\n * Convert the specified input object into an output object of the\n * specified type.\n *\n * @param type is the type to which this value should be converted. In the\n * case of this BooleanConverter class, this value is ignored.\n *\n * @param value is the input value to be converted. The toString method\n * shall be invoked on this object, and the result compared (ignoring\n * case) against the known \"true\" and \"false\" string values.\n *\n * @return Boolean.TRUE if the value was a recognised \"true\" value,\n * Boolean.FALSE if the value was a recognised \"false\" value, or\n * the default value if the value was not recognised and the constructor\n * was provided with a default value.\n *\n * @throws Throwable if an error occurs converting to the specified type\n * @since 1.8.0\n */\n @Override\n protected Object convertToType(final Class type, final Object value) throws Throwable {\n // All the values in the trueStrings and falseStrings arrays are\n // guaranteed to be lower-case. By converting the input value\n // to lowercase too, we can use the efficient String.equals method\n // instead of the less-efficient String.equalsIgnoreCase method.\n String stringValue = value.toString().toLowerCase();\n if (\"\".equals(stringValue)) {\n return BeanUtils.getDefaultValue(type);\n }\n for (String trueString : this.trueStrings) {\n if (trueString.equals(stringValue)) {\n return Boolean.TRUE;\n }\n }\n for (String falseString : this.falseStrings) {\n if (falseString.equals(stringValue)) {\n return Boolean.FALSE;\n }\n }\n throw new ConversionException(\"Can't convert value '\" + value + \"' to a Boolean\");\n }\n\n /**\n * This method creates a copy of the provided array, and ensures that\n * all the strings in the newly created array contain only lower-case\n * letters.\n *

\n * Using this method to copy string arrays means that changes to the\n * src array do not modify the dst array.\n */\n private static String[] copyStrings(final String[] src) {\n String[] dst = new String[src.length];\n for (int i = 0; i < src.length; ++i) {\n dst[i] = src[i].toLowerCase();\n }\n return dst;\n }\n}\n", "file_name": "BooleanConverter.java", "human_label": "Copy the source string and transfer each character to lowecase.", "level": "self_contained", "lineno": "201", "name": "copyStrings", "oracle_context": "{ \"apis\" : \"[toLowerCase]\", \"classes\" : \"[String[]]\", \"vars\" : \"[length]\" }", "package": "net.hasor.utils.convert.convert", "project": "hasor-master" }, { "_id": "636767521a6d9265ec017ecc", "all_context": "{ \"class_level\" : \"import org.jgrapht.alg.util.*;\\nimport java.util.*;\\nsplitAlongXAxis(Box2D box);\\nsplitAlongYAxis(Box2D box);\\ncontainsPoint(Box2D box,Point2D p,Comparator comparator);\\ncontainsPoint(Box2D box,Point2D p);\\n\", \"repo_level\" : \"\" }", "class_name": "Boxes", "code": "public static Pair splitAlongXAxis(Box2D box){\n double newWidth=box.getWidth() / 2d;\n double height=box.getHeight();\n return Pair.of(Box2D.of(box.getMinX(),box.getMinY(),newWidth,height),Box2D.of(box.getMinX() + newWidth,box.getMinY(),newWidth,height));\n}\n", "docstring": "/** \n * Split a box along the x axis into two equal boxes.\n * @param box the box to split\n * @return a pair with the two resulting boxes\n */\n", "end_lineno": "71", "file_content": "/*\n * (C) Copyright 2018-2021, by Dimitrios Michail and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.drawing.model;\n\nimport org.jgrapht.alg.util.*;\n\nimport java.util.*;\n\n/**\n * A collection of utilities to assist with boxes manipulation.\n * \n * @author Dimitrios Michail\n */\npublic abstract class Boxes\n{\n /**\n * Test whether a box contains a point.\n * \n * @param box the box\n * @param p the point\n * @return true if the point is contained inside the box, false otherwise\n */\n public static boolean containsPoint(Box2D box, Point2D p)\n {\n double maxX = box.getMinX() + box.getWidth();\n if (p.getX() > maxX) {\n return false;\n }\n if (p.getX() < box.getMinX()) {\n return false;\n }\n double maxY = box.getMinY() + box.getHeight();\n if (p.getY() > maxY) {\n return false;\n }\n if (p.getY() < box.getMinY()) {\n return false;\n }\n return true;\n }\n\n /**\n * Split a box along the x axis into two equal boxes.\n * \n * @param box the box to split\n * @return a pair with the two resulting boxes\n */\n public static Pair splitAlongXAxis(Box2D box)\n {\n double newWidth = box.getWidth() / 2d;\n double height = box.getHeight();\n return Pair\n .of(\n Box2D.of(box.getMinX(), box.getMinY(), newWidth, height),\n Box2D.of(box.getMinX() + newWidth, box.getMinY(), newWidth, height));\n }\n\n /**\n * Split a box along the y axis into two equal boxes.\n * \n * @param box the box to split\n * @return a pair with the two resulting boxes\n */\n public static Pair splitAlongYAxis(Box2D box)\n {\n double width = box.getWidth();\n double newHeight = box.getHeight() / 2d;\n return Pair\n .of(\n Box2D.of(box.getMinX(), box.getMinY(), width, newHeight),\n Box2D.of(box.getMinX(), box.getMinY() + newHeight, width, newHeight));\n }\n\n /**\n * Test whether a box contains a point.\n * \n * @param box the box\n * @param p the point\n * @param comparator the comparator to use\n * @return true if the point is contained inside the box, false otherwise\n */\n public static boolean containsPoint(Box2D box, Point2D p, Comparator comparator)\n {\n double maxX = box.getMinX() + box.getWidth();\n if (comparator.compare(p.getX(), maxX) > 0) {\n return false;\n }\n if (comparator.compare(p.getX(), box.getMinX()) < 0) {\n return false;\n }\n double maxY = box.getMinY() + box.getHeight();\n if (comparator.compare(p.getY(), maxY) > 0) {\n return false;\n }\n if (comparator.compare(p.getY(), box.getMinY()) < 0) {\n return false;\n }\n return true;\n }\n\n}\n", "file_name": "Boxes.java", "human_label": "Divide a box into two equal boxes on the x axis.", "level": "project_runnable", "lineno": "57", "name": "splitAlongXAxis", "oracle_context": "{ \"apis\" : \"[getWidth, getHeight, of, getMinX, getMinY]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "org.jgrapht.alg.drawing.model", "project": "jgrapht-master" }, { "_id": "636766a91a6d9265ec0175c1", "all_context": "{ \"class_level\" : \"byte[] data;\\nint length;\\nByteVector(int initialCapacity);\\nput11(int byteValue1,int byteValue2);\\nputShort(int shortValue);\\nput12(int byteValue,int shortValue);\\nputInt(int intValue);\\nput122(int byteValue,int shortValue1,int shortValue2);\\nputLong(long longValue);\\nputUTF8(String stringValue);\\nencodeUtf8(String stringValue,int offset,int maxByteLength);\\nputByteArray(byte[] byteArrayValue,int byteOffset,int byteLength);\\nenlarge(int size);\\nputByte(int byteValue);\\n\", \"repo_level\" : \"\" }", "class_name": "ByteVector", "code": "private void enlarge(final int size){\n int doubleCapacity=2 * data.length;\n int minimalCapacity=length + size;\n byte[] newData=new byte[doubleCapacity > minimalCapacity ? doubleCapacity : minimalCapacity];\n System.arraycopy(data,0,newData,0,length);\n data=newData;\n}\n", "docstring": "/** \n * Enlarges this byte vector so that it can receive 'size' more bytes.\n * @param size number of additional bytes that this byte vector should be able to receive.\n */\n", "end_lineno": "332", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage com.alibaba.fastjson2.internal.asm;\n\n/**\n * A dynamically extensible vector of bytes. This class is roughly equivalent to a DataOutputStream\n * on top of a ByteArrayOutputStream, but is more efficient.\n *\n * @author Eric Bruneton\n */\npublic class ByteVector {\n /**\n * The content of this vector. Only the first {@link #length} bytes contain real data.\n */\n byte[] data;\n\n /**\n * The actual number of bytes in this vector.\n */\n int length;\n//\n// /**\n// * Constructs a new {@link ByteVector} with a default initial capacity.\n// */\n// public ByteVector() {\n// data = new byte[64];\n// }\n\n /**\n * Constructs a new {@link ByteVector} with the given initial capacity.\n *\n * @param initialCapacity the initial capacity of the byte vector to be constructed.\n */\n public ByteVector(final int initialCapacity) {\n data = new byte[initialCapacity];\n }\n\n /**\n * Puts a byte into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param byteValue a byte.\n * @return this byte vector.\n */\n public ByteVector putByte(final int byteValue) {\n int currentLength = length;\n if (currentLength + 1 > data.length) {\n enlarge(1);\n }\n data[currentLength++] = (byte) byteValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts two bytes into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param byteValue1 a byte.\n * @param byteValue2 another byte.\n * @return this byte vector.\n */\n final ByteVector put11(final int byteValue1, final int byteValue2) {\n int currentLength = length;\n if (currentLength + 2 > data.length) {\n enlarge(2);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue1;\n currentData[currentLength++] = (byte) byteValue2;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a short into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param shortValue a short.\n * @return this byte vector.\n */\n public ByteVector putShort(final int shortValue) {\n int currentLength = length;\n if (currentLength + 2 > data.length) {\n enlarge(2);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a byte and a short into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteValue a byte.\n * @param shortValue a short.\n * @return this byte vector.\n */\n final ByteVector put12(final int byteValue, final int shortValue) {\n int currentLength = length;\n if (currentLength + 3 > data.length) {\n enlarge(3);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an int into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param intValue an int.\n * @return this byte vector.\n */\n public ByteVector putInt(final int intValue) {\n int currentLength = length;\n if (currentLength + 4 > data.length) {\n enlarge(4);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts one byte and two shorts into this byte vector. The byte vector is automatically enlarged\n * if necessary.\n *\n * @param byteValue a byte.\n * @param shortValue1 a short.\n * @param shortValue2 another short.\n * @return this byte vector.\n */\n final ByteVector put122(final int byteValue, final int shortValue1, final int shortValue2) {\n int currentLength = length;\n if (currentLength + 5 > data.length) {\n enlarge(5);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue;\n currentData[currentLength++] = (byte) (shortValue1 >>> 8);\n currentData[currentLength++] = (byte) shortValue1;\n currentData[currentLength++] = (byte) (shortValue2 >>> 8);\n currentData[currentLength++] = (byte) shortValue2;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a long into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param longValue a long.\n * @return this byte vector.\n */\n public ByteVector putLong(final long longValue) {\n int currentLength = length;\n if (currentLength + 8 > data.length) {\n enlarge(8);\n }\n byte[] currentData = data;\n int intValue = (int) (longValue >>> 32);\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n intValue = (int) longValue;\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param stringValue a String whose UTF8 encoded length must be less than 65536.\n * @return this byte vector.\n */\n // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility).\n public ByteVector putUTF8(final String stringValue) {\n int charLength = stringValue.length();\n if (charLength > 65535) {\n throw new IllegalArgumentException(\"UTF8 string too large\");\n }\n int currentLength = length;\n if (currentLength + 2 + charLength > data.length) {\n enlarge(2 + charLength);\n }\n byte[] currentData = data;\n // Optimistic algorithm: instead of computing the byte length and then serializing the string\n // (which requires two loops), we assume the byte length is equal to char length (which is the\n // most frequent case), and we start serializing the string right away. During the\n // serialization, if we find that this assumption is wrong, we continue with the general method.\n currentData[currentLength++] = (byte) (charLength >>> 8);\n currentData[currentLength++] = (byte) charLength;\n for (int i = 0; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= '\\u0001' && charValue <= '\\u007F') {\n currentData[currentLength++] = (byte) charValue;\n } else {\n length = currentLength;\n return encodeUtf8(stringValue, i, 65535);\n }\n }\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if\n * necessary. The string length is encoded in two bytes before the encoded characters, if there is\n * space for that (i.e. if this.length - offset - 2 >= 0).\n *\n * @param stringValue the String to encode.\n * @param offset the index of the first character to encode. The previous characters are supposed\n * to have already been encoded, using only one byte per character.\n * @param maxByteLength the maximum byte length of the encoded string, including the already\n * encoded characters.\n * @return this byte vector.\n */\n final ByteVector encodeUtf8(final String stringValue, final int offset, final int maxByteLength) {\n int charLength = stringValue.length();\n int byteLength = offset;\n for (int i = offset; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= 0x0001 && charValue <= 0x007F) {\n byteLength++;\n } else if (charValue <= 0x07FF) {\n byteLength += 2;\n } else {\n byteLength += 3;\n }\n }\n if (byteLength > maxByteLength) {\n throw new IllegalArgumentException(\"UTF8 string too large\");\n }\n // Compute where 'byteLength' must be stored in 'data', and store it at this location.\n int byteLengthOffset = length - offset - 2;\n if (byteLengthOffset >= 0) {\n data[byteLengthOffset] = (byte) (byteLength >>> 8);\n data[byteLengthOffset + 1] = (byte) byteLength;\n }\n if (length + byteLength - offset > data.length) {\n enlarge(byteLength - offset);\n }\n int currentLength = length;\n for (int i = offset; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= 0x0001 && charValue <= 0x007F) {\n data[currentLength++] = (byte) charValue;\n } else if (charValue <= 0x07FF) {\n data[currentLength++] = (byte) (0xC0 | charValue >> 6 & 0x1F);\n data[currentLength++] = (byte) (0x80 | charValue & 0x3F);\n } else {\n data[currentLength++] = (byte) (0xE0 | charValue >> 12 & 0xF);\n data[currentLength++] = (byte) (0x80 | charValue >> 6 & 0x3F);\n data[currentLength++] = (byte) (0x80 | charValue & 0x3F);\n }\n }\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an array of bytes into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteArrayValue an array of bytes. May be {@literal null} to put {@code byteLength} null\n * bytes into this byte vector.\n * @param byteOffset index of the first byte of byteArrayValue that must be copied.\n * @param byteLength number of bytes of byteArrayValue that must be copied.\n * @return this byte vector.\n */\n public ByteVector putByteArray(\n final byte[] byteArrayValue, final int byteOffset, final int byteLength) {\n if (length + byteLength > data.length) {\n enlarge(byteLength);\n }\n if (byteArrayValue != null) {\n System.arraycopy(byteArrayValue, byteOffset, data, length, byteLength);\n }\n length += byteLength;\n return this;\n }\n\n /**\n * Enlarges this byte vector so that it can receive 'size' more bytes.\n *\n * @param size number of additional bytes that this byte vector should be able to receive.\n */\n private void enlarge(final int size) {\n int doubleCapacity = 2 * data.length;\n int minimalCapacity = length + size;\n byte[] newData = new byte[doubleCapacity > minimalCapacity ? doubleCapacity : minimalCapacity];\n System.arraycopy(data, 0, newData, 0, length);\n data = newData;\n }\n}\n", "file_name": "ByteVector.java", "human_label": "Convert the original data array to a longer array.", "level": "self_contained", "lineno": "321", "name": "enlarge", "oracle_context": "{ \"apis\" : \"[arraycopy]\", \"classes\" : \"[byte[], data]\", \"vars\" : \"[length, data]\" }", "package": "com.alibaba.fastjson2.internal.asm", "project": "fastjson2-main" }, { "_id": "636767781a6d9265ec018238", "all_context": "{ \"class_level\" : \"import org.apache.log4j.spi.AppenderAttachable;\\nimport org.apache.log4j.spi.LoggingEvent;\\nimport org.apache.log4j.Appender;\\nimport java.util.Vector;\\nimport java.util.Enumeration;\\nVector appenderList;\\nappendLoopOnAppenders(LoggingEvent event);\\ngetAllAppenders();\\ngetAppender(String name);\\nisAttached(Appender appender);\\nremoveAllAppenders();\\nremoveAppender(Appender appender);\\nremoveAppender(String name);\\naddAppender(Appender newAppender);\\n\", \"repo_level\" : \"public interface AppenderAttachable {public void addAppender(Appender newAppender);\\npublic Enumeration getAllAppenders();\\npublic Appender getAppender(String name);\\npublic boolean isAttached(Appender appender);\\n void removeAllAppenders();\\n void removeAppender(Appender appender);\\n void removeAppender(String name);\\n }\\npublic interface LoggingEvent {public LocationInfo getLocationInformation();\\npublic Level getLevel();\\npublic String getLoggerName();\\npublic Category getLogger();\\npublic Object getMessage();\\npublic String getNDC();\\npublic Object getMDC(String key);\\npublic void getMDCCopy();\\npublic String getRenderedMessage();\\nstatic long getStartTime();\\npublic String getThreadName();\\npublic ThrowableInformation getThrowableInformation();\\npublic String[] getThrowableStrRep();\\nfinal void setProperty(String propName,String propValue);\\nfinal String getProperty(String key);\\nfinal boolean locationInformationExists();\\nfinal long getTimeStamp();\\npublic Set getPropertyKeySet();\\npublic Map getProperties();\\npublic String getFQNOfLoggerClass();\\npublic Object removeProperty(String propName);\\n }\\npublic interface Appender { void addFilter(Filter newFilter);\\npublic Filter getFilter();\\npublic void clearFilters();\\npublic void close();\\npublic void doAppend(LoggingEvent event);\\npublic String getName();\\npublic void setErrorHandler(ErrorHandler errorHandler);\\npublic ErrorHandler getErrorHandler();\\npublic void setLayout(Layout layout);\\npublic Layout getLayout();\\npublic void setName(String name);\\npublic boolean requiresLayout();\\n }\\n\" }", "class_name": "AppenderAttachableImpl", "code": "public boolean isAttached(Appender appender){\n if (appenderList == null || appender == null) return false;\n int size=appenderList.size();\n Appender a;\n for (int i=0; i < size; i++) {\n a=(Appender)appenderList.elementAt(i);\n if (a == appender) return true;\n }\n return false;\n}\n", "docstring": "/** \n * Returns true if the specified appender is in the list of attached appenders, false otherwise.\n * @since 1.2 \n */\n", "end_lineno": "128", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.log4j.helpers;\n\nimport org.apache.log4j.spi.AppenderAttachable;\nimport org.apache.log4j.spi.LoggingEvent;\n\nimport org.apache.log4j.Appender;\nimport java.util.Vector;\nimport java.util.Enumeration;\n\n/**\n A straightforward implementation of the {@link AppenderAttachable}\n interface.\n\n @author Ceki Gülcü\n @since version 0.9.1 */\npublic class AppenderAttachableImpl implements AppenderAttachable {\n \n /** Array of appenders. */\n protected Vector appenderList;\n\n /**\n Attach an appender. If the appender is already in the list in\n won't be added again.\n */\n public\n void addAppender(Appender newAppender) {\n // Null values for newAppender parameter are strictly forbidden.\n if(newAppender == null)\n return;\n \n if(appenderList == null) {\n appenderList = new Vector(1);\n }\n if(!appenderList.contains(newAppender))\n appenderList.addElement(newAppender);\n }\n\n /**\n Call the doAppend method on all attached appenders. */\n public\n int appendLoopOnAppenders(LoggingEvent event) {\n int size = 0;\n Appender appender;\n\n if(appenderList != null) {\n size = appenderList.size();\n for(int i = 0; i < size; i++) {\n\tappender = (Appender) appenderList.elementAt(i);\n\tappender.doAppend(event);\n }\n } \n return size;\n }\n\n\n /**\n Get all attached appenders as an Enumeration. If there are no\n attached appenders null is returned.\n \n @return Enumeration An enumeration of attached appenders.\n */\n public\n Enumeration getAllAppenders() {\n if(appenderList == null)\n return null;\n else \n return appenderList.elements(); \n }\n\n /**\n Look for an attached appender named as name.\n\n

Return the appender with that name if in the list. Return null\n otherwise. \n \n */\n public\n Appender getAppender(String name) {\n if(appenderList == null || name == null)\n return null;\n\n int size = appenderList.size();\n Appender appender;\n for(int i = 0; i < size; i++) {\n appender = (Appender) appenderList.elementAt(i);\n if(name.equals(appender.getName()))\n\t return appender;\n }\n return null; \n }\n\n\n /**\n Returns true if the specified appender is in the\n list of attached appenders, false otherwise.\n\n @since 1.2 */\n public \n boolean isAttached(Appender appender) {\n if(appenderList == null || appender == null)\n return false;\n\n int size = appenderList.size();\n Appender a;\n for(int i = 0; i < size; i++) {\n a = (Appender) appenderList.elementAt(i);\n if(a == appender)\n\t return true;\n }\n return false; \n }\n\n\n\n /**\n * Remove and close all previously attached appenders.\n * */\n public\n void removeAllAppenders() {\n if(appenderList != null) {\n int len = appenderList.size(); \n for(int i = 0; i < len; i++) {\n\tAppender a = (Appender) appenderList.elementAt(i);\n\ta.close();\n }\n appenderList.removeAllElements();\n appenderList = null; \n }\n }\n\n\n /**\n Remove the appender passed as parameter form the list of attached\n appenders. */\n public\n void removeAppender(Appender appender) {\n if(appender == null || appenderList == null) \n return;\n appenderList.removeElement(appender); \n }\n\n\n /**\n Remove the appender with the name passed as parameter form the\n list of appenders. \n */\n public\n void removeAppender(String name) {\n if(name == null || appenderList == null) return;\n int size = appenderList.size();\n for(int i = 0; i < size; i++) {\n if(name.equals(((Appender)appenderList.elementAt(i)).getName())) {\n\t appenderList.removeElementAt(i);\n\t break;\n }\n }\n }\n\n}\n", "file_name": "AppenderAttachableImpl.java", "human_label": "Check whether appender elements exist in appenderList. If yes, true is returned. Otherwise, false is returned.", "level": "project_runnable", "lineno": "110", "name": "isAttached", "oracle_context": "{ \"apis\" : \"[elementAt]\", \"classes\" : \"[Appender]\", \"vars\" : \"[appenderList]\" }", "package": "org.apache.log4j.helpers", "project": "logging-log4j1-main" }, { "_id": "6367674a1a6d9265ec017dab", "all_context": "{ \"class_level\" : \"import java.io.*;\\nimport java.util.*;\\nlong serialVersionUID;\\ndouble DEFAULT_EPSILON;\\ndouble epsilon;\\nToleranceDoubleComparator();\\nToleranceDoubleComparator(double epsilon);\\n\", \"repo_level\" : \"\" }", "class_name": "ToleranceDoubleComparator", "code": "@Override public int compare(Double o1,Double o2){\n if (Math.abs(o1 - o2) < epsilon) {\n return 0;\n }\n else {\n return Double.compare(o1,o2);\n }\n}\n", "docstring": "/** \n * Compares two floating point values. Returns 0 if they are equal, -1 if {@literal o1 < o2}, 1 otherwise\n * @param o1 the first value\n * @param o2 the second value\n * @return 0 if they are equal, -1 if {@literal o1 < o2}, 1 otherwise\n */\n", "end_lineno": "79", "file_content": "/*\n * (C) Copyright 2016-2021, by Dimitrios Michail and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.util;\n\nimport java.io.*;\nimport java.util.*;\n\n/**\n * A double comparator with adjustable tolerance.\n *\n * @author Dimitrios Michail\n */\npublic class ToleranceDoubleComparator\n implements\n Comparator,\n Serializable\n{\n private static final long serialVersionUID = -3819451375975842372L;\n\n /**\n * Default tolerance used by the comparator.\n */\n public static final double DEFAULT_EPSILON = 1e-9;\n\n private final double epsilon;\n\n /**\n * Construct a new comparator with a {@link #DEFAULT_EPSILON} tolerance.\n */\n public ToleranceDoubleComparator()\n {\n this(DEFAULT_EPSILON);\n }\n\n /**\n * Construct a new comparator with a specified tolerance.\n * \n * @param epsilon the tolerance\n */\n public ToleranceDoubleComparator(double epsilon)\n {\n if (epsilon <= 0.0) {\n throw new IllegalArgumentException(\"Tolerance must be positive\");\n }\n this.epsilon = epsilon;\n }\n\n /**\n * Compares two floating point values. Returns 0 if they are equal, -1 if {@literal o1 < o2}, 1\n * otherwise\n * \n * @param o1 the first value\n * @param o2 the second value\n * @return 0 if they are equal, -1 if {@literal o1 < o2}, 1 otherwise\n */\n @Override\n public int compare(Double o1, Double o2)\n {\n if (Math.abs(o1 - o2) < epsilon) {\n return 0;\n } else {\n return Double.compare(o1, o2);\n }\n }\n}\n", "file_name": "ToleranceDoubleComparator.java", "human_label": "Compares two values. If the difference between the two values is less than epsilon, 0 is returned. Otherwise, Double.compare is invoked.", "level": "slib_runnable", "lineno": "63", "name": "compare", "oracle_context": "{ \"apis\" : \"[abs]\", \"classes\" : \"[]\", \"vars\" : \"[epsilon]\" }", "package": "org.jgrapht.alg.util", "project": "jgrapht-master" }, { "_id": "6367672d1a6d9265ec017c78", "all_context": "{ \"class_level\" : \"HashMap map;\\nArrayList values;\\nRandomizedSet();\\nremove(int val);\\ngetRandom();\\n\", \"repo_level\" : \"\" }", "class_name": "RandomizedSet", "code": "public boolean insert(int val){\n if (!map.containsKey(val)) {\n map.put(val,val);\n values.add(val);\n return true;\n }\n else {\n return false;\n }\n}\n", "docstring": "/** \n * Inserts a value to the set. Returns true if the set did not already contain the specified element. \n */\n", "end_lineno": "52", "file_content": "//Design a data structure that supports all following operations in average O(1) time.\n\n//insert(val): Inserts an item val to the set if not already present.\n//remove(val): Removes an item val from the set if present.\n//getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.\n\n//Example:\n// Init an empty set.\n//RandomizedSet randomSet = new RandomizedSet();\n\n// Inserts 1 to the set. Returns true as 1 was inserted successfully.\n//randomSet.insert(1);\n\n// Returns false as 2 does not exist in the set.\n//randomSet.remove(2);\n\n// Inserts 2 to the set, returns true. Set now contains [1,2].\n//randomSet.insert(2);\n\n// getRandom should return either 1 or 2 randomly.\n//randomSet.getRandom();\n\n// Removes 1 from the set, returns true. Set now contains [2].\n//randomSet.remove(1);\n\n// 2 was already in the set, so return false.\n//randomSet.insert(2);\n\n// Since 2 is the only number in the set, getRandom always return 2.\n//randomSet.getRandom();\n\nclass RandomizedSet {\n HashMap map;\n ArrayList values;\n\n /** Initialize your data structure here. */\n public RandomizedSet() {\n map = new HashMap();\n values = new ArrayList();\n }\n \n /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */\n public boolean insert(int val) {\n if(!map.containsKey(val)) {\n map.put(val, val);\n values.add(val);\n return true;\n }\n else {\n return false;\n }\n }\n \n /** Removes a value from the set. Returns true if the set contained the specified element. */\n public boolean remove(int val) {\n if(map.containsKey(val)) {\n map.remove(val);\n values.remove(values.indexOf(val));\n return true;\n }\n return false;\n }\n \n /** Get a random element from the set. */\n public int getRandom() {\n int random = (int)(Math.random() * values.size());\n int valueToReturn = values.get(random);\n return map.get(valueToReturn);\n }\n}\n\n/**\n * Your RandomizedSet object will be instantiated and called as such:\n * RandomizedSet obj = new RandomizedSet();\n * boolean param_1 = obj.insert(val);\n * boolean param_2 = obj.remove(val);\n * int param_3 = obj.getRandom();\n */\n\n", "file_name": "InsertDeleteGetRandomO1.java", "human_label": "If the key whose value is val does not exist in the map, add (val, val) to the map and return true. Otherwise, return false.", "level": "self_contained", "lineno": "42", "name": "insert", "oracle_context": "{ \"apis\" : \"[containsKey, put, add]\", \"classes\" : \"[]\", \"vars\" : \"[map, values]\" }", "package": "", "project": "interviews-master" }, { "_id": "636767dc1a6d9265ec0186c6", "all_context": "{ \"class_level\" : \"import java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Objects;\\nimport java.util.stream.Collectors;\\nimport org.apache.skywalking.library.elasticsearch.response.Mappings;\\nimport org.apache.skywalking.oap.server.library.client.elasticsearch.ElasticSearchClient;\\nMap structures;\\nMap properties;\\nMappings.Source source;\\nIndexStructures();\\ngetMapping(String tableName);\\ndiffStructure(String tableName,Mappings mappings);\\ncontainsStructure(String tableName,Mappings mappings);\\nFields(Mappings mapping);\\ncontainsAllFields(Fields fields);\\nappendNewFields(Fields fields);\\ndiffFields(Fields fields);\\nputStructure(String tableName,Mappings mapping);\\n\", \"repo_level\" : \"public interface Mappings { }\\npublic interface ElasticSearchClient {public void connect();\\npublic void shutdown();\\npublic void registerChecker(HealthChecker healthChecker);\\npublic boolean createIndex(String indexName);\\npublic boolean createIndex(String indexName,Mappings mappings,Map settings);\\npublic boolean updateIndexMapping(String indexName,Mappings mapping);\\npublic Optional getIndex(String indexName);\\npublic Collection retrievalIndexByAliases(String alias);\\npublic boolean deleteByIndexName(String indexName);\\npublic boolean isExistsIndex(String indexName);\\npublic Optional getTemplate(String name);\\npublic boolean isExistsTemplate(String indexName);\\npublic boolean createOrUpdateTemplate(String indexName,Map settings,Mappings mapping,int order);\\npublic boolean deleteTemplate(String indexName);\\npublic SearchResponse search(Supplier indices,Search search);\\npublic SearchResponse search(String indexName,Search search);\\npublic SearchResponse search(String indexName,Search search,SearchParams params);\\npublic SearchResponse scroll(Duration contextRetention,String scrollId);\\npublic boolean deleteScrollContextQuietly(String scrollId);\\npublic Optional get(String indexName,String id);\\npublic boolean existDoc(String indexName,String id);\\npublic Optional ids(Map indexIds);\\npublic SearchResponse searchIDs(String indexName,Iterable ids);\\npublic void forceInsert(String indexName,String id,Map source);\\npublic void forceUpdate(String indexName,String id,Map source);\\npublic IndexRequestWrapper prepareInsert(String indexName,String id,Map source);\\npublic UpdateRequestWrapper prepareUpdate(String indexName,String id,Map source);\\npublic BulkProcessor createBulkProcessor(int bulkActions,int flushInterval,int concurrentRequests);\\npublic String formatIndexName(String indexName);\\n }\\n\" }", "class_name": "IndexStructures", "code": "private boolean containsAllFields(Fields fields){\n if (this.properties.size() < fields.properties.size()) {\n return false;\n }\n boolean isContains=fields.properties.entrySet().stream().allMatch(item -> Objects.equals(properties.get(item.getKey()),item.getValue()));\n if (!isContains) {\n return false;\n }\n return fields.source.getExcludes().containsAll(this.source.getExcludes());\n}\n", "docstring": "/** \n * Returns ture when the input fields have already been stored in the properties.\n */\n", "end_lineno": "125", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.stream.Collectors;\nimport org.apache.skywalking.library.elasticsearch.response.Mappings;\nimport org.apache.skywalking.oap.server.library.client.elasticsearch.ElasticSearchClient;\n\npublic class IndexStructures {\n private final Map structures;\n\n public IndexStructures() {\n this.structures = new HashMap<>();\n }\n\n public Mappings getMapping(String tableName) {\n Map properties =\n structures.containsKey(tableName) ?\n structures.get(tableName).properties : new HashMap<>();\n Mappings.Source source =\n structures.containsKey(tableName) ?\n structures.get(tableName).source : new Mappings.Source();\n return Mappings.builder()\n .type(ElasticSearchClient.TYPE)\n .properties(properties)\n .source(source)\n .build();\n }\n\n /**\n * Add or append field when the current structures don't contain the input structure or having\n * new fields in it.\n */\n public void putStructure(String tableName, Mappings mapping) {\n if (Objects.isNull(mapping)\n || Objects.isNull(mapping.getProperties())\n || mapping.getProperties().isEmpty()) {\n return;\n }\n Fields fields = new Fields(mapping);\n if (structures.containsKey(tableName)) {\n structures.get(tableName).appendNewFields(fields);\n } else {\n structures.put(tableName, fields);\n }\n }\n\n /**\n * Returns mappings with fields that not exist in the input mappings.\n * The input mappings should be history mapping from current index.\n * Do not return _source config to avoid current index update conflict.\n */\n public Mappings diffStructure(String tableName, Mappings mappings) {\n if (!structures.containsKey(tableName)) {\n return new Mappings();\n }\n Map properties = mappings.getProperties();\n Map diffProperties =\n structures.get(tableName).diffFields(new Fields(mappings));\n return Mappings.builder()\n .type(ElasticSearchClient.TYPE)\n .properties(diffProperties)\n .build();\n }\n\n /**\n * Returns true when the current structures already contains the properties of the input\n * mappings.\n */\n public boolean containsStructure(String tableName, Mappings mappings) {\n if (Objects.isNull(mappings) ||\n Objects.isNull(mappings.getProperties()) ||\n mappings.getProperties().isEmpty()) {\n return true;\n }\n return structures.containsKey(tableName)\n && structures.get(tableName)\n .containsAllFields(new Fields(mappings));\n }\n\n /**\n * The properties of the template or index.\n */\n public static class Fields {\n private final Map properties;\n private Mappings.Source source;\n\n private Fields(Mappings mapping) {\n this.properties = mapping.getProperties();\n this.source = mapping.getSource();\n }\n\n /**\n * Returns ture when the input fields have already been stored in the properties.\n */\n private boolean containsAllFields(Fields fields) {\n if (this.properties.size() < fields.properties.size()) {\n return false;\n }\n boolean isContains = fields.properties.entrySet().stream()\n .allMatch(item -> Objects.equals(properties.get(item.getKey()), item.getValue()));\n if (!isContains) {\n return false;\n }\n return fields.source.getExcludes().containsAll(this.source.getExcludes());\n }\n\n /**\n * Append new fields and update.\n * Properties combine input and exist, update property's attribute, won't remove old one.\n * Source will be updated to the input.\n */\n private void appendNewFields(Fields fields) {\n properties.putAll(fields.properties);\n source = fields.source;\n }\n\n /**\n * Returns the properties that not exist in the input fields.\n */\n private Map diffFields(Fields fields) {\n return this.properties.entrySet().stream()\n .filter(e -> !fields.properties.containsKey(e.getKey()))\n .collect(Collectors.toMap(\n Map.Entry::getKey,\n Map.Entry::getValue\n ));\n }\n }\n}\n", "file_name": "IndexStructures.java", "human_label": "Check whether all fields exist in properties.", "level": "slib_runnable", "lineno": "112", "name": "containsAllFields", "oracle_context": "{ \"apis\" : \"[size, allMatch, stream, entrySet, equals, get, getKey, getValue, containsAll, getExcludes, Fields]\", \"classes\" : \"[]\", \"vars\" : \"[properties, source]\" }", "package": "org.apache.skywalking.oap.server.storage.plugin.elasticsearch.base", "project": "skywalking-master" }, { "_id": "636766821a6d9265ec0174bf", "all_context": "{ \"class_level\" : \"import org.slf4j.Logger;\\nimport org.slf4j.LoggerFactory;\\nimport java.io.File;\\nimport java.io.FilenameFilter;\\nimport java.io.IOException;\\nimport java.lang.reflect.Method;\\nimport java.net.InetAddress;\\nimport java.net.MalformedURLException;\\nimport java.net.URL;\\nimport java.net.UnknownHostException;\\nimport java.util.Hashtable;\\nimport java.util.StringTokenizer;\\nimport java.util.Vector;\\nLogger logger;\\nHashtable,Method[]> objectMethods;\\nObject[] emptyArray;\\nint dbg;\\nsetAttribute(Object proxy,String name,Object value);\\ngetAttribute(Object proxy,String name);\\nsetProperty(Object o,String name,String value);\\naddProperty(Object o,String name,String value);\\ninvokeProperty(Object object,String setter,String name,String value);\\ngetProperty(Object object,String name);\\nsetProperty(Object object,String name);\\nreplaceProperties(String value,Hashtable staticProp,PropertySource dynamicProp);\\ncapitalize(String name);\\nunCapitalize(String name);\\naddToClassPath(Vector cpV,String dir);\\naddToolsJar(Vector v);\\ngetFilesByExt(String ld,String ext);\\naccept(File d,String name);\\ngetURL(String base,String file);\\naddJarsFromClassPath(Vector jars,String cp);\\ngetClassPath(Vector v);\\ngetClassPath(String dir,String cpath,String cpathProp,boolean addTools);\\nprocessArgs(Object proxy,String args);\\nprocessArgs(Object proxy,String args,String args0,String args1,Hashtable aliases);\\nclear();\\nfindVoidSetters(Class c);\\nfindBooleanSetters(Class c);\\nfindMethods(Class c);\\nfindMethod(Class c,String name,Class params);\\nhasHook(Object obj,String methodN);\\ncallMain(Class c,String args);\\ncallMethod1(Object target,String methodN,Object param1,String typeParam1,ClassLoader cl);\\ncallMethod0(Object target,String methodN);\\ncallMethodN(Object target,String methodN,Object params,Class typeParams);\\nconvert(String object,Class paramType);\\ngetProperty(String key);\\nsetAttribute(String key,Object o);\\ndebug(String s);\\nexecute(Object proxy,String method);\\n\", \"repo_level\" : \"\" }", "class_name": "IntrospectionUtils", "code": "public static String capitalize(String name){\n if (name == null || name.length() == 0) {\n return name;\n }\n char chars[]=name.toCharArray();\n chars[0]=Character.toUpperCase(chars[0]);\n return new String(chars);\n}\n", "docstring": "/** \n * Reverse of Introspector.decapitalize\n */\n", "end_lineno": "384", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n\n/*\n * This file incorporates work covered by the following copyright and\n * permission notice:\n *\n * Copyright 2004 The Apache Software Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.atmosphere.util;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.io.IOException;\nimport java.lang.reflect.Method;\nimport java.net.InetAddress;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.net.UnknownHostException;\nimport java.util.Hashtable;\nimport java.util.StringTokenizer;\nimport java.util.Vector;\n\n/**\n * Utils for introspection and reflection\n */\npublic final class IntrospectionUtils {\n\n private static final Logger logger = LoggerFactory.getLogger(IntrospectionUtils.class);\n\n /**\n * Call execute() - any ant-like task should work\n */\n public static void execute(Object proxy, String method) throws Exception {\n Method executeM = null;\n Class c = proxy.getClass();\n Class params[] = new Class[0];\n // params[0]=args.getClass();\n executeM = findMethod(c, method, params);\n if (executeM == null) {\n throw new RuntimeException(\"No execute in \" + proxy.getClass());\n }\n executeM.invoke(proxy, (Object[]) null);//new Object[] { args });\n }\n\n /**\n * Call void setAttribute( String ,Object )\n */\n public static void setAttribute(Object proxy, String name, Object value)\n throws Exception {\n if (proxy instanceof AttributeHolder) {\n ((AttributeHolder) proxy).setAttribute(name, value);\n return;\n }\n\n Method executeM = null;\n Class c = proxy.getClass();\n Class params[] = new Class[2];\n params[0] = String.class;\n params[1] = Object.class;\n executeM = findMethod(c, \"setAttribute\", params);\n if (executeM == null) {\n logger.debug(\"No setAttribute in {}\", proxy.getClass());\n return;\n }\n\n logger.debug(\"Setting {}={} in proxy: {}\", new Object[]{name, value, proxy});\n executeM.invoke(proxy, new Object[]{name, value});\n return;\n }\n\n /**\n * Call void getAttribute( String )\n */\n public static Object getAttribute(Object proxy, String name) throws Exception {\n Class c = proxy.getClass();\n Class params[] = new Class[1];\n params[0] = String.class;\n Method executeM = findMethod(c, \"getAttribute\", params);\n if (executeM == null) {\n logger.debug(\"No getAttribute in {}\", proxy.getClass());\n return null;\n }\n return executeM.invoke(proxy, new Object[]{name});\n }\n\n\n /**\n * Find a method with the right name If found, call the method ( if param is\n * int or boolean we'll convert value to the right type before) - that means\n * you can have setDebug(1).\n */\n final public static boolean setProperty(Object o, String name, String value) {\n String setter = \"set\" + capitalize(name);\n return invokeProperty(o, setter, name, value);\n }\n\n final public static boolean addProperty(Object o, String name, String value) {\n String setter = \"add\" + capitalize(name);\n return invokeProperty(o, setter, name, value);\n }\n\n final static public boolean invokeProperty(Object object, String setter, String name, String value) {\n try {\n Method methods[] = findMethods(object.getClass());\n Method setPropertyMethodVoid = null;\n Method setPropertyMethodBool = null;\n\n // First, the ideal case - a setFoo( String ) method\n for (int i = 0; i < methods.length; i++) {\n Class paramT[] = methods[i].getParameterTypes();\n if (setter.equals(methods[i].getName()) && paramT.length == 1\n && \"java.lang.String\".equals(paramT[0].getName())) {\n\n methods[i].invoke(object, new Object[]{value});\n return true;\n }\n }\n\n // Try a setFoo ( int ) or ( boolean )\n for (int i = 0; i < methods.length; i++) {\n boolean ok = true;\n if (setter.equals(methods[i].getName())\n && methods[i].getParameterTypes().length == 1) {\n\n // match - find the type and invoke it\n Class paramType = methods[i].getParameterTypes()[0];\n Object params[] = new Object[1];\n\n // Try a setFoo ( int )\n if (\"java.lang.Integer\".equals(paramType.getName())\n || \"int\".equals(paramType.getName())) {\n try {\n params[0] = new Integer(value);\n } catch (NumberFormatException ex) {\n ok = false;\n }\n // Try a setFoo ( long )\n } else if (\"java.lang.Long\".equals(paramType.getName())\n || \"long\".equals(paramType.getName())) {\n try {\n params[0] = new Long(value);\n } catch (NumberFormatException ex) {\n ok = false;\n }\n\n // Try a setFoo ( boolean )\n } else if (\"java.lang.Boolean\".equals(paramType.getName())\n || \"boolean\".equals(paramType.getName())) {\n params[0] = new Boolean(value);\n\n // Try a setFoo ( InetAddress )\n } else if (\"java.net.InetAddress\".equals(paramType\n .getName())) {\n try {\n params[0] = InetAddress.getByName(value);\n } catch (UnknownHostException exc) {\n debug(\"Unable to resolve host name:\" + value);\n ok = false;\n }\n\n // Unknown type\n } else {\n debug(\"Unknown type \" + paramType.getName());\n }\n\n if (ok) {\n methods[i].invoke(object, params);\n return true;\n }\n }\n\n // save \"setProperty\" for later\n if (\"setProperty\".equals(methods[i].getName())) {\n if (methods[i].getReturnType() == Boolean.TYPE) {\n setPropertyMethodBool = methods[i];\n } else {\n setPropertyMethodVoid = methods[i];\n }\n\n }\n }\n\n // Ok, no setXXX found, try a setProperty(\"name\", \"value\")\n if (setPropertyMethodBool != null || setPropertyMethodVoid != null) {\n Object params[] = new Object[2];\n params[0] = name;\n params[1] = value;\n if (setPropertyMethodBool != null) {\n try {\n return (Boolean) setPropertyMethodBool.invoke(object, params);\n } catch (IllegalArgumentException biae) {\n //the boolean method had the wrong\n //parameter types. lets try the other\n if (setPropertyMethodVoid != null) {\n setPropertyMethodVoid.invoke(object, params);\n return true;\n } else {\n throw biae;\n }\n }\n } else {\n setPropertyMethodVoid.invoke(object, params);\n return true;\n }\n }\n\n } catch (IllegalArgumentException e) {\n logger.info(\"failed, object: \" + object + \", setter: \" + setter + \", value: \" + value, e);\n } catch (Exception e) {\n if (dbg > 0) {\n debug(e.getClass().getSimpleName() + \" for \" + object.getClass() + \" \" + setter + \"=\" + value + \")\");\n }\n if (dbg > 1) {\n logger.debug(\"\", e);\n }\n }\n\n return false;\n }\n\n public static Object getProperty(Object object, String name) {\n String getter = \"get\" + capitalize(name);\n String isGetter = \"is\" + capitalize(name);\n\n try {\n Method methods[] = findMethods(object.getClass());\n Method getPropertyMethod = null;\n\n // First, the ideal case - a getFoo() method\n for (int i = 0; i < methods.length; i++) {\n Class paramT[] = methods[i].getParameterTypes();\n if (getter.equals(methods[i].getName()) && paramT.length == 0) {\n return methods[i].invoke(object, (Object[]) null);\n }\n if (isGetter.equals(methods[i].getName()) && paramT.length == 0) {\n return methods[i].invoke(object, (Object[]) null);\n }\n\n if (\"getProperty\".equals(methods[i].getName())) {\n getPropertyMethod = methods[i];\n }\n }\n\n // Ok, no setXXX found, try a getProperty(\"name\")\n if (getPropertyMethod != null) {\n Object params[] = new Object[1];\n params[0] = name;\n return getPropertyMethod.invoke(object, params);\n }\n\n } catch (IllegalArgumentException e) {\n logger.info(\"failed, object: \" + object + \", name: \" + name, e);\n } catch (Exception e) {\n if (dbg > 0) {\n debug(e.getClass().getSimpleName() + \" for \" + object.getClass() + \" \" + name + \")\");\n }\n if (dbg > 1) {\n logger.debug(\"\", e);\n }\n }\n\n return null;\n }\n\n /**\n */\n public static void setProperty(Object object, String name) {\n String setter = \"set\" + capitalize(name);\n try {\n Method methods[] = findMethods(object.getClass());\n Method setPropertyMethod = null;\n // find setFoo() method\n for (int i = 0; i < methods.length; i++) {\n Class paramT[] = methods[i].getParameterTypes();\n if (setter.equals(methods[i].getName()) && paramT.length == 0) {\n methods[i].invoke(object, new Object[]{});\n return;\n }\n }\n } catch (Exception e) {\n if (dbg > 0) {\n debug(\"Exception for \" + object.getClass() + \" \" + name);\n }\n if (dbg > 1) {\n logger.debug(\"\", e);\n }\n }\n }\n\n /**\n * Replace ${NAME} with the property value\n */\n public static String replaceProperties(String value,\n Hashtable staticProp, PropertySource dynamicProp[]) {\n if (value.indexOf(\"$\") < 0) {\n return value;\n }\n StringBuilder sb = new StringBuilder();\n int prev = 0;\n // assert value!=nil\n int pos;\n while ((pos = value.indexOf(\"$\", prev)) >= 0) {\n if (pos > 0) {\n sb.append(value.substring(prev, pos));\n }\n if (pos == (value.length() - 1)) {\n sb.append('$');\n prev = pos + 1;\n } else if (value.charAt(pos + 1) != '{') {\n sb.append('$');\n prev = pos + 1; // XXX\n } else {\n int endName = value.indexOf('}', pos);\n if (endName < 0) {\n sb.append(value.substring(pos));\n prev = value.length();\n continue;\n }\n String n = value.substring(pos + 2, endName);\n String v = null;\n if (staticProp != null) {\n v = staticProp.get(n);\n }\n if (v == null && dynamicProp != null) {\n for (int i = 0; i < dynamicProp.length; i++) {\n v = dynamicProp[i].getProperty(n);\n if (v != null) {\n break;\n }\n }\n }\n if (v == null)\n v = \"${\" + n + \"}\";\n\n sb.append(v);\n prev = endName + 1;\n }\n }\n if (prev < value.length())\n sb.append(value.substring(prev));\n return sb.toString();\n }\n\n /**\n * Reverse of Introspector.decapitalize\n */\n public static String capitalize(String name) {\n if (name == null || name.length() == 0) {\n return name;\n }\n char chars[] = name.toCharArray();\n chars[0] = Character.toUpperCase(chars[0]);\n return new String(chars);\n }\n\n public static String unCapitalize(String name) {\n if (name == null || name.length() == 0) {\n return name;\n }\n char chars[] = name.toCharArray();\n chars[0] = Character.toLowerCase(chars[0]);\n return new String(chars);\n }\n\n // -------------------- Class path tools --------------------\n\n /**\n * Add all the jar files in a dir to the classpath, represented as a Vector\n * of URLs.\n */\n @SuppressWarnings(\"unchecked\")\n public static void addToClassPath(Vector cpV, String dir) {\n try {\n String cpComp[] = getFilesByExt(dir, \".jar\");\n if (cpComp != null) {\n int jarCount = cpComp.length;\n for (int i = 0; i < jarCount; i++) {\n URL url = getURL(dir, cpComp[i]);\n if (url != null)\n cpV.addElement(url);\n }\n }\n } catch (Exception ex) {\n logger.debug(\"failed to add urls to classpath\", ex);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public static void addToolsJar(Vector v) {\n try {\n // Add tools.jar in any case\n File f = new File(System.getProperty(\"java.home\")\n + \"/../lib/tools.jar\");\n\n if (!f.exists()) {\n // On some systems java.home gets set to the root of jdk.\n // That's a bug, but we can work around and be nice.\n f = new File(System.getProperty(\"java.home\") + \"/lib/tools.jar\");\n if (f.exists()) {\n logger.debug(\"Detected strange java.home value {}, it should point to jre\",\n System.getProperty(\"java.home\"));\n }\n }\n URL url = new URL(\"file\", \"\", f.getAbsolutePath());\n\n v.addElement(url);\n } catch (MalformedURLException ex) {\n logger.debug(\"failed to add tools jar url to vector\", ex);\n }\n }\n\n /**\n * Return all files with a given extension in a dir\n */\n public static String[] getFilesByExt(String ld, String ext) {\n File dir = new File(ld);\n String[] names = null;\n final String lext = ext;\n if (dir.isDirectory()) {\n names = dir.list(new FilenameFilter() {\n public boolean accept(File d, String name) {\n if (name.endsWith(lext)) {\n return true;\n }\n return false;\n }\n });\n }\n return names;\n }\n\n /**\n * Construct a file url from a file, using a base dir\n */\n public static URL getURL(String base, String file) {\n try {\n File baseF = new File(base);\n File f = new File(baseF, file);\n String path = f.getCanonicalPath();\n if (f.isDirectory()) {\n path += \"/\";\n }\n if (!f.exists()) {\n return null;\n }\n return new URL(\"file\", \"\", path);\n } catch (Exception ex) {\n logger.debug(\"failed to get url, base: \" + base + \", file: \" + file, ex);\n return null;\n }\n }\n\n /**\n * Add elements from the classpath cp to a Vector jars as\n * file URLs (We use Vector for JDK 1.1 compat).\n *

\n *\n * @param jars The jar list\n * @param cp a String classpath of directory or jar file elements\n * separated by path.separator delimiters.\n * @throws IOException If an I/O error occurs\n * @throws MalformedURLException Doh ;)\n */\n @SuppressWarnings(\"unchecked\")\n public static void addJarsFromClassPath(Vector jars, String cp)\n throws IOException, MalformedURLException {\n String sep = System.getProperty(\"path.separator\");\n String token;\n StringTokenizer st;\n if (cp != null) {\n st = new StringTokenizer(cp, sep);\n while (st.hasMoreTokens()) {\n File f = new File(st.nextToken());\n String path = f.getCanonicalPath();\n if (f.isDirectory()) {\n path += \"/\";\n }\n URL url = new URL(\"file\", \"\", path);\n if (!jars.contains(url)) {\n jars.addElement(url);\n }\n }\n }\n }\n\n /**\n * Return a URL[] that can be used to construct a class loader\n */\n public static URL[] getClassPath(Vector v) {\n URL[] urls = new URL[v.size()];\n for (int i = 0; i < v.size(); i++) {\n urls[i] = v.elementAt(i);\n }\n return urls;\n }\n\n /**\n * Construct a URL classpath from files in a directory, a cpath property,\n * and tools.jar.\n */\n @SuppressWarnings(\"unchecked\")\n public static URL[] getClassPath(String dir, String cpath,\n String cpathProp, boolean addTools) throws IOException,\n MalformedURLException {\n Vector jarsV = new Vector();\n if (dir != null) {\n // Add dir/classes first, if it exists\n URL url = getURL(dir, \"classes\");\n if (url != null)\n jarsV.addElement(url);\n addToClassPath(jarsV, dir);\n }\n\n if (cpath != null)\n addJarsFromClassPath(jarsV, cpath);\n\n if (cpathProp != null) {\n String cpath1 = System.getProperty(cpathProp);\n addJarsFromClassPath(jarsV, cpath1);\n }\n\n if (addTools)\n addToolsJar(jarsV);\n\n return getClassPath(jarsV);\n }\n\n // -------------------- Mapping command line params to setters\n\n public static boolean processArgs(Object proxy, String args[])\n throws Exception {\n String args0[] = null;\n if (null != findMethod(proxy.getClass(), \"getOptions1\", new Class[]{})) {\n args0 = (String[]) callMethod0(proxy, \"getOptions1\");\n }\n\n if (args0 == null) {\n //args0=findVoidSetters(proxy.getClass());\n args0 = findBooleanSetters(proxy.getClass());\n }\n Hashtable h = null;\n if (null != findMethod(proxy.getClass(), \"getOptionAliases\",\n new Class[]{})) {\n h = (Hashtable) callMethod0(proxy, \"getOptionAliases\");\n }\n return processArgs(proxy, args, args0, null, h);\n }\n\n public static boolean processArgs(Object proxy, String args[],\n String args0[], String args1[],\n Hashtable aliases) throws Exception {\n for (int i = 0; i < args.length; i++) {\n String arg = args[i];\n if (arg.startsWith(\"-\"))\n arg = arg.substring(1);\n if (aliases != null && aliases.get(arg) != null)\n arg = aliases.get(arg);\n\n if (args0 != null) {\n boolean set = false;\n for (int j = 0; j < args0.length; j++) {\n if (args0[j].equalsIgnoreCase(arg)) {\n setProperty(proxy, args0[j], \"true\");\n set = true;\n break;\n }\n }\n if (set)\n continue;\n }\n if (args1 != null) {\n for (int j = 0; j < args1.length; j++) {\n if (args1[j].equalsIgnoreCase(arg)) {\n i++;\n if (i >= args.length)\n return false;\n setProperty(proxy, arg, args[i]);\n break;\n }\n }\n } else {\n // if args1 is not specified,assume all other options have param\n i++;\n if (i >= args.length)\n return false;\n setProperty(proxy, arg, args[i]);\n }\n\n }\n return true;\n }\n\n // -------------------- other utils --------------------\n\n public static void clear() {\n objectMethods.clear();\n }\n\n @SuppressWarnings(\"unchecked\")\n public static String[] findVoidSetters(Class c) {\n Method m[] = findMethods(c);\n if (m == null)\n return null;\n Vector v = new Vector();\n for (int i = 0; i < m.length; i++) {\n if (m[i].getName().startsWith(\"set\")\n && m[i].getParameterTypes().length == 0) {\n String arg = m[i].getName().substring(3);\n v.addElement(unCapitalize(arg));\n }\n }\n String s[] = new String[v.size()];\n for (int i = 0; i < s.length; i++) {\n s[i] = (String) v.elementAt(i);\n }\n return s;\n }\n\n @SuppressWarnings(\"unchecked\")\n public static String[] findBooleanSetters(Class c) {\n Method m[] = findMethods(c);\n if (m == null)\n return null;\n Vector v = new Vector();\n for (int i = 0; i < m.length; i++) {\n if (m[i].getName().startsWith(\"set\")\n && m[i].getParameterTypes().length == 1\n && \"boolean\".equalsIgnoreCase(m[i].getParameterTypes()[0]\n .getName())) {\n String arg = m[i].getName().substring(3);\n v.addElement(unCapitalize(arg));\n }\n }\n String s[] = new String[v.size()];\n for (int i = 0; i < s.length; i++) {\n s[i] = v.elementAt(i);\n }\n return s;\n }\n\n static Hashtable, Method[]> objectMethods =\n new Hashtable, Method[]>();\n\n @SuppressWarnings(\"unchecked\")\n public static Method[] findMethods(Class c) {\n Method methods[] = (Method[]) objectMethods.get(c);\n if (methods != null)\n return methods;\n\n methods = c.getMethods();\n objectMethods.put(c, methods);\n return methods;\n }\n\n public static Method findMethod(Class c, String name,\n Class params[]) {\n Method methods[] = findMethods(c);\n if (methods == null)\n return null;\n for (int i = 0; i < methods.length; i++) {\n if (methods[i].getName().equals(name)) {\n Class methodParams[] = methods[i].getParameterTypes();\n if (methodParams == null)\n if (params == null || params.length == 0)\n return methods[i];\n if (params == null)\n if (methodParams == null || methodParams.length == 0)\n return methods[i];\n if (params.length != methodParams.length)\n continue;\n boolean found = true;\n for (int j = 0; j < params.length; j++) {\n if (params[j] != methodParams[j]) {\n found = false;\n break;\n }\n }\n if (found)\n return methods[i];\n }\n }\n return null;\n }\n\n /**\n * Test if the object implements a particular\n * method\n */\n public static boolean hasHook(Object obj, String methodN) {\n try {\n Method myMethods[] = findMethods(obj.getClass());\n for (int i = 0; i < myMethods.length; i++) {\n if (methodN.equals(myMethods[i].getName())) {\n // check if it's overriden\n Class declaring = myMethods[i].getDeclaringClass();\n Class parentOfDeclaring = declaring.getSuperclass();\n // this works only if the base class doesn't extend\n // another class.\n\n // if the method is declared in a top level class\n // like BaseInterceptor parent is Object, otherwise\n // parent is BaseInterceptor or an intermediate class\n if (!\"java.lang.Object\".equals(parentOfDeclaring.getName())) {\n return true;\n }\n }\n }\n } catch (Exception ex) {\n logger.debug(\"hasHook() failed\", ex);\n }\n return false;\n }\n\n public static void callMain(Class c, String args[]) throws Exception {\n Class p[] = new Class[1];\n p[0] = args.getClass();\n @SuppressWarnings(\"unchecked\")\n Method m = c.getMethod(\"main\", p);\n m.invoke(c, new Object[]{args});\n }\n\n public static Object callMethod1(Object target, String methodN,\n Object param1, String typeParam1, ClassLoader cl) throws Exception {\n if (target == null || param1 == null) {\n debug(\"Assert: Illegal params \" + target + \" \" + param1);\n }\n if (dbg > 0)\n debug(\"callMethod1 \" + target.getClass().getName() + \" \" + param1.getClass().getName() + \" \" +\n typeParam1);\n\n Class params[] = new Class[1];\n if (typeParam1 == null) {\n params[0] = param1.getClass();\n } else {\n params[0] = cl.loadClass(typeParam1);\n }\n Method m = findMethod(target.getClass(), methodN, params);\n if (m == null) {\n throw new NoSuchMethodException(target.getClass().getName() + \" \" + methodN);\n }\n return m.invoke(target, new Object[]{param1});\n }\n\n public static Object callMethod0(Object target, String methodN)\n throws Exception {\n if (target == null) {\n debug(\"Assert: Illegal params \" + target);\n return null;\n }\n if (dbg > 0) {\n debug(\"callMethod0 \" + target.getClass().getName() + \".\" + methodN);\n }\n\n Class params[] = new Class[0];\n Method m = findMethod(target.getClass(), methodN, params);\n if (m == null) {\n throw new NoSuchMethodException(target.getClass().getName() + \" \" + methodN);\n }\n return m.invoke(target, emptyArray);\n }\n\n static Object[] emptyArray = new Object[]{};\n\n public static Object callMethodN(Object target, String methodN,\n Object params[], Class typeParams[]) throws Exception {\n Method m = null;\n m = findMethod(target.getClass(), methodN, typeParams);\n if (m == null) {\n debug(\"Can't find method \" + methodN + \" in \" + target + \" CLASS \" + target.getClass());\n return null;\n }\n Object o = m.invoke(target, params);\n\n if (dbg > 0) {\n // debug\n StringBuffer sb = new StringBuffer();\n sb.append(\"\" + target.getClass().getName() + \".\" + methodN + \"( \");\n for (int i = 0; i < params.length; i++) {\n if (i > 0)\n sb.append(\", \");\n sb.append(params[i]);\n }\n sb.append(\")\");\n debug(sb.toString());\n }\n return o;\n }\n\n public static Object convert(String object, Class paramType) {\n Object result = null;\n if (\"java.lang.String\".equals(paramType.getName())) {\n result = object;\n } else if (\"java.lang.Integer\".equals(paramType.getName())\n || \"int\".equals(paramType.getName())) {\n try {\n result = new Integer(object);\n } catch (NumberFormatException ex) {\n }\n // Try a setFoo ( boolean )\n } else if (\"java.lang.Boolean\".equals(paramType.getName())\n || \"boolean\".equals(paramType.getName())) {\n result = new Boolean(object);\n\n // Try a setFoo ( InetAddress )\n } else if (\"java.net.InetAddress\".equals(paramType\n .getName())) {\n try {\n result = InetAddress.getByName(object);\n } catch (UnknownHostException exc) {\n debug(\"Unable to resolve host name:\" + object);\n }\n\n // Unknown type\n } else {\n debug(\"Unknown type \" + paramType.getName());\n }\n if (result == null) {\n throw new IllegalArgumentException(\"Can't convert argument: \" + object);\n }\n return result;\n }\n\n // -------------------- Get property --------------------\n // This provides a layer of abstraction\n\n public static interface PropertySource {\n\n public String getProperty(String key);\n\n }\n\n public static interface AttributeHolder {\n\n public void setAttribute(String key, Object o);\n\n }\n\n // debug --------------------\n static final int dbg = 0;\n\n static void debug(String s) {\n logger.debug(\"IntrospectionUtils: {}\", s);\n }\n}\n", "file_name": "IntrospectionUtils.java", "human_label": "Converts a name of the string type to a character array and converts the first letter to an uppercase letter.", "level": "slib_runnable", "lineno": "374", "name": "capitalize", "oracle_context": "{ \"apis\" : \"[length, toCharArray, toUpperCase]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "org.atmosphere.util", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767aa1a6d9265ec01865a", "all_context": "{ \"class_level\" : \"import java.io.DataOutput;\\nimport java.io.IOException;\\nimport java.io.OutputStream;\\nint MIN_BUFFER_SIZE;\\nint DEFAULT_BUFFER_SIZE;\\nbyte[] buffer;\\nint start;\\nint offset;\\nLinkedBuffer next;\\nallocate(int size);\\nallocate(int size,LinkedBuffer previous);\\nwrap(byte[] array,int offset,int length);\\nuse(byte[] buffer);\\nuse(byte[] buffer,int start);\\nwriteTo(OutputStream out,LinkedBuffer node);\\nwriteTo(DataOutput out,LinkedBuffer node);\\nLinkedBuffer(int size);\\nLinkedBuffer(int size,LinkedBuffer appendTarget);\\nLinkedBuffer(byte[] buffer,int offset);\\nLinkedBuffer(byte[] buffer,int start,int offset);\\nLinkedBuffer(byte[] buffer,int offset,LinkedBuffer appendTarget);\\nLinkedBuffer(byte[] buffer,int start,int offset,LinkedBuffer appendTarget);\\nLinkedBuffer(LinkedBuffer viewSource,LinkedBuffer appendTarget);\\nclear();\\nallocate();\\n\", \"repo_level\" : \"\" }", "class_name": "LinkedBuffer", "code": "public static int writeTo(final DataOutput out,LinkedBuffer node) throws IOException {\n int contentSize=0, len;\n do {\n if ((len=node.offset - node.start) > 0) {\n out.write(node.buffer,node.start,len);\n contentSize+=len;\n }\n }\n while ((node=node.next) != null);\n return contentSize;\n}\n", "docstring": "/** \n * Writes the contents of the {@link LinkedBuffer} into the {@link DataOutput}.\n * @return the total content size of the buffer.\n */\n", "end_lineno": "136", "file_content": "//========================================================================\r\n//Copyright 2007-2010 David Yu dyuproject@gmail.com\r\n//------------------------------------------------------------------------\r\n//Licensed under the Apache License, Version 2.0 (the \"License\");\r\n//you may not use this file except in compliance with the License.\r\n//You may obtain a copy of the License at \r\n//http://www.apache.org/licenses/LICENSE-2.0\r\n//Unless required by applicable law or agreed to in writing, software\r\n//distributed under the License is distributed on an \"AS IS\" BASIS,\r\n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n//See the License for the specific language governing permissions and\r\n//limitations under the License.\r\n//========================================================================\r\n\r\npackage io.protostuff;\r\n\r\nimport java.io.DataOutput;\r\nimport java.io.IOException;\r\nimport java.io.OutputStream;\r\n\r\n/**\r\n * A buffer that wraps a byte array and has a reference to the next buffer for dynamic increase.\r\n * \r\n * @author David Yu\r\n * @created May 18, 2010\r\n */\r\npublic final class LinkedBuffer\r\n{\r\n\r\n /**\r\n * The minimum buffer size for a {@link LinkedBuffer}.\r\n */\r\n public static final int MIN_BUFFER_SIZE = 256;\r\n\r\n /**\r\n * The default buffer size for a {@link LinkedBuffer}.\r\n */\r\n public static final int DEFAULT_BUFFER_SIZE = 512;\r\n\r\n /**\r\n * Allocates a new buffer with default size.\r\n */\r\n public static LinkedBuffer allocate()\r\n {\r\n return new LinkedBuffer(DEFAULT_BUFFER_SIZE);\r\n }\r\n\r\n /**\r\n * Allocates a new buffer with the specified size.\r\n */\r\n public static LinkedBuffer allocate(int size)\r\n {\r\n if (size < MIN_BUFFER_SIZE)\r\n throw new IllegalArgumentException(MIN_BUFFER_SIZE + \" is the minimum buffer size.\");\r\n\r\n return new LinkedBuffer(size);\r\n }\r\n\r\n /**\r\n * Allocates a new buffer with the specified size and appends it to the previous buffer.\r\n */\r\n public static LinkedBuffer allocate(int size, LinkedBuffer previous)\r\n {\r\n if (size < MIN_BUFFER_SIZE)\r\n throw new IllegalArgumentException(MIN_BUFFER_SIZE + \" is the minimum buffer size.\");\r\n\r\n return new LinkedBuffer(size, previous);\r\n }\r\n\r\n /**\r\n * Wraps the byte array buffer as a read-only buffer.\r\n */\r\n public static LinkedBuffer wrap(byte[] array, int offset, int length)\r\n {\r\n return new LinkedBuffer(array, offset, offset + length);\r\n }\r\n\r\n /**\r\n * Uses the existing byte array as the internal buffer.\r\n */\r\n public static LinkedBuffer use(byte[] buffer)\r\n {\r\n return use(buffer, 0);\r\n }\r\n\r\n /**\r\n * Uses the existing byte array as the internal buffer.\r\n */\r\n public static LinkedBuffer use(byte[] buffer, int start)\r\n {\r\n assert start >= 0;\r\n if (buffer.length - start < MIN_BUFFER_SIZE)\r\n throw new IllegalArgumentException(MIN_BUFFER_SIZE + \" is the minimum buffer size.\");\r\n\r\n return new LinkedBuffer(buffer, start, start);\r\n }\r\n\r\n /**\r\n * Writes the contents of the {@link LinkedBuffer} into the {@link OutputStream}.\r\n * \r\n * @return the total content size of the buffer.\r\n */\r\n public static int writeTo(final OutputStream out, LinkedBuffer node) throws IOException\r\n {\r\n int contentSize = 0, len;\r\n do\r\n {\r\n if ((len = node.offset - node.start) > 0)\r\n {\r\n out.write(node.buffer, node.start, len);\r\n contentSize += len;\r\n }\r\n } while ((node = node.next) != null);\r\n\r\n return contentSize;\r\n }\r\n\r\n /**\r\n * Writes the contents of the {@link LinkedBuffer} into the {@link DataOutput}.\r\n * \r\n * @return the total content size of the buffer.\r\n */\r\n public static int writeTo(final DataOutput out, LinkedBuffer node) throws IOException\r\n {\r\n int contentSize = 0, len;\r\n do\r\n {\r\n if ((len = node.offset - node.start) > 0)\r\n {\r\n out.write(node.buffer, node.start, len);\r\n contentSize += len;\r\n }\r\n } while ((node = node.next) != null);\r\n\r\n return contentSize;\r\n }\r\n\r\n final byte[] buffer;\r\n\r\n final int start;\r\n\r\n int offset;\r\n\r\n LinkedBuffer next;\r\n\r\n /**\r\n * Creates a buffer with the specified {@code size}.\r\n */\r\n LinkedBuffer(int size)\r\n {\r\n this(new byte[size], 0, 0);\r\n }\r\n\r\n /**\r\n * Creates a buffer with the specified {@code size} and appends to the provided buffer {@code appendTarget}.\r\n */\r\n LinkedBuffer(int size, LinkedBuffer appendTarget)\r\n {\r\n this(new byte[size], 0, 0, appendTarget);\r\n }\r\n\r\n /**\r\n * Uses the buffer starting at the specified {@code offset}\r\n */\r\n LinkedBuffer(byte[] buffer, int offset)\r\n {\r\n this(buffer, offset, offset);\r\n }\r\n\r\n LinkedBuffer(byte[] buffer, int start, int offset)\r\n {\r\n this.buffer = buffer;\r\n this.start = start;\r\n this.offset = offset;\r\n }\r\n\r\n /**\r\n * Uses the buffer starting at the specified {@code offset} and appends to the provided buffer {@code appendTarget}.\r\n */\r\n LinkedBuffer(byte[] buffer, int offset, LinkedBuffer appendTarget)\r\n {\r\n this(buffer, offset, offset);\r\n appendTarget.next = this;\r\n }\r\n\r\n LinkedBuffer(byte[] buffer, int start, int offset, LinkedBuffer appendTarget)\r\n {\r\n this(buffer, start, offset);\r\n appendTarget.next = this;\r\n }\r\n\r\n /**\r\n * Creates a view from the buffer {@code viewSource} and appends the view to the provided buffer\r\n * {@code appendTarget}.\r\n */\r\n LinkedBuffer(LinkedBuffer viewSource, LinkedBuffer appendTarget)\r\n {\r\n buffer = viewSource.buffer;\r\n offset = start = viewSource.offset;\r\n appendTarget.next = this;\r\n }\r\n\r\n /**\r\n * The offset will be reset to its starting position. The buffer next to this will be dereferenced.\r\n */\r\n public LinkedBuffer clear()\r\n {\r\n next = null;\r\n offset = start;\r\n return this;\r\n }\r\n\r\n}\r\n", "file_name": "LinkedBuffer.java", "human_label": "Write the content into the LinkedBuffer.", "level": "class_runnable", "lineno": "118", "name": "writeTo", "oracle_context": "{ \"apis\" : \"[write, LinkedBuffer]\", \"classes\" : \"[]\", \"vars\" : \"[offset, start, buffer, next]\" }", "package": "io.protostuff", "project": "protostuff-master" }, { "_id": "636766f21a6d9265ec017677", "all_context": "{ \"class_level\" : \"BooleanUtils();\\nisTrue(Boolean bool);\\nisNotTrue(Boolean bool);\\nisFalse(Boolean bool);\\nisNotFalse(Boolean bool);\\ntoBooleanObject(boolean bool);\\ntoBoolean(Boolean bool);\\ntoBooleanDefaultIfNull(Boolean bool,boolean valueIfNull);\\ntoBoolean(int value);\\ntoBooleanObject(int value);\\ntoBooleanObject(Integer value);\\ntoBoolean(int value,int trueValue,int falseValue);\\ntoBoolean(Integer value,Integer trueValue,Integer falseValue);\\ntoBooleanObject(int value,int trueValue,int falseValue,int nullValue);\\ntoBooleanObject(Integer value,Integer trueValue,Integer falseValue,Integer nullValue);\\ntoInteger(boolean bool);\\ntoInteger(boolean bool,int trueValue,int falseValue);\\ntoInteger(Boolean bool,int trueValue,int falseValue,int nullValue);\\ntoIntegerObject(boolean bool,Integer trueValue,Integer falseValue);\\ntoIntegerObject(Boolean bool,Integer trueValue,Integer falseValue,Integer nullValue);\\ntoBooleanObject(String str);\\ntoBooleanObject(String str,String trueString,String falseString,String nullString);\\ntoBoolean(String str);\\ntoBoolean(String str,String trueString,String falseString);\\ntoStringTrueFalse(Boolean bool);\\ntoStringOnOff(Boolean bool);\\ntoStringYesNo(Boolean bool);\\ntoString(Boolean bool,String trueString,String falseString,String nullString);\\ntoStringTrueFalse(boolean bool);\\ntoStringOnOff(boolean bool);\\ntoStringYesNo(boolean bool);\\ntoString(boolean bool,String trueString,String falseString);\\nxor(boolean[] array);\\nxor(Boolean[] array);\\nisBooleanType(Class targetType);\\nnegate(Boolean bool);\\n\", \"repo_level\" : \"\" }", "class_name": "BooleanUtils", "code": "public static boolean isNotTrue(Boolean bool){\n return !isTrue(bool);\n}\n", "docstring": "/** \n *

Checks if a Boolean value is not true, handling null by returning true.

 BooleanUtils.isNotTrue(Boolean.TRUE)  = false BooleanUtils.isNotTrue(Boolean.FALSE) = true BooleanUtils.isNotTrue(null)          = true 
\n * @param bool the boolean to check, null returns true\n * @return true if the input is null or false\n * @since 2.3\n */\n", "end_lineno": "106", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\n/**\n *

Operations on boolean primitives and Boolean objects.

\n *\n *

This class tries to handle null input gracefully.\n * An exception will not be thrown for a null input.\n * Each method documents its behaviour in more detail.

\n *\n *

#ThreadSafe#

\n * @author Apache Software Foundation\n * @author Matthew Hawthorne\n * @author Gary Gregory\n * @since 2.0\n * @version $Id: BooleanUtils.java 1057037 2011-01-09 21:35:32Z niallp $\n */\npublic class BooleanUtils {\n /**\n *

BooleanUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as BooleanUtils.toBooleanObject(true);.

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public BooleanUtils() {\n super();\n }\n // Boolean utilities\n //--------------------------------------------------------------------------\n\n /**\n *

Negates the specified boolean.

\n *\n *

If null is passed in, null will be returned.

\n *\n *
\n     *   BooleanUtils.negate(Boolean.TRUE)  = Boolean.FALSE;\n     *   BooleanUtils.negate(Boolean.FALSE) = Boolean.TRUE;\n     *   BooleanUtils.negate(null)          = null;\n     * 
\n *\n * @param bool the Boolean to negate, may be null\n * @return the negated Boolean, or null if null input\n */\n public static Boolean negate(Boolean bool) {\n if (bool == null) {\n return null;\n }\n return (bool.booleanValue() ? Boolean.FALSE : Boolean.TRUE);\n }\n // boolean Boolean methods\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if a Boolean value is true,\n * handling null by returning false.

\n *\n *
\n     *   BooleanUtils.isTrue(Boolean.TRUE)  = true\n     *   BooleanUtils.isTrue(Boolean.FALSE) = false\n     *   BooleanUtils.isTrue(null)          = false\n     * 
\n *\n * @param bool the boolean to check, null returns false\n * @return true only if the input is non-null and true\n * @since 2.1\n */\n public static boolean isTrue(Boolean bool) {\n if (bool == null) {\n return false;\n }\n return bool.booleanValue() ? true : false;\n }\n\n /**\n *

Checks if a Boolean value is not true,\n * handling null by returning true.

\n *\n *
\n     *   BooleanUtils.isNotTrue(Boolean.TRUE)  = false\n     *   BooleanUtils.isNotTrue(Boolean.FALSE) = true\n     *   BooleanUtils.isNotTrue(null)          = true\n     * 
\n *\n * @param bool the boolean to check, null returns true\n * @return true if the input is null or false\n * @since 2.3\n */\n public static boolean isNotTrue(Boolean bool) {\n return !isTrue(bool);\n }\n\n /**\n *

Checks if a Boolean value is false,\n * handling null by returning false.

\n *\n *
\n     *   BooleanUtils.isFalse(Boolean.TRUE)  = false\n     *   BooleanUtils.isFalse(Boolean.FALSE) = true\n     *   BooleanUtils.isFalse(null)          = false\n     * 
\n *\n * @param bool the boolean to check, null returns false\n * @return true only if the input is non-null and false\n * @since 2.1\n */\n public static boolean isFalse(Boolean bool) {\n if (bool == null) {\n return false;\n }\n return bool.booleanValue() ? false : true;\n }\n\n /**\n *

Checks if a Boolean value is not false,\n * handling null by returning true.

\n *\n *
\n     *   BooleanUtils.isNotFalse(Boolean.TRUE)  = true\n     *   BooleanUtils.isNotFalse(Boolean.FALSE) = false\n     *   BooleanUtils.isNotFalse(null)          = true\n     * 
\n *\n * @param bool the boolean to check, null returns true\n * @return true if the input is null or true\n * @since 2.3\n */\n public static boolean isNotFalse(Boolean bool) {\n return !isFalse(bool);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Boolean factory that avoids creating new Boolean objecs all the time.

\n *\n *

This method was added to JDK1.4 but is available here for earlier JDKs.

\n *\n *
\n     *   BooleanUtils.toBooleanObject(false) = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(true)  = Boolean.TRUE\n     * 
\n *\n * @param bool the boolean to convert\n * @return Boolean.TRUE or Boolean.FALSE as appropriate\n */\n public static Boolean toBooleanObject(boolean bool) {\n return bool ? Boolean.TRUE : Boolean.FALSE;\n }\n\n /**\n *

Converts a Boolean to a boolean handling null\n * by returning false.

\n *\n *
\n     *   BooleanUtils.toBoolean(Boolean.TRUE)  = true\n     *   BooleanUtils.toBoolean(Boolean.FALSE) = false\n     *   BooleanUtils.toBoolean(null)          = false\n     * 
\n *\n * @param bool the boolean to convert\n * @return true or false, \n * null returns false\n */\n public static boolean toBoolean(Boolean bool) {\n if (bool == null) {\n return false;\n }\n return bool.booleanValue() ? true : false;\n }\n\n /**\n *

Converts a Boolean to a boolean handling null.

\n *\n *
\n     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false) = true\n     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true) = false\n     *   BooleanUtils.toBooleanDefaultIfNull(null, true)          = true\n     * 
\n *\n * @param bool the boolean to convert\n * @param valueIfNull the boolean value to return if null\n * @return true or false\n */\n public static boolean toBooleanDefaultIfNull(Boolean bool, boolean valueIfNull) {\n if (bool == null) {\n return valueIfNull;\n }\n return bool.booleanValue() ? true : false;\n }\n // Integer to Boolean methods\n //-----------------------------------------------------------------------\n\n /**\n *

Converts an int to a boolean using the convention that zero\n * is false.

\n *\n *
\n     *   BooleanUtils.toBoolean(0) = false\n     *   BooleanUtils.toBoolean(1) = true\n     *   BooleanUtils.toBoolean(2) = true\n     * 
\n *\n * @param value the int to convert\n * @return true if non-zero, false\n * if zero\n */\n public static boolean toBoolean(int value) {\n return value == 0 ? false : true;\n }\n\n /**\n *

Converts an int to a Boolean using the convention that zero\n * is false.

\n *\n *
\n     *   BooleanUtils.toBoolean(0) = Boolean.FALSE\n     *   BooleanUtils.toBoolean(1) = Boolean.TRUE\n     *   BooleanUtils.toBoolean(2) = Boolean.TRUE\n     * 
\n *\n * @param value the int to convert\n * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero,\n * null if null\n */\n public static Boolean toBooleanObject(int value) {\n return value == 0 ? Boolean.FALSE : Boolean.TRUE;\n }\n\n /**\n *

Converts an Integer to a Boolean using the convention that zero\n * is false.

\n *\n *

null will be converted to null.

\n *\n *
\n     *   BooleanUtils.toBoolean(new Integer(0))    = Boolean.FALSE\n     *   BooleanUtils.toBoolean(new Integer(1))    = Boolean.TRUE\n     *   BooleanUtils.toBoolean(new Integer(null)) = null\n     * 
\n *\n * @param value the Integer to convert\n * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero,\n * null if null input\n */\n public static Boolean toBooleanObject(Integer value) {\n if (value == null) {\n return null;\n }\n return value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE;\n }\n\n /**\n *

Converts an int to a boolean specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toBoolean(0, 1, 0) = false\n     *   BooleanUtils.toBoolean(1, 1, 0) = true\n     *   BooleanUtils.toBoolean(2, 1, 2) = false\n     *   BooleanUtils.toBoolean(2, 2, 0) = true\n     * 
\n *\n * @param value the Integer to convert\n * @param trueValue the value to match for true\n * @param falseValue the value to match for false\n * @return true or false\n * @throws IllegalArgumentException if no match\n */\n public static boolean toBoolean(int value, int trueValue, int falseValue) {\n if (value == trueValue) {\n return true;\n } else if (value == falseValue) {\n return false;\n }\n // no match\n throw new IllegalArgumentException(\"The Integer did not match either specified value\");\n }\n\n /**\n *

Converts an Integer to a boolean specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toBoolean(new Integer(0), new Integer(1), new Integer(0)) = false\n     *   BooleanUtils.toBoolean(new Integer(1), new Integer(1), new Integer(0)) = true\n     *   BooleanUtils.toBoolean(new Integer(2), new Integer(1), new Integer(2)) = false\n     *   BooleanUtils.toBoolean(new Integer(2), new Integer(2), new Integer(0)) = true\n     *   BooleanUtils.toBoolean(null, null, new Integer(0))                     = true\n     * 
\n *\n * @param value the Integer to convert\n * @param trueValue the value to match for true,\n * may be null\n * @param falseValue the value to match for false,\n * may be null\n * @return true or false\n * @throws IllegalArgumentException if no match\n */\n public static boolean toBoolean(Integer value, Integer trueValue, Integer falseValue) {\n if (value == null) {\n if (trueValue == null) {\n return true;\n } else if (falseValue == null) {\n return false;\n }\n } else if (value.equals(trueValue)) {\n return true;\n } else if (value.equals(falseValue)) {\n return false;\n }\n // no match\n throw new IllegalArgumentException(\"The Integer did not match either specified value\");\n }\n\n /**\n *

Converts an int to a Boolean specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toBooleanObject(0, 0, 2, 3) = Boolean.TRUE\n     *   BooleanUtils.toBooleanObject(2, 1, 2, 3) = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(3, 1, 2, 3) = null\n     * 
\n *\n * @param value the Integer to convert\n * @param trueValue the value to match for true\n * @param falseValue the value to match for false\n * @param nullValue the value to to match for null\n * @return Boolean.TRUE, Boolean.FALSE, or null\n * @throws IllegalArgumentException if no match\n */\n public static Boolean toBooleanObject(int value, int trueValue, int falseValue, int nullValue) {\n if (value == trueValue) {\n return Boolean.TRUE;\n } else if (value == falseValue) {\n return Boolean.FALSE;\n } else if (value == nullValue) {\n return null;\n }\n // no match\n throw new IllegalArgumentException(\"The Integer did not match any specified value\");\n }\n\n /**\n *

Converts an Integer to a Boolean specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toBooleanObject(new Integer(0), new Integer(0), new Integer(2), new Integer(3)) = Boolean.TRUE\n     *   BooleanUtils.toBooleanObject(new Integer(2), new Integer(1), new Integer(2), new Integer(3)) = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(new Integer(3), new Integer(1), new Integer(2), new Integer(3)) = null\n     * 
\n *\n * @param value the Integer to convert\n * @param trueValue the value to match for true,\n * may be null\n * @param falseValue the value to match for false,\n * may be null\n * @param nullValue the value to to match for null,\n * may be null\n * @return Boolean.TRUE, Boolean.FALSE, or null\n * @throws IllegalArgumentException if no match\n */\n public static Boolean toBooleanObject(Integer value, Integer trueValue, Integer falseValue, Integer nullValue) {\n if (value == null) {\n if (trueValue == null) {\n return Boolean.TRUE;\n } else if (falseValue == null) {\n return Boolean.FALSE;\n } else if (nullValue == null) {\n return null;\n }\n } else if (value.equals(trueValue)) {\n return Boolean.TRUE;\n } else if (value.equals(falseValue)) {\n return Boolean.FALSE;\n } else if (value.equals(nullValue)) {\n return null;\n }\n // no match\n throw new IllegalArgumentException(\"The Integer did not match any specified value\");\n }\n // Boolean to Integer methods\n //-----------------------------------------------------------------------\n\n /**\n *

Converts a boolean to an int using the convention that\n * zero is false.

\n *\n *
\n     *   BooleanUtils.toInteger(true)  = 1\n     *   BooleanUtils.toInteger(false) = 0\n     * 
\n *\n * @param bool the boolean to convert\n * @return one if true, zero if false\n */\n public static int toInteger(boolean bool) {\n return bool ? 1 : 0;\n }\n\n /**\n *

Converts a boolean to an int specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toInteger(true, 1, 0)  = 1\n     *   BooleanUtils.toInteger(false, 1, 0) = 0\n     * 
\n *\n * @param bool the to convert\n * @param trueValue the value to return if true\n * @param falseValue the value to return if false\n * @return the appropriate value\n */\n public static int toInteger(boolean bool, int trueValue, int falseValue) {\n return bool ? trueValue : falseValue;\n }\n\n /**\n *

Converts a Boolean to an int specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toInteger(Boolean.TRUE, 1, 0, 2)  = 1\n     *   BooleanUtils.toInteger(Boolean.FALSE, 1, 0, 2) = 0\n     *   BooleanUtils.toInteger(null, 1, 0, 2)          = 2\n     * 
\n *\n * @param bool the Boolean to convert\n * @param trueValue the value to return if true\n * @param falseValue the value to return if false\n * @param nullValue the value to return if null\n * @return the appropriate value\n */\n public static int toInteger(Boolean bool, int trueValue, int falseValue, int nullValue) {\n if (bool == null) {\n return nullValue;\n }\n return bool.booleanValue() ? trueValue : falseValue;\n }\n\n /**\n *

Converts a boolean to an Integer specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toIntegerObject(true, new Integer(1), new Integer(0))  = new Integer(1)\n     *   BooleanUtils.toIntegerObject(false, new Integer(1), new Integer(0)) = new Integer(0)\n     * 
\n *\n * @param bool the to convert\n * @param trueValue the value to return if true,\n * may be null\n * @param falseValue the value to return if false,\n * may be null\n * @return the appropriate value\n */\n public static Integer toIntegerObject(boolean bool, Integer trueValue, Integer falseValue) {\n return bool ? trueValue : falseValue;\n }\n\n /**\n *

Converts a Boolean to an Integer specifying the conversion values.

\n *\n *
\n     *   BooleanUtils.toIntegerObject(Boolean.TRUE, new Integer(1), new Integer(0), new Integer(2))  = new Integer(1)\n     *   BooleanUtils.toIntegerObject(Boolean.FALSE, new Integer(1), new Integer(0), new Integer(2)) = new Integer(0)\n     *   BooleanUtils.toIntegerObject(null, new Integer(1), new Integer(0), new Integer(2))          = new Integer(2)\n     * 
\n *\n * @param bool the Boolean to convert\n * @param trueValue the value to return if true,\n * may be null\n * @param falseValue the value to return if false,\n * may be null\n * @param nullValue the value to return if null,\n * may be null\n * @return the appropriate value\n */\n public static Integer toIntegerObject(Boolean bool, Integer trueValue, Integer falseValue, Integer nullValue) {\n if (bool == null) {\n return nullValue;\n }\n return bool.booleanValue() ? trueValue : falseValue;\n }\n // String to Boolean methods\n //-----------------------------------------------------------------------\n\n /**\n *

Converts a String to a Boolean.

\n *\n *

'true', 'on' or 'yes'\n * (case insensitive) will return true.\n * 'false', 'off' or 'no'\n * (case insensitive) will return false.\n * Otherwise, null is returned.

\n *\n *
\n     *   BooleanUtils.toBooleanObject(null)    = null\n     *   BooleanUtils.toBooleanObject(\"true\")  = Boolean.TRUE\n     *   BooleanUtils.toBooleanObject(\"false\") = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(\"on\")    = Boolean.TRUE\n     *   BooleanUtils.toBooleanObject(\"ON\")    = Boolean.TRUE\n     *   BooleanUtils.toBooleanObject(\"off\")   = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(\"oFf\")   = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(\"blue\")  = null\n     * 
\n *\n * @param str the String to check\n * @return the Boolean value of the string,\n * null if no match or null input\n */\n public static Boolean toBooleanObject(String str) {\n // Previously used equalsIgnoreCase, which was fast for interned 'true'.\n // Non interned 'true' matched 15 times slower.\n // \n // Optimisation provides same performance as before for interned 'true'.\n // Similar performance for null, 'false', and other strings not length 2/3/4.\n // 'true'/'TRUE' match 4 times slower, 'tRUE'/'True' 7 times slower.\n if (str == null) {\n return null;\n }\n if (\"true\".equals(str)) {\n return Boolean.TRUE;\n }\n switch (str.length()) {\n case 1: {\n char ch0 = str.charAt(0);\n if ((ch0 == 'y' || ch0 == 'Y') || (ch0 == 't' || ch0 == 'T')) {\n return Boolean.TRUE;\n }\n if ((ch0 == 'n' || ch0 == 'N') || (ch0 == 'f' || ch0 == 'F')) {\n return Boolean.FALSE;\n }\n break;\n }\n case 2: {\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n if ((ch0 == 'o' || ch0 == 'O') && (ch1 == 'n' || ch1 == 'N')) {\n return Boolean.TRUE;\n }\n if ((ch0 == 'n' || ch0 == 'N') && (ch1 == 'o' || ch1 == 'O')) {\n return Boolean.FALSE;\n }\n break;\n }\n case 3: {\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n char ch2 = str.charAt(2);\n if ((ch0 == 'y' || ch0 == 'Y') && (ch1 == 'e' || ch1 == 'E') && (ch2 == 's' || ch2 == 'S')) {\n return Boolean.TRUE;\n }\n if ((ch0 == 'o' || ch0 == 'O') && (ch1 == 'f' || ch1 == 'F') && (ch2 == 'f' || ch2 == 'F')) {\n return Boolean.FALSE;\n }\n break;\n }\n case 4: {\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n char ch2 = str.charAt(2);\n char ch3 = str.charAt(3);\n if ((ch0 == 't' || ch0 == 'T') && (ch1 == 'r' || ch1 == 'R') && (ch2 == 'u' || ch2 == 'U') && (ch3 == 'e' || ch3 == 'E')) {\n return Boolean.TRUE;\n }\n break;\n }\n case 5: {\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n char ch2 = str.charAt(2);\n char ch3 = str.charAt(3);\n char ch4 = str.charAt(4);\n if ((ch0 == 'f' || ch0 == 'F') && (ch1 == 'a' || ch1 == 'A') && (ch2 == 'l' || ch2 == 'L') && (ch3 == 's' || ch3 == 'S') && (ch4 == 'e' || ch4 == 'E')) {\n return Boolean.FALSE;\n }\n break;\n }\n }\n return null;\n }\n\n /**\n *

Converts a String to a Boolean throwing an exception if no match.

\n *\n *
\n     *   BooleanUtils.toBooleanObject(\"true\", \"true\", \"false\", \"null\")  = Boolean.TRUE\n     *   BooleanUtils.toBooleanObject(\"false\", \"true\", \"false\", \"null\") = Boolean.FALSE\n     *   BooleanUtils.toBooleanObject(\"null\", \"true\", \"false\", \"null\")  = null\n     * 
\n *\n * @param str the String to check\n * @param trueString the String to match for true\n * (case sensitive), may be null\n * @param falseString the String to match for false\n * (case sensitive), may be null\n * @param nullString the String to match for null\n * (case sensitive), may be null\n * @return the Boolean value of the string,\n * null if either the String matches nullString\n * or if null input and nullString is\n * null\n * @throws IllegalArgumentException if the String doesn't match\n */\n public static Boolean toBooleanObject(String str, String trueString, String falseString, String nullString) {\n if (str == null) {\n if (trueString == null) {\n return Boolean.TRUE;\n } else if (falseString == null) {\n return Boolean.FALSE;\n } else if (nullString == null) {\n return null;\n }\n } else if (str.equals(trueString)) {\n return Boolean.TRUE;\n } else if (str.equals(falseString)) {\n return Boolean.FALSE;\n } else if (str.equals(nullString)) {\n return null;\n }\n // no match\n throw new IllegalArgumentException(\"The String did not match any specified value\");\n }\n // String to boolean methods\n //-----------------------------------------------------------------------\n\n /**\n *

Converts a String to a boolean (optimised for performance).

\n *\n *

'true', 'on' or 'yes'\n * (case insensitive) will return true. Otherwise,\n * false is returned.

\n *\n *

This method performs 4 times faster (JDK1.4) than\n * Boolean.valueOf(String). However, this method accepts\n * 'on' and 'yes' as true values.\n *\n *

\n     *   BooleanUtils.toBoolean(null)    = false\n     *   BooleanUtils.toBoolean(\"true\")  = true\n     *   BooleanUtils.toBoolean(\"TRUE\")  = true\n     *   BooleanUtils.toBoolean(\"tRUe\")  = true\n     *   BooleanUtils.toBoolean(\"on\")    = true\n     *   BooleanUtils.toBoolean(\"yes\")   = true\n     *   BooleanUtils.toBoolean(\"false\") = false\n     *   BooleanUtils.toBoolean(\"x gti\") = false\n     * 
\n *\n * @param str the String to check\n * @return the boolean value of the string, false if no match or the String is null\n */\n public static boolean toBoolean(String str) {\n return toBoolean(toBooleanObject(str));\n }\n\n /**\n *

Converts a String to a Boolean throwing an exception if no match found.

\n *\n *

null is returned if there is no match.

\n *\n *
\n     *   BooleanUtils.toBoolean(\"true\", \"true\", \"false\")  = true\n     *   BooleanUtils.toBoolean(\"false\", \"true\", \"false\") = false\n     * 
\n *\n * @param str the String to check\n * @param trueString the String to match for true\n * (case sensitive), may be null\n * @param falseString the String to match for false\n * (case sensitive), may be null\n * @return the boolean value of the string\n * @throws IllegalArgumentException if the String doesn't match\n */\n public static boolean toBoolean(String str, String trueString, String falseString) {\n if (str == null) {\n if (trueString == null) {\n return true;\n } else if (falseString == null) {\n return false;\n }\n } else if (str.equals(trueString)) {\n return true;\n } else if (str.equals(falseString)) {\n return false;\n }\n // no match\n throw new IllegalArgumentException(\"The String did not match either specified value\");\n }\n // Boolean to String methods\n //-----------------------------------------------------------------------\n\n /**\n *

Converts a Boolean to a String returning 'true',\n * 'false', or null.

\n *\n *
\n     *   BooleanUtils.toStringTrueFalse(Boolean.TRUE)  = \"true\"\n     *   BooleanUtils.toStringTrueFalse(Boolean.FALSE) = \"false\"\n     *   BooleanUtils.toStringTrueFalse(null)          = null;\n     * 
\n *\n * @param bool the Boolean to check\n * @return 'true', 'false',\n * or null\n */\n public static String toStringTrueFalse(Boolean bool) {\n return toString(bool, \"true\", \"false\", null);\n }\n\n /**\n *

Converts a Boolean to a String returning 'on',\n * 'off', or null.

\n *\n *
\n     *   BooleanUtils.toStringOnOff(Boolean.TRUE)  = \"on\"\n     *   BooleanUtils.toStringOnOff(Boolean.FALSE) = \"off\"\n     *   BooleanUtils.toStringOnOff(null)          = null;\n     * 
\n *\n * @param bool the Boolean to check\n * @return 'on', 'off',\n * or null\n */\n public static String toStringOnOff(Boolean bool) {\n return toString(bool, \"on\", \"off\", null);\n }\n\n /**\n *

Converts a Boolean to a String returning 'yes',\n * 'no', or null.

\n *\n *
\n     *   BooleanUtils.toStringYesNo(Boolean.TRUE)  = \"yes\"\n     *   BooleanUtils.toStringYesNo(Boolean.FALSE) = \"no\"\n     *   BooleanUtils.toStringYesNo(null)          = null;\n     * 
\n *\n * @param bool the Boolean to check\n * @return 'yes', 'no',\n * or null\n */\n public static String toStringYesNo(Boolean bool) {\n return toString(bool, \"yes\", \"no\", null);\n }\n\n /**\n *

Converts a Boolean to a String returning one of the input Strings.

\n *\n *
\n     *   BooleanUtils.toString(Boolean.TRUE, \"true\", \"false\", null)   = \"true\"\n     *   BooleanUtils.toString(Boolean.FALSE, \"true\", \"false\", null)  = \"false\"\n     *   BooleanUtils.toString(null, \"true\", \"false\", null)           = null;\n     * 
\n *\n * @param bool the Boolean to check\n * @param trueString the String to return if true,\n * may be null\n * @param falseString the String to return if false,\n * may be null\n * @param nullString the String to return if null,\n * may be null\n * @return one of the three input Strings\n */\n public static String toString(Boolean bool, String trueString, String falseString, String nullString) {\n if (bool == null) {\n return nullString;\n }\n return bool.booleanValue() ? trueString : falseString;\n }\n // boolean to String methods\n //-----------------------------------------------------------------------\n\n /**\n *

Converts a boolean to a String returning 'true'\n * or 'false'.

\n *\n *
\n     *   BooleanUtils.toStringTrueFalse(true)   = \"true\"\n     *   BooleanUtils.toStringTrueFalse(false)  = \"false\"\n     * 
\n *\n * @param bool the Boolean to check\n * @return 'true', 'false',\n * or null\n */\n public static String toStringTrueFalse(boolean bool) {\n return toString(bool, \"true\", \"false\");\n }\n\n /**\n *

Converts a boolean to a String returning 'on'\n * or 'off'.

\n *\n *
\n     *   BooleanUtils.toStringOnOff(true)   = \"on\"\n     *   BooleanUtils.toStringOnOff(false)  = \"off\"\n     * 
\n *\n * @param bool the Boolean to check\n * @return 'on', 'off',\n * or null\n */\n public static String toStringOnOff(boolean bool) {\n return toString(bool, \"on\", \"off\");\n }\n\n /**\n *

Converts a boolean to a String returning 'yes'\n * or 'no'.

\n *\n *
\n     *   BooleanUtils.toStringYesNo(true)   = \"yes\"\n     *   BooleanUtils.toStringYesNo(false)  = \"no\"\n     * 
\n *\n * @param bool the Boolean to check\n * @return 'yes', 'no',\n * or null\n */\n public static String toStringYesNo(boolean bool) {\n return toString(bool, \"yes\", \"no\");\n }\n\n /**\n *

Converts a boolean to a String returning one of the input Strings.

\n *\n *
\n     *   BooleanUtils.toString(true, \"true\", \"false\")   = \"true\"\n     *   BooleanUtils.toString(false, \"true\", \"false\")  = \"false\"\n     * 
\n *\n * @param bool the Boolean to check\n * @param trueString the String to return if true,\n * may be null\n * @param falseString the String to return if false,\n * may be null\n * @return one of the two input Strings\n */\n public static String toString(boolean bool, String trueString, String falseString) {\n return bool ? trueString : falseString;\n }\n // xor methods\n // ----------------------------------------------------------------------\n\n /**\n *

Performs an xor on a set of booleans.

\n *\n *
\n     *   BooleanUtils.xor(new boolean[] { true, true })   = false\n     *   BooleanUtils.xor(new boolean[] { false, false }) = false\n     *   BooleanUtils.xor(new boolean[] { true, false })  = true\n     * 
\n *\n * @param array an array of booleans\n * @return true if the xor is successful.\n * @throws IllegalArgumentException if array is null\n * @throws IllegalArgumentException if array is empty.\n */\n public static boolean xor(boolean[] array) {\n // Validates input\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array is empty\");\n }\n // Loops through array, comparing each item\n int trueCount = 0;\n for (int i = 0; i < array.length; i++) {\n // If item is true, and trueCount is < 1, increments count\n // Else, xor fails\n if (array[i]) {\n if (trueCount < 1) {\n trueCount++;\n } else {\n return false;\n }\n }\n }\n // Returns true if there was exactly 1 true item\n return trueCount == 1;\n }\n\n /**\n *

Performs an xor on an array of Booleans.

\n *\n *
\n     *   BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE })   = Boolean.FALSE\n     *   BooleanUtils.xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) = Boolean.FALSE\n     *   BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE })  = Boolean.TRUE\n     * 
\n *\n * @param array an array of Booleans\n * @return true if the xor is successful.\n * @throws IllegalArgumentException if array is null\n * @throws IllegalArgumentException if array is empty.\n * @throws IllegalArgumentException if array contains a null\n */\n public static Boolean xor(Boolean[] array) {\n if (array == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n } else if (array.length == 0) {\n throw new IllegalArgumentException(\"Array is empty\");\n }\n boolean[] primitive = null;\n try {\n primitive = ArrayUtils.toPrimitive(array);\n } catch (NullPointerException ex) {\n throw new IllegalArgumentException(\"The array must not contain any null elements\");\n }\n return xor(primitive) ? Boolean.TRUE : Boolean.FALSE;\n }\n\n //\n public static boolean isBooleanType(Class targetType) {\n return targetType.equals(Boolean.class) || targetType.equals(Boolean.TYPE);\n }\n}\n", "file_name": "BooleanUtils.java", "human_label": "Check whether the parameter bool is not true.", "level": "self_contained", "lineno": "90", "name": "isNotTrue", "oracle_context": "{ \"apis\" : \"[isTrue]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "6367674f1a6d9265ec017e74", "all_context": "{ \"class_level\" : \"int[] vs;\\nint i;\\nint n;\\nFixedSizeIntegerQueue(int capacity);\\npoll();\\nisEmpty();\\nsize();\\nclear();\\ntoString();\\nenqueue(int e);\\n\", \"repo_level\" : \"\" }", "class_name": "FixedSizeIntegerQueue", "code": "public String toString(){\n StringBuilder s=new StringBuilder();\n for (int j=i; j < n; j++) s.append(vs[j]).append(\" \");\n return s.toString();\n}\n", "docstring": "/** \n * Returns a textual representation of the queue.\n * @return a textual representation of the queue.\n */\n", "end_lineno": "107", "file_content": "/*\n * (C) Copyright 2017-2021, by Joris Kinable and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.util;\n\n/**\n * Primitive but efficient implementation of a fixed size queue for integers. Note: this queue is\n * not implemented as a ring, so at most $N$ enqueue operations are allowed, where $N$ is the\n * maximum capacity of the queue! After that, queue.clear() must be invoked.\n *\n * @author Joris Kinable\n */\npublic final class FixedSizeIntegerQueue\n{\n /* Storage array for the elements in the queue */\n private final int[] vs;\n /* Index of left most element in the queue */\n private int i = 0;\n /* Index of right most element in the queue. If i==n, the queue is empty */\n private int n = 0;\n\n /**\n * Create a queue of fixed size.\n *\n * @param capacity size of the queue\n */\n public FixedSizeIntegerQueue(int capacity)\n {\n assert capacity > 0;\n vs = new int[capacity];\n }\n\n /**\n * Add an element to the queue.\n *\n * @param e element\n */\n public void enqueue(int e)\n {\n assert n < vs.length;\n vs[n++] = e;\n }\n\n /**\n * Poll the first element from the queue.\n *\n * @return the first element.\n */\n public int poll()\n {\n assert !isEmpty();\n return vs[i++];\n }\n\n /**\n * Check if the queue has any items.\n *\n * @return true if the queue is empty\n */\n public boolean isEmpty()\n {\n return i == n;\n }\n\n /**\n * Returns the number of items in the queue.\n * \n * @return number of items in the queue\n */\n public int size()\n {\n return n - i;\n }\n\n /** Empty the queue. */\n public void clear()\n {\n i = 0;\n n = 0;\n }\n\n /**\n * Returns a textual representation of the queue.\n * \n * @return a textual representation of the queue.\n */\n public String toString()\n {\n StringBuilder s = new StringBuilder();\n for (int j = i; j < n; j++)\n s.append(vs[j]).append(\" \");\n return s.toString();\n }\n}\n", "file_name": "FixedSizeIntegerQueue.java", "human_label": "Convert a value in a vs array to a string", "level": "class_runnable", "lineno": "96", "name": "toString", "oracle_context": "{ \"apis\" : \"[append]\", \"classes\" : \"[StringBuilder]\", \"vars\" : \"[i, n, vs]\" }", "package": "org.jgrapht.alg.util", "project": "jgrapht-master" }, { "_id": "6367675c1a6d9265ec018058", "all_context": "{ \"class_level\" : \"import org.jgrapht.graph.*;\\nimport java.io.*;\\nimport java.lang.reflect.*;\\nimport java.util.*;\\nimport java.util.function.*;\\nSupplier DEFAULT_EDGE_SUPPLIER;\\nSupplier DEFAULT_WEIGHTED_EDGE_SUPPLIER;\\nSupplier OBJECT_SUPPLIER;\\nConstructor constructor;\\nlong serialVersionUID;\\nClass type;\\ngetThrowingSupplier(Throwable e);\\ncreateDefaultEdgeSupplier();\\ncreateDefaultWeightedEdgeSupplier();\\ncreateIntegerSupplier();\\ncreateIntegerSupplier(int start);\\ncreateLongSupplier();\\ncreateLongSupplier(long start);\\ncreateStringSupplier();\\ncreateRandomUUIDStringSupplier();\\ncreateStringSupplier(int start);\\nSerializedForm(Class type);\\nreadResolve();\\nConstructorSupplier(Constructor constructor);\\nget();\\nwriteReplace();\\ncreateSupplier(Class clazz);\\n\", \"repo_level\" : \"\" }", "class_name": "SupplierUtil", "code": "@SuppressWarnings(\"unchecked\") public static Supplier createStringSupplier(int start){\n int[] container=new int[]{start};\n return (Supplier & Serializable)() -> String.valueOf(container[0]++);\n}\n", "docstring": "/** \n * Create a string supplier which returns unique strings. The returns strings are simply integers starting from start.\n * @param start where to start the sequence\n * @return a string supplier\n */\n", "end_lineno": "198", "file_content": "/*\n * (C) Copyright 2018-2021, by Dimitrios Michail and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.util;\n\nimport org.jgrapht.graph.*;\n\nimport java.io.*;\nimport java.lang.reflect.*;\nimport java.util.*;\nimport java.util.function.*;\n\n/**\n * Helper class for suppliers.\n *\n * @author Dimitrios Michail\n */\npublic class SupplierUtil\n{\n\n /**\n * Supplier for {@link DefaultEdge}.\n */\n @SuppressWarnings(\"unchecked\")\n public static final Supplier DEFAULT_EDGE_SUPPLIER =\n (Supplier & Serializable) DefaultEdge::new;\n\n /**\n * Supplier for {@link DefaultWeightedEdge}.\n */\n @SuppressWarnings(\"unchecked\")\n public static final Supplier DEFAULT_WEIGHTED_EDGE_SUPPLIER =\n (Supplier & Serializable) DefaultWeightedEdge::new;\n\n /**\n * Supplier for {@link Object}.\n */\n @SuppressWarnings(\"unchecked\")\n public static final Supplier OBJECT_SUPPLIER =\n (Supplier & Serializable) Object::new;\n\n /**\n * Create a supplier from a class which calls the default constructor.\n * \n * @param clazz the class\n * @return the supplier\n * @param the type of results supplied by this supplier\n */\n @SuppressWarnings(\"unchecked\")\n public static Supplier createSupplier(Class clazz)\n {\n // shortcut to use pre-defined constructor method reference based suppliers\n if (clazz == DefaultEdge.class) {\n return (Supplier) DEFAULT_EDGE_SUPPLIER;\n } else if (clazz == DefaultWeightedEdge.class) {\n return (Supplier) DEFAULT_WEIGHTED_EDGE_SUPPLIER;\n } else if (clazz == Object.class) {\n return (Supplier) OBJECT_SUPPLIER;\n }\n\n try {\n final Constructor constructor = clazz.getDeclaredConstructor();\n if ((!Modifier.isPublic(constructor.getModifiers())\n || !Modifier.isPublic(constructor.getDeclaringClass().getModifiers()))\n && !constructor.canAccess(null))\n {\n constructor.setAccessible(true);\n }\n return new ConstructorSupplier<>(constructor);\n } catch (ReflectiveOperationException e) {\n // Defer throwing an exception to the first time the supplier is called\n return getThrowingSupplier(e);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private static Supplier getThrowingSupplier(Throwable e)\n {\n return (Supplier & Serializable) () -> {\n throw new SupplierException(e.getMessage(), e);\n };\n }\n\n /**\n * Create a default edge supplier.\n * \n * @return a default edge supplier\n */\n public static Supplier createDefaultEdgeSupplier()\n {\n return DEFAULT_EDGE_SUPPLIER;\n }\n\n /**\n * Create a default weighted edge supplier.\n * \n * @return a default weighted edge supplier\n */\n public static Supplier createDefaultWeightedEdgeSupplier()\n {\n return DEFAULT_WEIGHTED_EDGE_SUPPLIER;\n }\n\n /**\n * Create an integer supplier which returns a sequence starting from zero.\n * \n * @return an integer supplier\n */\n public static Supplier createIntegerSupplier()\n {\n return createIntegerSupplier(0);\n }\n\n /**\n * Create an integer supplier which returns a sequence starting from a specific numbers.\n * \n * @param start where to start the sequence\n * @return an integer supplier\n */\n @SuppressWarnings(\"unchecked\")\n public static Supplier createIntegerSupplier(int start)\n {\n int[] modifiableInt = new int[] { start }; // like a modifiable int\n return (Supplier & Serializable) () -> modifiableInt[0]++;\n }\n\n /**\n * Create a long supplier which returns a sequence starting from zero.\n * \n * @return a long supplier\n */\n public static Supplier createLongSupplier()\n {\n return createLongSupplier(0);\n }\n\n /**\n * Create a long supplier which returns a sequence starting from a specific numbers.\n * \n * @param start where to start the sequence\n * @return a long supplier\n */\n @SuppressWarnings(\"unchecked\")\n public static Supplier createLongSupplier(long start)\n {\n long[] modifiableLong = new long[] { start }; // like a modifiable long\n return (Supplier & Serializable) () -> modifiableLong[0]++;\n }\n\n /**\n * Create a string supplier which returns unique strings. The returns strings are simply\n * integers starting from zero.\n * \n * @return a string supplier\n */\n public static Supplier createStringSupplier()\n {\n return createStringSupplier(0);\n }\n\n /**\n * Create a string supplier which returns random UUIDs.\n * \n * @return a string supplier\n */\n @SuppressWarnings(\"unchecked\")\n public static Supplier createRandomUUIDStringSupplier()\n {\n return (Supplier & Serializable) () -> UUID.randomUUID().toString();\n }\n\n /**\n * Create a string supplier which returns unique strings. The returns strings are simply\n * integers starting from start.\n * \n * @param start where to start the sequence\n * @return a string supplier\n */\n @SuppressWarnings(\"unchecked\")\n public static Supplier createStringSupplier(int start)\n {\n int[] container = new int[] { start };\n return (Supplier & Serializable) () -> String.valueOf(container[0]++);\n }\n\n private static class ConstructorSupplier\n implements\n Supplier,\n Serializable\n {\n private final Constructor constructor;\n\n private static class SerializedForm\n implements\n Serializable\n {\n private static final long serialVersionUID = -2385289829144892760L;\n\n private final Class type;\n\n public SerializedForm(Class type)\n {\n this.type = type;\n }\n\n Object readResolve()\n throws ObjectStreamException\n {\n try {\n return new ConstructorSupplier<>(type.getDeclaredConstructor());\n } catch (ReflectiveOperationException e) {\n InvalidObjectException ex = new InvalidObjectException(\n \"Failed to get no-args constructor from \" + type);\n ex.initCause(e);\n throw ex;\n }\n }\n }\n\n public ConstructorSupplier(Constructor constructor)\n {\n this.constructor = constructor;\n }\n\n @Override\n public T get()\n {\n try {\n return constructor.newInstance();\n } catch (ReflectiveOperationException ex) {\n throw new SupplierException(\"Supplier failed\", ex);\n }\n }\n\n Object writeReplace()\n throws ObjectStreamException\n {\n return new SerializedForm<>(constructor.getDeclaringClass());\n }\n }\n}\n", "file_name": "SupplierUtil.java", "human_label": "Create a string supplier which returns unique integer strings starting from the given start.", "level": "slib_runnable", "lineno": "186", "name": "createStringSupplier", "oracle_context": "{ \"apis\" : \"[valueOf]\", \"classes\" : \"[int[]]\", \"vars\" : \"[]\" }", "package": "org.jgrapht.util", "project": "jgrapht-master" }, { "_id": "6367677b1a6d9265ec0182bd", "all_context": "{ \"class_level\" : \"import org.apache.log4j.helpers.OptionConverter;\\nimport org.apache.log4j.helpers.PatternConverter;\\nimport org.apache.log4j.pattern.BridgePatternConverter;\\nimport org.apache.log4j.spi.LoggingEvent;\\nString DEFAULT_CONVERSION_PATTERN;\\nString TTCC_CONVERSION_PATTERN;\\nint BUF_SIZE;\\nint MAX_CAPACITY;\\nString PATTERN_RULE_REGISTRY;\\nPatternConverter head;\\nString conversionPattern;\\nboolean handlesExceptions;\\nEnhancedPatternLayout();\\nEnhancedPatternLayout(String pattern);\\nsetConversionPattern(String conversionPattern);\\ngetConversionPattern();\\nactivateOptions();\\nformat(LoggingEvent event);\\nignoresThrowable();\\ncreatePatternParser(String pattern);\\n\", \"repo_level\" : \"public interface OptionConverter {static String[] concatanateArrays(String[] l,String[] r);\\nstatic String convertSpecialChars(String s);\\nstatic String getSystemProperty(String key,String def);\\nstatic Object instantiateByKey(Properties props,String key,Class superClass,Object defaultValue);\\nstatic boolean toBoolean(String value,boolean dEfault);\\nstatic int toInt(String value,int dEfault);\\nstatic Level toLevel(String value,Level defaultValue);\\nstatic long toFileSize(String value,long dEfault);\\nstatic String findAndSubst(String key,Properties props);\\nstatic Object instantiateByClassName(String className,Class superClass,Object defaultValue);\\nstatic String substVars(String val,Properties props);\\npublic void selectAndConfigure(InputStream inputStream,String clazz,LoggerRepository hierarchy);\\npublic void selectAndConfigure(URL url,String clazz,LoggerRepository hierarchy);\\n }\\npublic interface PatternConverter {protected String convert(LoggingEvent event);\\npublic void format(StringBuffer sbuf,LoggingEvent e);\\npublic void spacePad(StringBuffer sbuf,int length);\\n }\\npublic interface BridgePatternConverter {protected String convert(LoggingEvent event);\\npublic void format(StringBuffer sbuf,LoggingEvent e);\\npublic boolean ignoresThrowable();\\n }\\npublic interface LoggingEvent {public LocationInfo getLocationInformation();\\npublic Level getLevel();\\npublic String getLoggerName();\\npublic Category getLogger();\\npublic Object getMessage();\\npublic String getNDC();\\npublic Object getMDC(String key);\\npublic void getMDCCopy();\\npublic String getRenderedMessage();\\nstatic long getStartTime();\\npublic String getThreadName();\\npublic ThrowableInformation getThrowableInformation();\\npublic String[] getThrowableStrRep();\\nfinal void setProperty(String propName,String propValue);\\nfinal String getProperty(String key);\\nfinal boolean locationInformationExists();\\nfinal long getTimeStamp();\\npublic Set getPropertyKeySet();\\npublic Map getProperties();\\npublic String getFQNOfLoggerClass();\\npublic Object removeProperty(String propName);\\n }\\n\" }", "class_name": "EnhancedPatternLayout", "code": "public String format(final LoggingEvent event){\n StringBuffer buf=new StringBuffer();\n for (PatternConverter c=head; c != null; c=c.next) {\n c.format(buf,event);\n }\n return buf.toString();\n}\n", "docstring": "/** \n * Formats a logging event to a writer.\n * @param event logging event to be formatted.\n */\n", "end_lineno": "549", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.log4j;\n\nimport org.apache.log4j.helpers.OptionConverter;\nimport org.apache.log4j.helpers.PatternConverter;\nimport org.apache.log4j.pattern.BridgePatternConverter;\nimport org.apache.log4j.spi.LoggingEvent;\n\n\n// Contributors: Nelson Minar \n// Anders Kristensen \n\n/**\n * This class is an enhanced version of org.apache.log4j.PatternLayout\n * which was originally developed as part of the abandoned log4j 1.3\n * effort and has been available in the extras companion.\n * This pattern layout should be used in preference to\n * org.apache.log4j.PatternLayout except when compatibility\n * where PatternLayout has been extended either through subclassing\n * or alternative pattern parsers.\n *\n *\n *

A flexible layout configurable with pattern string. The goal of this class\n * is to {@link #format format} a {@link LoggingEvent} and return the results\n * in a {@link StringBuffer}. The format of the result depends on the\n * conversion pattern.\n *

\n *\n *

The conversion pattern is closely related to the conversion\n * pattern of the printf function in C. A conversion pattern is\n * composed of literal text and format control expressions called\n * conversion specifiers.\n *\n *

Note that you are free to insert any literal text within the\n * conversion pattern.\n *

\n\n

Each conversion specifier starts with a percent sign (%) and is\n followed by optional format modifiers and a conversion\n character. The conversion character specifies the type of\n data, e.g. category, priority, date, thread name. The format\n modifiers control such things as field width, padding, left and\n right justification. The following is a simple example.\n\n

Let the conversion pattern be \"%-5p [%t]: %m%n\" and assume\n that the log4j environment was set to use a EnhancedPatternLayout. Then the\n statements\n

\n   Category root = Category.getRoot();\n   root.debug(\"Message 1\");\n   root.warn(\"Message 2\");\n   
\n would yield the output\n
\n   DEBUG [main]: Message 1\n   WARN  [main]: Message 2\n   
\n\n

Note that there is no explicit separator between text and\n conversion specifiers. The pattern parser knows when it has reached\n the end of a conversion specifier when it reads a conversion\n character. In the example above the conversion specifier\n %-5p means the priority of the logging event should be left\n justified to a width of five characters.\n\n The recognized conversion characters are\n\n

\n \n \n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n\n \n \n\n \n \n\n \n \n\n \n\n\n \n \n \n \n\n \n \n\n \n\n \n \n\n \n\n \n \n \n \n\n \n\n \n\n \n \n\n\n \n \n\n \n\n \n\n \n\n \n\n \n \n\n\n \n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n \n\n \n\n \n\n \n \n\n
Conversion CharacterEffect
cUsed to output the category of the logging event. The\n category conversion specifier can be optionally followed by\n NameAbbreviator pattern.\n\n

For example, for the category name \"alpha.beta.gamma\" the pattern\n %c{2} will output the last two elements (\"beta.gamma\"),\n %c{-2} will remove two elements leaving \"gamma\",\n %c{1.} will output \"a.b.gamma\".\n\n

CUsed to output the fully qualified class name of the caller\n issuing the logging request. This conversion specifier\n can be optionally followed by precision specifier, that\n is a decimal constant in brackets.\n\n Used to output the category of the logging event. The\n category conversion specifier can be optionally followed by\n NameAbbreviator pattern.\n\n

For example, for the category name \"alpha.beta.gamma\" the pattern\n %c{2} will output the last two elements (\"beta.gamma\"),\n %c{-2} will remove two elements leaving \"gamma\",\n %c{1.} will output \"a.b.gamma\".\n\n

WARNING Generating the caller class information is\n slow. Thus, its use should be avoided unless execution speed is\n not an issue.\n\n

d Used to output the date of\n the logging event. The date conversion specifier may be\n followed by a set of braces containing a\n date and time pattern strings {@link java.text.SimpleDateFormat},\n ABSOLUTE, DATE or ISO8601\n and a set of braces containing a time zone id per \n {@link java.util.TimeZone#getTimeZone(String)}. \n For example, %d{HH:mm:ss,SSS},\n %d{dd MMM yyyy HH:mm:ss,SSS},\n %d{DATE} or %d{HH:mm:ss}{GMT+0}. If no date format specifier is given then\n ISO8601 format is assumed. \n
FUsed to output the file name where the logging request was\n issued.\n\n

WARNING Generating caller location information is\n extremely slow and should be avoided unless execution speed\n is not an issue.\n\n

lUsed to output location information of the caller which generated\n the logging event.\n\n

The location information depends on the JVM implementation but\n usually consists of the fully qualified name of the calling\n method followed by the callers source the file name and line\n number between parentheses.\n\n

The location information can be very useful. However, its\n generation is extremely slow and should be avoided\n unless execution speed is not an issue.\n\n

LUsed to output the line number from where the logging request\n was issued.\n\n

WARNING Generating caller location information is\n extremely slow and should be avoided unless execution speed\n is not an issue.\n\n

mUsed to output the application supplied message associated with\n the logging event.
MUsed to output the method name where the logging request was\n issued.\n\n

WARNING Generating caller location information is\n extremely slow and should be avoided unless execution speed\n is not an issue.\n\n

nOutputs the platform dependent line separator character or\n characters.\n\n

This conversion character offers practically the same\n performance as using non-portable line separator strings such as\n \"\\n\", or \"\\r\\n\". Thus, it is the preferred way of specifying a\n line separator.\n\n\n

pUsed to output the priority of the logging event.
rUsed to output the number of milliseconds elapsed since the construction \n of the layout until the creation of the logging event.
tUsed to output the name of the thread that generated the\n logging event.
xUsed to output the NDC (nested diagnostic context) associated\n with the thread that generated the logging event.\n
X\n\n

Used to output the MDC (mapped diagnostic context) associated\n with the thread that generated the logging event. The X\n conversion character can be followed by the key for the\n map placed between braces, as in %X{clientNumber} where\n clientNumber is the key. The value in the MDC\n corresponding to the key will be output. If no additional sub-option\n is specified, then the entire contents of the MDC key value pair set\n is output using a format {{key1,val1},{key2,val2}}

\n\n

See {@link MDC} class for more details.\n

\n\n
properties\n

Used to output the Properties associated\n with the logging event. The properties\n conversion word can be followed by the key for the\n map placed between braces, as in %properties{application} where\n application is the key. The value in the Properties bundle\n corresponding to the key will be output. If no additional sub-option\n is specified, then the entire contents of the Properties key value pair set\n is output using a format {{key1,val1},{key2,val2}}

\n
throwable\n

Used to output the Throwable trace that has been bound to the LoggingEvent, by\n default this will output the full trace as one would normally \n find by a call to Throwable.printStackTrace().\n %throwable{short} or %throwable{1} will output the first line of\n stack trace. throwable{none} or throwable{0} will suppress\n the stack trace. %throwable{n} will output n lines of stack trace\n if a positive integer or omit the last -n lines if a negative integer.\n If no %throwable pattern is specified, the appender will take\n responsibility to output the stack trace as it sees fit.

\n
%The sequence %% outputs a single percent sign.\n
\n\n

By default the relevant information is output as is. However,\n with the aid of format modifiers it is possible to change the\n minimum field width, the maximum field width and justification.\n\n

The optional format modifier is placed between the percent sign\n and the conversion character.\n\n

The first optional format modifier is the left justification\n flag which is just the minus (-) character. Then comes the\n optional minimum field width modifier. This is a decimal\n constant that represents the minimum number of characters to\n output. If the data item requires fewer characters, it is padded on\n either the left or the right until the minimum width is\n reached. The default is to pad on the left (right justify) but you\n can specify right padding with the left justification flag. The\n padding character is space. If the data item is larger than the\n minimum field width, the field is expanded to accommodate the\n data. The value is never truncated.\n\n

This behavior can be changed using the maximum field\n width modifier which is designated by a period followed by a\n decimal constant. If the data item is longer than the maximum\n field, then the extra characters are removed from the\n beginning of the data item and not from the end. For\n example, it the maximum field width is eight and the data item is\n ten characters long, then the first two characters of the data item\n are dropped. This behavior deviates from the printf function in C\n where truncation is done from the end.\n\n

Below are various format modifier examples for the category\n conversion specifier.\n\n

\n \n \n \n \n \n \n\n 20 \n \n \n \n \n\n \n \n \n \n \n\n \n \n \n \n \n\n
Format modifier\n left justify\n minimum width\n maximum width\n comment\n\n
%20cfalse20noneLeft pad with spaces if the category name is less than 20\n characters long.\n\n
%-20c true none Right pad with\n spaces if the category name is less than 20 characters long.\n\n
%.30cNAnone30Truncate from the beginning if the category name is longer than 30\n characters.\n\n
%20.30cfalse2030Left pad with spaces if the category name is shorter than 20\n characters. However, if category name is longer than 30 characters,\n then truncate from the beginning.\n\n
%-20.30ctrue2030Right pad with spaces if the category name is shorter than 20\n characters. However, if category name is longer than 30 characters,\n then truncate from the beginning.\n\n
\n\n

Below are some examples of conversion patterns.\n\n

\n\n

%r [%t] %-5p %c %x - %m%n\n

This is essentially the TTCC layout.\n\n

%-6r [%15.15t] %-5p %30.30c %x - %m%n\n\n

Similar to the TTCC layout except that the relative time is\n right padded if less than 6 digits, thread name is right padded if\n less than 15 characters and truncated if longer and the category\n name is left padded if shorter than 30 characters and truncated if\n longer.\n\n
\n\n

The above text is largely inspired from Peter A. Darnell and\n Philip E. Margolis' highly recommended book \"C -- a Software\n Engineering Approach\", ISBN 0-387-97389-3.\n\n @author James P. Cakalic\n @author Ceki Gülcü\n\n\n @since 1.2.16 */\npublic class EnhancedPatternLayout extends Layout {\n /** Default pattern string for log output. Currently set to the\n string \"%m%n\" which just prints the application supplied\n message. */\n public static final String DEFAULT_CONVERSION_PATTERN = \"%m%n\";\n\n /** A conversion pattern equivalent to the TTCCCLayout.\n Current value is %r [%t] %p %c %x - %m%n. */\n public static final String TTCC_CONVERSION_PATTERN =\n \"%r [%t] %p %c %x - %m%n\";\n\n /**\n * Initial size of internal buffer, no longer used.\n * @deprecated since 1.3\n */\n protected final int BUF_SIZE = 256;\n\n /**\n * Maximum capacity of internal buffer, no longer used.\n * @deprecated since 1.3\n */\n protected final int MAX_CAPACITY = 1024;\n\n /**\n * Customized pattern conversion rules are stored under this key in the\n * {@link org.apache.log4j.spi.LoggerRepository LoggerRepository} object store.\n */\n public static final String PATTERN_RULE_REGISTRY = \"PATTERN_RULE_REGISTRY\";\n\n\n /**\n * Initial converter for pattern.\n */\n private PatternConverter head;\n\n /**\n * Conversion pattern.\n */\n private String conversionPattern;\n\n /**\n * True if any element in pattern formats information from exceptions.\n */\n private boolean handlesExceptions;\n\n /**\n Constructs a EnhancedPatternLayout using the DEFAULT_LAYOUT_PATTERN.\n\n The default pattern just produces the application supplied message.\n */\n public EnhancedPatternLayout() {\n this(DEFAULT_CONVERSION_PATTERN);\n }\n\n /**\n * Constructs a EnhancedPatternLayout using the supplied conversion pattern.\n * @param pattern conversion pattern.\n */\n public EnhancedPatternLayout(final String pattern) {\n this.conversionPattern = pattern;\n head = createPatternParser(\n (pattern == null) ? DEFAULT_CONVERSION_PATTERN : pattern).parse();\n if (head instanceof BridgePatternConverter) {\n handlesExceptions = !((BridgePatternConverter) head).ignoresThrowable();\n } else {\n handlesExceptions = false;\n }\n }\n\n /**\n * Set the ConversionPattern option. This is the string which\n * controls formatting and consists of a mix of literal content and\n * conversion specifiers.\n *\n * @param conversionPattern conversion pattern.\n */\n public void setConversionPattern(final String conversionPattern) {\n this.conversionPattern =\n OptionConverter.convertSpecialChars(conversionPattern);\n head = createPatternParser(this.conversionPattern).parse();\n if (head instanceof BridgePatternConverter) {\n handlesExceptions = !((BridgePatternConverter) head).ignoresThrowable();\n } else {\n handlesExceptions = false;\n }\n }\n\n /**\n * Returns the value of the ConversionPattern option.\n * @return conversion pattern.\n */\n public String getConversionPattern() {\n return conversionPattern;\n }\n\n\n /**\n Returns PatternParser used to parse the conversion string. Subclasses\n may override this to return a subclass of PatternParser which recognize\n custom conversion characters.\n\n @since 0.9.0\n */\n protected org.apache.log4j.helpers.PatternParser createPatternParser(String pattern) {\n return new org.apache.log4j.pattern.BridgePatternParser(pattern);\n }\n\n\n /**\n Activates the conversion pattern. Do not forget to call this method after\n you change the parameters of the EnhancedPatternLayout instance.\n */\n public void activateOptions() {\n // nothing to do.\n }\n\n\n /**\n * Formats a logging event to a writer.\n * @param event logging event to be formatted.\n */\n public String format(final LoggingEvent event) {\n StringBuffer buf = new StringBuffer();\n for(PatternConverter c = head;\n c != null;\n c = c.next) {\n c.format(buf, event);\n }\n return buf.toString();\n }\n\n /**\n * Will return false if any of the conversion specifiers in the pattern\n * handles {@link Exception Exceptions}.\n * @return true if the pattern formats any information from exceptions.\n */\n public boolean ignoresThrowable() {\n return !handlesExceptions;\n }\n}\n", "file_name": "EnhancedPatternLayout.java", "human_label": "Formats LoggingEvent as a fixed-format string", "level": "project_runnable", "lineno": "537", "name": "format", "oracle_context": "{ \"apis\" : \"[toString]\", \"classes\" : \"[StringBuffer]\", \"vars\" : \"[next, head]\" }", "package": "org.apache.log4j", "project": "logging-log4j1-main" }, { "_id": "636766ff1a6d9265ec017842", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static double[] toPrimitive(final Double[] array){\n if (array == null) {\n return null;\n }\n else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result=new double[array.length];\n for (int i=0; i < array.length; i++) {\n result[i]=array[i].doubleValue();\n }\n return result;\n}\n", "docstring": "/** \n *

Converts an array of object Doubles to primitives.

This method returns null for a null input array.

\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n", "end_lineno": "2872", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

\n *\n *

This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

\n *\n *

#ThreadSafe#

\n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

\n *\n *

This method can be used to initialize:

\n *
\n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
\n *\n *

This method returns null for a null input array.

\n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

Shallow clones an array returning a typecast result and handling\n * null.

\n *\n *

The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

Clones an array returning a typecast result and handling\n * null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

Defensive programming technique to change a null\n * reference to an empty one.

\n *\n *

This method returns an empty array for a null input array.

\n *\n *

As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

\n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

Produces a new array containing the elements between\n * the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n *

The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

\n *\n *
\n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new long array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new int array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new short array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new char array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new byte array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new double array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new float array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

Produces a new boolean array containing the elements\n * between the start and end indices.

\n *\n *

The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

\n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

Any multi-dimensional aspects of the arrays are ignored.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

Checks whether two arrays are the same length, treating\n * null arrays as length 0.

\n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

\n *\n *

If the input array is null, 0 is returned.

\n *\n *
\n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
\n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

\n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

Reverses the order of the given array.

\n *\n *

There is no special handling for multi-dimensional arrays.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

Reverses the order of the given array.

\n *\n *

This method does nothing for a null input array.

\n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given object in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

Finds the index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given object within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given object in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the object is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

\n *\n *

The method returns false if a null array\n * is passed in.

\n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the index of the given value in the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

Finds the index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

\n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Finds the last index of the given value within the array.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

\n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

Finds the last index of the given value in the array starting at the given index.

\n *\n *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

\n *\n *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

\n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the value is in the given array.

\n *\n *

The method returns false if a null array is passed in.

\n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Characters to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Character to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive chars to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Longs to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Long to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive longs to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Integers to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Integer to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive ints to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Shorts to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Short to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive shorts to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Bytes to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Bytes to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive bytes to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Doubles to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Doubles to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive doubles to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Floats to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Floats to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive floats to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

Converts an array of object Booleans to primitives.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of object Booleans to primitives handling null.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

Converts an array of primitive booleans to objects.

\n *\n *

This method returns null for a null input array.

\n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive longs is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive ints is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive chars is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive floats is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is empty or null.

\n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

Checks if an array of Objects is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive longs is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive ints is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive shorts is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive chars is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive bytes is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive doubles is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive floats is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Checks if an array of primitive booleans is not empty or not null.

\n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Adds all the elements of the given arrays into a new array.

\n *

The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

\n *\n *
\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
\n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

\n *\n *
\n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n *
\n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

\n *\n *

This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *
\n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
\n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

\n *\n *

This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

\n *\n *

If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

\n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "If the length of the array is 0, return EMPTY_DOUBLE_ARAY. Otherwise, convert the array to an array of the double type.", "level": "self_contained", "lineno": "2852", "name": "toPrimitive", "oracle_context": "{ \"apis\" : \"[doubleValue, ArrayUtils]\", \"classes\" : \"[double[], ArrayUtils]\", \"vars\" : \"[length, EMPTY_DOUBLE_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636766fa1a6d9265ec0177a9", "all_context": "{ \"class_level\" : \"int SAME_FRAME;\\nint SAME_LOCALS_1_STACK_ITEM_FRAME;\\nint RESERVED;\\nint SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED;\\nint CHOP_FRAME;\\nint SAME_FRAME_EXTENDED;\\nint APPEND_FRAME;\\nint FULL_FRAME;\\nint ITEM_TOP;\\nint ITEM_INTEGER;\\nint ITEM_FLOAT;\\nint ITEM_DOUBLE;\\nint ITEM_LONG;\\nint ITEM_NULL;\\nint ITEM_UNINITIALIZED_THIS;\\nint ITEM_OBJECT;\\nint ITEM_UNINITIALIZED;\\nint ITEM_ASM_BOOLEAN;\\nint ITEM_ASM_BYTE;\\nint ITEM_ASM_CHAR;\\nint ITEM_ASM_SHORT;\\nint DIM_SIZE;\\nint KIND_SIZE;\\nint FLAGS_SIZE;\\nint VALUE_SIZE;\\nint DIM_SHIFT;\\nint KIND_SHIFT;\\nint FLAGS_SHIFT;\\nint DIM_MASK;\\nint KIND_MASK;\\nint VALUE_MASK;\\nint ARRAY_OF;\\nint ELEMENT_OF;\\nint CONSTANT_KIND;\\nint REFERENCE_KIND;\\nint UNINITIALIZED_KIND;\\nint LOCAL_KIND;\\nint STACK_KIND;\\nint TOP_IF_LONG_OR_DOUBLE_FLAG;\\nint TOP;\\nint BOOLEAN;\\nint BYTE;\\nint CHAR;\\nint SHORT;\\nint INTEGER;\\nint FLOAT;\\nint LONG;\\nint DOUBLE;\\nint NULL;\\nint UNINITIALIZED_THIS;\\nLabel owner;\\nint[] inputLocals;\\nint[] inputStack;\\nint[] outputLocals;\\nint[] outputStack;\\nshort outputStackStart;\\nshort outputStackTop;\\nint initializationCount;\\nint[] initializations;\\nFrame(Label owner);\\ngetAbstractTypeFromApiFormat(SymbolTable symbolTable,Object type);\\ngetAbstractTypeFromInternalName(SymbolTable symbolTable,String internalName);\\ngetAbstractTypeFromDescriptor(SymbolTable symbolTable,String buffer,int offset);\\nsetInputFrameFromDescriptor(SymbolTable symbolTable,int access,String descriptor,int maxLocals);\\nsetInputFrameFromApiFormat(SymbolTable symbolTable,int numLocal,Object[] local,int numStack,Object[] stack);\\ngetInputStackSize();\\ngetLocal(int localIndex);\\nsetLocal(int localIndex,int abstractType);\\npush(int abstractType);\\npush(SymbolTable symbolTable,String descriptor);\\npop();\\npop(int elements);\\npop(String descriptor);\\naddInitializedType(int abstractType);\\ngetInitializedType(SymbolTable symbolTable,int abstractType);\\nexecute(int opcode,int arg,Symbol argSymbol,SymbolTable symbolTable);\\ngetConcreteOutputType(int abstractOutputType,int numStack);\\nmerge(SymbolTable symbolTable,Frame dstFrame,int catchTypeIndex);\\nmerge(SymbolTable symbolTable,int sourceType,int[] dstTypes,int dstIndex);\\naccept(MethodWriter methodWriter);\\nputAbstractType(SymbolTable symbolTable,int abstractType,ByteVector output);\\ncopyFrom(Frame frame);\\n\", \"repo_level\" : \"\" }", "class_name": "Frame", "code": "private void addInitializedType(final int abstractType){\n if (initializations == null) {\n initializations=new int[2];\n }\n int initializationsLength=initializations.length;\n if (initializationCount >= initializationsLength) {\n int[] newInitializations=new int[Math.max(initializationCount + 1,2 * initializationsLength)];\n System.arraycopy(initializations,0,newInitializations,0,initializationsLength);\n initializations=newInitializations;\n }\n initializations[initializationCount++]=abstractType;\n}\n", "docstring": "/** \n * Adds an abstract type to the list of types on which a constructor is invoked in the basic block.\n * @param abstractType an abstract type on a which a constructor is invoked.\n */\n", "end_lineno": "582", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage net.hasor.utils.asm;\n/**\n * The input and output stack map frames of a basic block.\n *\n *

Stack map frames are computed in two steps:\n *\n *

    \n *
  • During the visit of each instruction in MethodWriter, the state of the frame at the end of\n * the current basic block is updated by simulating the action of the instruction on the\n * previous state of this so called \"output frame\".\n *
  • After all instructions have been visited, a fix point algorithm is used in MethodWriter to\n * compute the \"input frame\" of each basic block (i.e. the stack map frame at the beginning of\n * the basic block). See {@link MethodWriter#computeAllFrames}.\n *
\n *\n *

Output stack map frames are computed relatively to the input frame of the basic block, which\n * is not yet known when output frames are computed. It is therefore necessary to be able to\n * represent abstract types such as \"the type at position x in the input frame locals\" or \"the type\n * at position x from the top of the input frame stack\" or even \"the type at position x in the input\n * frame, with y more (or less) array dimensions\". This explains the rather complicated type format\n * used in this class, explained below.\n *\n *

The local variables and the operand stack of input and output frames contain values called\n * \"abstract types\" hereafter. An abstract type is represented with 4 fields named DIM, KIND, FLAGS\n * and VALUE, packed in a single int value for better performance and memory efficiency:\n *\n *

\n *   =====================================\n *   |...DIM|KIND|.F|...............VALUE|\n *   =====================================\n * 
\n *\n *
    \n *
  • the DIM field, stored in the 6 most significant bits, is a signed number of array\n * dimensions (from -32 to 31, included). It can be retrieved with {@link #DIM_MASK} and a\n * right shift of {@link #DIM_SHIFT}.\n *
  • the KIND field, stored in 4 bits, indicates the kind of VALUE used. These 4 bits can be\n * retrieved with {@link #KIND_MASK} and, without any shift, must be equal to {@link\n * #CONSTANT_KIND}, {@link #REFERENCE_KIND}, {@link #UNINITIALIZED_KIND}, {@link #LOCAL_KIND}\n * or {@link #STACK_KIND}.\n *
  • the FLAGS field, stored in 2 bits, contains up to 2 boolean flags. Currently only one flag\n * is defined, namely {@link #TOP_IF_LONG_OR_DOUBLE_FLAG}.\n *
  • the VALUE field, stored in the remaining 20 bits, contains either\n *
      \n *
    • one of the constants {@link #ITEM_TOP}, {@link #ITEM_ASM_BOOLEAN}, {@link\n * #ITEM_ASM_BYTE}, {@link #ITEM_ASM_CHAR} or {@link #ITEM_ASM_SHORT}, {@link\n * #ITEM_INTEGER}, {@link #ITEM_FLOAT}, {@link #ITEM_LONG}, {@link #ITEM_DOUBLE}, {@link\n * #ITEM_NULL} or {@link #ITEM_UNINITIALIZED_THIS}, if KIND is equal to {@link\n * #CONSTANT_KIND}.\n *
    • the index of a {@link Symbol#TYPE_TAG} {@link Symbol} in the type table of a {@link\n * SymbolTable}, if KIND is equal to {@link #REFERENCE_KIND}.\n *
    • the index of an {@link Symbol#UNINITIALIZED_TYPE_TAG} {@link Symbol} in the type\n * table of a SymbolTable, if KIND is equal to {@link #UNINITIALIZED_KIND}.\n *
    • the index of a local variable in the input stack frame, if KIND is equal to {@link\n * #LOCAL_KIND}.\n *
    • a position relatively to the top of the stack of the input stack frame, if KIND is\n * equal to {@link #STACK_KIND},\n *
    \n *
\n *\n *

Output frames can contain abstract types of any kind and with a positive or negative array\n * dimension (and even unassigned types, represented by 0 - which does not correspond to any valid\n * abstract type value). Input frames can only contain CONSTANT_KIND, REFERENCE_KIND or\n * UNINITIALIZED_KIND abstract types of positive or {@literal null} array dimension. In all cases\n * the type table contains only internal type names (array type descriptors are forbidden - array\n * dimensions must be represented through the DIM field).\n *\n *

The LONG and DOUBLE types are always represented by using two slots (LONG + TOP or DOUBLE +\n * TOP), for local variables as well as in the operand stack. This is necessary to be able to\n * simulate DUPx_y instructions, whose effect would be dependent on the concrete types represented\n * by the abstract types in the stack (which are not always known).\n *\n * @author Eric Bruneton\n */\nclass Frame {\n // Constants used in the StackMapTable attribute.\n // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.4.\n static final int SAME_FRAME = 0;\n static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64;\n static final int RESERVED = 128;\n static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247;\n static final int CHOP_FRAME = 248;\n static final int SAME_FRAME_EXTENDED = 251;\n static final int APPEND_FRAME = 252;\n static final int FULL_FRAME = 255;\n static final int ITEM_TOP = 0;\n static final int ITEM_INTEGER = 1;\n static final int ITEM_FLOAT = 2;\n static final int ITEM_DOUBLE = 3;\n static final int ITEM_LONG = 4;\n static final int ITEM_NULL = 5;\n static final int ITEM_UNINITIALIZED_THIS = 6;\n static final int ITEM_OBJECT = 7;\n static final int ITEM_UNINITIALIZED = 8;\n // Additional, ASM specific constants used in abstract types below.\n private static final int ITEM_ASM_BOOLEAN = 9;\n private static final int ITEM_ASM_BYTE = 10;\n private static final int ITEM_ASM_CHAR = 11;\n private static final int ITEM_ASM_SHORT = 12;\n // The size and offset in bits of each field of an abstract type.\n private static final int DIM_SIZE = 6;\n private static final int KIND_SIZE = 4;\n private static final int FLAGS_SIZE = 2;\n private static final int VALUE_SIZE = 32 - DIM_SIZE - KIND_SIZE - FLAGS_SIZE;\n private static final int DIM_SHIFT = KIND_SIZE + FLAGS_SIZE + VALUE_SIZE;\n private static final int KIND_SHIFT = FLAGS_SIZE + VALUE_SIZE;\n private static final int FLAGS_SHIFT = VALUE_SIZE;\n // Bitmasks to get each field of an abstract type.\n private static final int DIM_MASK = ((1 << DIM_SIZE) - 1) << DIM_SHIFT;\n private static final int KIND_MASK = ((1 << KIND_SIZE) - 1) << KIND_SHIFT;\n private static final int VALUE_MASK = (1 << VALUE_SIZE) - 1;\n // Constants to manipulate the DIM field of an abstract type.\n /** The constant to be added to an abstract type to get one with one more array dimension. */\n private static final int ARRAY_OF = +1 << DIM_SHIFT;\n /** The constant to be added to an abstract type to get one with one less array dimension. */\n private static final int ELEMENT_OF = -1 << DIM_SHIFT;\n // Possible values for the KIND field of an abstract type.\n private static final int CONSTANT_KIND = 1 << KIND_SHIFT;\n private static final int REFERENCE_KIND = 2 << KIND_SHIFT;\n private static final int UNINITIALIZED_KIND = 3 << KIND_SHIFT;\n private static final int LOCAL_KIND = 4 << KIND_SHIFT;\n private static final int STACK_KIND = 5 << KIND_SHIFT;\n // Possible flags for the FLAGS field of an abstract type.\n /**\n * A flag used for LOCAL_KIND and STACK_KIND abstract types, indicating that if the resolved,\n * concrete type is LONG or DOUBLE, TOP should be used instead (because the value has been\n * partially overridden with an xSTORE instruction).\n */\n private static final int TOP_IF_LONG_OR_DOUBLE_FLAG = 1 << FLAGS_SHIFT;\n // Useful predefined abstract types (all the possible CONSTANT_KIND types).\n private static final int TOP = CONSTANT_KIND | ITEM_TOP;\n private static final int BOOLEAN = CONSTANT_KIND | ITEM_ASM_BOOLEAN;\n private static final int BYTE = CONSTANT_KIND | ITEM_ASM_BYTE;\n private static final int CHAR = CONSTANT_KIND | ITEM_ASM_CHAR;\n private static final int SHORT = CONSTANT_KIND | ITEM_ASM_SHORT;\n private static final int INTEGER = CONSTANT_KIND | ITEM_INTEGER;\n private static final int FLOAT = CONSTANT_KIND | ITEM_FLOAT;\n private static final int LONG = CONSTANT_KIND | ITEM_LONG;\n private static final int DOUBLE = CONSTANT_KIND | ITEM_DOUBLE;\n private static final int NULL = CONSTANT_KIND | ITEM_NULL;\n private static final int UNINITIALIZED_THIS = CONSTANT_KIND | ITEM_UNINITIALIZED_THIS;\n // -----------------------------------------------------------------------------------------------\n // Instance fields\n // -----------------------------------------------------------------------------------------------\n /** The basic block to which these input and output stack map frames correspond. */\n Label owner;\n /** The input stack map frame locals. This is an array of abstract types. */\n private int[] inputLocals;\n /** The input stack map frame stack. This is an array of abstract types. */\n private int[] inputStack;\n /** The output stack map frame locals. This is an array of abstract types. */\n private int[] outputLocals;\n /** The output stack map frame stack. This is an array of abstract types. */\n private int[] outputStack;\n /**\n * The start of the output stack, relatively to the input stack. This offset is always negative or\n * null. A null offset means that the output stack must be appended to the input stack. A -n\n * offset means that the first n output stack elements must replace the top n input stack\n * elements, and that the other elements must be appended to the input stack.\n */\n private short outputStackStart;\n /** The index of the top stack element in {@link #outputStack}. */\n private short outputStackTop;\n /** The number of types that are initialized in the basic block. See {@link #initializations}. */\n private int initializationCount;\n /**\n * The abstract types that are initialized in the basic block. A constructor invocation on an\n * UNINITIALIZED or UNINITIALIZED_THIS abstract type must replace every occurrence of this\n * type in the local variables and in the operand stack. This cannot be done during the first step\n * of the algorithm since, during this step, the local variables and the operand stack types are\n * still abstract. It is therefore necessary to store the abstract types of the constructors which\n * are invoked in the basic block, in order to do this replacement during the second step of the\n * algorithm, where the frames are fully computed. Note that this array can contain abstract types\n * that are relative to the input locals or to the input stack.\n */\n private int[] initializations;\n // -----------------------------------------------------------------------------------------------\n // Constructor\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Constructs a new Frame.\n *\n * @param owner the basic block to which these input and output stack map frames correspond.\n */\n Frame(final Label owner) {\n this.owner = owner;\n }\n\n /**\n * Sets this frame to the value of the given frame.\n *\n *

WARNING: after this method is called the two frames share the same data structures. It is\n * recommended to discard the given frame to avoid unexpected side effects.\n *\n * @param frame The new frame value.\n */\n final void copyFrom(final Frame frame) {\n inputLocals = frame.inputLocals;\n inputStack = frame.inputStack;\n outputStackStart = 0;\n outputLocals = frame.outputLocals;\n outputStack = frame.outputStack;\n outputStackTop = frame.outputStackTop;\n initializationCount = frame.initializationCount;\n initializations = frame.initializations;\n }\n // -----------------------------------------------------------------------------------------------\n // Static methods to get abstract types from other type formats\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the abstract type corresponding to the given public API frame element type.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param type a frame element type described using the same format as in {@link\n * MethodVisitor#visitFrame}, i.e. either {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, {@link\n * Opcodes#FLOAT}, {@link Opcodes#LONG}, {@link Opcodes#DOUBLE}, {@link Opcodes#NULL}, or\n * {@link Opcodes#UNINITIALIZED_THIS}, or the internal name of a class, or a Label designating\n * a NEW instruction (for uninitialized types).\n * @return the abstract type corresponding to the given frame element type.\n */\n static int getAbstractTypeFromApiFormat(final SymbolTable symbolTable, final Object type) {\n if (type instanceof Integer) {\n return CONSTANT_KIND | ((Integer) type).intValue();\n } else if (type instanceof String) {\n String descriptor = Type.getObjectType((String) type).getDescriptor();\n return getAbstractTypeFromDescriptor(symbolTable, descriptor, 0);\n } else {\n return UNINITIALIZED_KIND | symbolTable.addUninitializedType(\"\", ((Label) type).bytecodeOffset);\n }\n }\n\n /**\n * Returns the abstract type corresponding to the internal name of a class.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param internalName the internal name of a class. This must not be an array type\n * descriptor.\n * @return the abstract type value corresponding to the given internal name.\n */\n static int getAbstractTypeFromInternalName(final SymbolTable symbolTable, final String internalName) {\n return REFERENCE_KIND | symbolTable.addType(internalName);\n }\n\n /**\n * Returns the abstract type corresponding to the given type descriptor.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param buffer a string ending with a type descriptor.\n * @param offset the start offset of the type descriptor in buffer.\n * @return the abstract type corresponding to the given type descriptor.\n */\n private static int getAbstractTypeFromDescriptor(final SymbolTable symbolTable, final String buffer, final int offset) {\n String internalName;\n switch (buffer.charAt(offset)) {\n case 'V':\n return 0;\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n return INTEGER;\n case 'F':\n return FLOAT;\n case 'J':\n return LONG;\n case 'D':\n return DOUBLE;\n case 'L':\n internalName = buffer.substring(offset + 1, buffer.length() - 1);\n return REFERENCE_KIND | symbolTable.addType(internalName);\n case '[':\n int elementDescriptorOffset = offset + 1;\n while (buffer.charAt(elementDescriptorOffset) == '[') {\n ++elementDescriptorOffset;\n }\n int typeValue;\n switch (buffer.charAt(elementDescriptorOffset)) {\n case 'Z':\n typeValue = BOOLEAN;\n break;\n case 'C':\n typeValue = CHAR;\n break;\n case 'B':\n typeValue = BYTE;\n break;\n case 'S':\n typeValue = SHORT;\n break;\n case 'I':\n typeValue = INTEGER;\n break;\n case 'F':\n typeValue = FLOAT;\n break;\n case 'J':\n typeValue = LONG;\n break;\n case 'D':\n typeValue = DOUBLE;\n break;\n case 'L':\n internalName = buffer.substring(elementDescriptorOffset + 1, buffer.length() - 1);\n typeValue = REFERENCE_KIND | symbolTable.addType(internalName);\n break;\n default:\n throw new IllegalArgumentException();\n }\n return ((elementDescriptorOffset - offset) << DIM_SHIFT) | typeValue;\n default:\n throw new IllegalArgumentException();\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Methods related to the input frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Sets the input frame from the given method description. This method is used to initialize the\n * first frame of a method, which is implicit (i.e. not stored explicitly in the StackMapTable\n * attribute).\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param access the method's access flags.\n * @param descriptor the method descriptor.\n * @param maxLocals the maximum number of local variables of the method.\n */\n final void setInputFrameFromDescriptor(final SymbolTable symbolTable, final int access, final String descriptor, final int maxLocals) {\n inputLocals = new int[maxLocals];\n inputStack = new int[0];\n int inputLocalIndex = 0;\n if ((access & Opcodes.ACC_STATIC) == 0) {\n if ((access & Constants.ACC_CONSTRUCTOR) == 0) {\n inputLocals[inputLocalIndex++] = REFERENCE_KIND | symbolTable.addType(symbolTable.getClassName());\n } else {\n inputLocals[inputLocalIndex++] = UNINITIALIZED_THIS;\n }\n }\n for (Type argumentType : Type.getArgumentTypes(descriptor)) {\n int abstractType = getAbstractTypeFromDescriptor(symbolTable, argumentType.getDescriptor(), 0);\n inputLocals[inputLocalIndex++] = abstractType;\n if (abstractType == LONG || abstractType == DOUBLE) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n }\n while (inputLocalIndex < maxLocals) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n }\n\n /**\n * Sets the input frame from the given public API frame description.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param numLocal the number of local variables.\n * @param local the local variable types, described using the same format as in {@link\n * MethodVisitor#visitFrame}.\n * @param numStack the number of operand stack elements.\n * @param stack the operand stack types, described using the same format as in {@link\n * MethodVisitor#visitFrame}.\n */\n final void setInputFrameFromApiFormat(final SymbolTable symbolTable, final int numLocal, final Object[] local, final int numStack, final Object[] stack) {\n int inputLocalIndex = 0;\n for (int i = 0; i < numLocal; ++i) {\n inputLocals[inputLocalIndex++] = getAbstractTypeFromApiFormat(symbolTable, local[i]);\n if (local[i] == Opcodes.LONG || local[i] == Opcodes.DOUBLE) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n }\n while (inputLocalIndex < inputLocals.length) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n int numStackTop = 0;\n for (int i = 0; i < numStack; ++i) {\n if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) {\n ++numStackTop;\n }\n }\n inputStack = new int[numStack + numStackTop];\n int inputStackIndex = 0;\n for (int i = 0; i < numStack; ++i) {\n inputStack[inputStackIndex++] = getAbstractTypeFromApiFormat(symbolTable, stack[i]);\n if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) {\n inputStack[inputStackIndex++] = TOP;\n }\n }\n outputStackTop = 0;\n initializationCount = 0;\n }\n\n final int getInputStackSize() {\n return inputStack.length;\n }\n // -----------------------------------------------------------------------------------------------\n // Methods related to the output frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the abstract type stored at the given local variable index in the output frame.\n *\n * @param localIndex the index of the local variable whose value must be returned.\n * @return the abstract type stored at the given local variable index in the output frame.\n */\n private int getLocal(final int localIndex) {\n if (outputLocals == null || localIndex >= outputLocals.length) {\n // If this local has never been assigned in this basic block, it is still equal to its value\n // in the input frame.\n return LOCAL_KIND | localIndex;\n } else {\n int abstractType = outputLocals[localIndex];\n if (abstractType == 0) {\n // If this local has never been assigned in this basic block, so it is still equal to its\n // value in the input frame.\n abstractType = outputLocals[localIndex] = LOCAL_KIND | localIndex;\n }\n return abstractType;\n }\n }\n\n /**\n * Replaces the abstract type stored at the given local variable index in the output frame.\n *\n * @param localIndex the index of the output frame local variable that must be set.\n * @param abstractType the value that must be set.\n */\n private void setLocal(final int localIndex, final int abstractType) {\n // Create and/or resize the output local variables array if necessary.\n if (outputLocals == null) {\n outputLocals = new int[10];\n }\n int outputLocalsLength = outputLocals.length;\n if (localIndex >= outputLocalsLength) {\n int[] newOutputLocals = new int[Math.max(localIndex + 1, 2 * outputLocalsLength)];\n System.arraycopy(outputLocals, 0, newOutputLocals, 0, outputLocalsLength);\n outputLocals = newOutputLocals;\n }\n // Set the local variable.\n outputLocals[localIndex] = abstractType;\n }\n\n /**\n * Pushes the given abstract type on the output frame stack.\n *\n * @param abstractType an abstract type.\n */\n private void push(final int abstractType) {\n // Create and/or resize the output stack array if necessary.\n if (outputStack == null) {\n outputStack = new int[10];\n }\n int outputStackLength = outputStack.length;\n if (outputStackTop >= outputStackLength) {\n int[] newOutputStack = new int[Math.max(outputStackTop + 1, 2 * outputStackLength)];\n System.arraycopy(outputStack, 0, newOutputStack, 0, outputStackLength);\n outputStack = newOutputStack;\n }\n // Pushes the abstract type on the output stack.\n outputStack[outputStackTop++] = abstractType;\n // Updates the maximum size reached by the output stack, if needed (note that this size is\n // relative to the input stack size, which is not known yet).\n short outputStackSize = (short) (outputStackStart + outputStackTop);\n if (outputStackSize > owner.outputStackMax) {\n owner.outputStackMax = outputStackSize;\n }\n }\n\n /**\n * Pushes the abstract type corresponding to the given descriptor on the output frame stack.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param descriptor a type or method descriptor (in which case its return type is pushed).\n */\n private void push(final SymbolTable symbolTable, final String descriptor) {\n int typeDescriptorOffset = descriptor.charAt(0) == '(' ? Type.getReturnTypeOffset(descriptor) : 0;\n int abstractType = getAbstractTypeFromDescriptor(symbolTable, descriptor, typeDescriptorOffset);\n if (abstractType != 0) {\n push(abstractType);\n if (abstractType == LONG || abstractType == DOUBLE) {\n push(TOP);\n }\n }\n }\n\n /**\n * Pops an abstract type from the output frame stack and returns its value.\n *\n * @return the abstract type that has been popped from the output frame stack.\n */\n private int pop() {\n if (outputStackTop > 0) {\n return outputStack[--outputStackTop];\n } else {\n // If the output frame stack is empty, pop from the input stack.\n return STACK_KIND | -(--outputStackStart);\n }\n }\n\n /**\n * Pops the given number of abstract types from the output frame stack.\n *\n * @param elements the number of abstract types that must be popped.\n */\n private void pop(final int elements) {\n if (outputStackTop >= elements) {\n outputStackTop -= elements;\n } else {\n // If the number of elements to be popped is greater than the number of elements in the output\n // stack, clear it, and pop the remaining elements from the input stack.\n outputStackStart -= elements - outputStackTop;\n outputStackTop = 0;\n }\n }\n\n /**\n * Pops as many abstract types from the output frame stack as described by the given descriptor.\n *\n * @param descriptor a type or method descriptor (in which case its argument types are popped).\n */\n private void pop(final String descriptor) {\n char firstDescriptorChar = descriptor.charAt(0);\n if (firstDescriptorChar == '(') {\n pop((Type.getArgumentsAndReturnSizes(descriptor) >> 2) - 1);\n } else if (firstDescriptorChar == 'J' || firstDescriptorChar == 'D') {\n pop(2);\n } else {\n pop(1);\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Methods to handle uninitialized types\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Adds an abstract type to the list of types on which a constructor is invoked in the basic\n * block.\n *\n * @param abstractType an abstract type on a which a constructor is invoked.\n */\n private void addInitializedType(final int abstractType) {\n // Create and/or resize the initializations array if necessary.\n if (initializations == null) {\n initializations = new int[2];\n }\n int initializationsLength = initializations.length;\n if (initializationCount >= initializationsLength) {\n int[] newInitializations = new int[Math.max(initializationCount + 1, 2 * initializationsLength)];\n System.arraycopy(initializations, 0, newInitializations, 0, initializationsLength);\n initializations = newInitializations;\n }\n // Store the abstract type.\n initializations[initializationCount++] = abstractType;\n }\n\n /**\n * Returns the \"initialized\" abstract type corresponding to the given abstract type.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param abstractType an abstract type.\n * @return the REFERENCE_KIND abstract type corresponding to abstractType if it is\n * UNINITIALIZED_THIS or an UNINITIALIZED_KIND abstract type for one of the types on which a\n * constructor is invoked in the basic block. Otherwise returns abstractType.\n */\n private int getInitializedType(final SymbolTable symbolTable, final int abstractType) {\n if (abstractType == UNINITIALIZED_THIS || (abstractType & (DIM_MASK | KIND_MASK)) == UNINITIALIZED_KIND) {\n for (int i = 0; i < initializationCount; ++i) {\n int initializedType = initializations[i];\n int dim = initializedType & DIM_MASK;\n int kind = initializedType & KIND_MASK;\n int value = initializedType & VALUE_MASK;\n if (kind == LOCAL_KIND) {\n initializedType = dim + inputLocals[value];\n } else if (kind == STACK_KIND) {\n initializedType = dim + inputStack[inputStack.length - value];\n }\n if (abstractType == initializedType) {\n if (abstractType == UNINITIALIZED_THIS) {\n return REFERENCE_KIND | symbolTable.addType(symbolTable.getClassName());\n } else {\n return REFERENCE_KIND | symbolTable.addType(symbolTable.getType(abstractType & VALUE_MASK).value);\n }\n }\n }\n }\n return abstractType;\n }\n // -----------------------------------------------------------------------------------------------\n // Main method, to simulate the execution of each instruction on the output frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Simulates the action of the given instruction on the output stack frame.\n *\n * @param opcode the opcode of the instruction.\n * @param arg the numeric operand of the instruction, if any.\n * @param argSymbol the Symbol operand of the instruction, if any.\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n */\n void execute(final int opcode, final int arg, final Symbol argSymbol, final SymbolTable symbolTable) {\n // Abstract types popped from the stack or read from local variables.\n int abstractType1;\n int abstractType2;\n int abstractType3;\n int abstractType4;\n switch (opcode) {\n case Opcodes.NOP:\n case Opcodes.INEG:\n case Opcodes.LNEG:\n case Opcodes.FNEG:\n case Opcodes.DNEG:\n case Opcodes.I2B:\n case Opcodes.I2C:\n case Opcodes.I2S:\n case Opcodes.GOTO:\n case Opcodes.RETURN:\n break;\n case Opcodes.ACONST_NULL:\n push(NULL);\n break;\n case Opcodes.ICONST_M1:\n case Opcodes.ICONST_0:\n case Opcodes.ICONST_1:\n case Opcodes.ICONST_2:\n case Opcodes.ICONST_3:\n case Opcodes.ICONST_4:\n case Opcodes.ICONST_5:\n case Opcodes.BIPUSH:\n case Opcodes.SIPUSH:\n case Opcodes.ILOAD:\n push(INTEGER);\n break;\n case Opcodes.LCONST_0:\n case Opcodes.LCONST_1:\n case Opcodes.LLOAD:\n push(LONG);\n push(TOP);\n break;\n case Opcodes.FCONST_0:\n case Opcodes.FCONST_1:\n case Opcodes.FCONST_2:\n case Opcodes.FLOAD:\n push(FLOAT);\n break;\n case Opcodes.DCONST_0:\n case Opcodes.DCONST_1:\n case Opcodes.DLOAD:\n push(DOUBLE);\n push(TOP);\n break;\n case Opcodes.LDC:\n switch (argSymbol.tag) {\n case Symbol.CONSTANT_INTEGER_TAG:\n push(INTEGER);\n break;\n case Symbol.CONSTANT_LONG_TAG:\n push(LONG);\n push(TOP);\n break;\n case Symbol.CONSTANT_FLOAT_TAG:\n push(FLOAT);\n break;\n case Symbol.CONSTANT_DOUBLE_TAG:\n push(DOUBLE);\n push(TOP);\n break;\n case Symbol.CONSTANT_CLASS_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/Class\"));\n break;\n case Symbol.CONSTANT_STRING_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/String\"));\n break;\n case Symbol.CONSTANT_METHOD_TYPE_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/invoke/MethodType\"));\n break;\n case Symbol.CONSTANT_METHOD_HANDLE_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/invoke/MethodHandle\"));\n break;\n case Symbol.CONSTANT_DYNAMIC_TAG:\n push(symbolTable, argSymbol.value);\n break;\n default:\n throw new AssertionError();\n }\n break;\n case Opcodes.ALOAD:\n push(getLocal(arg));\n break;\n case Opcodes.LALOAD:\n case Opcodes.D2L:\n pop(2);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.DALOAD:\n case Opcodes.L2D:\n pop(2);\n push(DOUBLE);\n push(TOP);\n break;\n case Opcodes.AALOAD:\n pop(1);\n abstractType1 = pop();\n push(abstractType1 == NULL ? abstractType1 : ELEMENT_OF + abstractType1);\n break;\n case Opcodes.ISTORE:\n case Opcodes.FSTORE:\n case Opcodes.ASTORE:\n abstractType1 = pop();\n setLocal(arg, abstractType1);\n if (arg > 0) {\n int previousLocalType = getLocal(arg - 1);\n if (previousLocalType == LONG || previousLocalType == DOUBLE) {\n setLocal(arg - 1, TOP);\n } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND || (previousLocalType & KIND_MASK) == STACK_KIND) {\n // The type of the previous local variable is not known yet, but if it later appears\n // to be LONG or DOUBLE, we should then use TOP instead.\n setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG);\n }\n }\n break;\n case Opcodes.LSTORE:\n case Opcodes.DSTORE:\n pop(1);\n abstractType1 = pop();\n setLocal(arg, abstractType1);\n setLocal(arg + 1, TOP);\n if (arg > 0) {\n int previousLocalType = getLocal(arg - 1);\n if (previousLocalType == LONG || previousLocalType == DOUBLE) {\n setLocal(arg - 1, TOP);\n } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND || (previousLocalType & KIND_MASK) == STACK_KIND) {\n // The type of the previous local variable is not known yet, but if it later appears\n // to be LONG or DOUBLE, we should then use TOP instead.\n setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG);\n }\n }\n break;\n case Opcodes.IASTORE:\n case Opcodes.BASTORE:\n case Opcodes.CASTORE:\n case Opcodes.SASTORE:\n case Opcodes.FASTORE:\n case Opcodes.AASTORE:\n pop(3);\n break;\n case Opcodes.LASTORE:\n case Opcodes.DASTORE:\n pop(4);\n break;\n case Opcodes.POP:\n case Opcodes.IFEQ:\n case Opcodes.IFNE:\n case Opcodes.IFLT:\n case Opcodes.IFGE:\n case Opcodes.IFGT:\n case Opcodes.IFLE:\n case Opcodes.IRETURN:\n case Opcodes.FRETURN:\n case Opcodes.ARETURN:\n case Opcodes.TABLESWITCH:\n case Opcodes.LOOKUPSWITCH:\n case Opcodes.ATHROW:\n case Opcodes.MONITORENTER:\n case Opcodes.MONITOREXIT:\n case Opcodes.IFNULL:\n case Opcodes.IFNONNULL:\n pop(1);\n break;\n case Opcodes.POP2:\n case Opcodes.IF_ICMPEQ:\n case Opcodes.IF_ICMPNE:\n case Opcodes.IF_ICMPLT:\n case Opcodes.IF_ICMPGE:\n case Opcodes.IF_ICMPGT:\n case Opcodes.IF_ICMPLE:\n case Opcodes.IF_ACMPEQ:\n case Opcodes.IF_ACMPNE:\n case Opcodes.LRETURN:\n case Opcodes.DRETURN:\n pop(2);\n break;\n case Opcodes.DUP:\n abstractType1 = pop();\n push(abstractType1);\n push(abstractType1);\n break;\n case Opcodes.DUP_X1:\n abstractType1 = pop();\n abstractType2 = pop();\n push(abstractType1);\n push(abstractType2);\n push(abstractType1);\n break;\n case Opcodes.DUP_X2:\n abstractType1 = pop();\n abstractType2 = pop();\n abstractType3 = pop();\n push(abstractType1);\n push(abstractType3);\n push(abstractType2);\n push(abstractType1);\n break;\n case Opcodes.DUP2:\n abstractType1 = pop();\n abstractType2 = pop();\n push(abstractType2);\n push(abstractType1);\n push(abstractType2);\n push(abstractType1);\n break;\n case Opcodes.DUP2_X1:\n abstractType1 = pop();\n abstractType2 = pop();\n abstractType3 = pop();\n push(abstractType2);\n push(abstractType1);\n push(abstractType3);\n push(abstractType2);\n push(abstractType1);\n break;\n case Opcodes.DUP2_X2:\n abstractType1 = pop();\n abstractType2 = pop();\n abstractType3 = pop();\n abstractType4 = pop();\n push(abstractType2);\n push(abstractType1);\n push(abstractType4);\n push(abstractType3);\n push(abstractType2);\n push(abstractType1);\n break;\n case Opcodes.SWAP:\n abstractType1 = pop();\n abstractType2 = pop();\n push(abstractType1);\n push(abstractType2);\n break;\n case Opcodes.IALOAD:\n case Opcodes.BALOAD:\n case Opcodes.CALOAD:\n case Opcodes.SALOAD:\n case Opcodes.IADD:\n case Opcodes.ISUB:\n case Opcodes.IMUL:\n case Opcodes.IDIV:\n case Opcodes.IREM:\n case Opcodes.IAND:\n case Opcodes.IOR:\n case Opcodes.IXOR:\n case Opcodes.ISHL:\n case Opcodes.ISHR:\n case Opcodes.IUSHR:\n case Opcodes.L2I:\n case Opcodes.D2I:\n case Opcodes.FCMPL:\n case Opcodes.FCMPG:\n pop(2);\n push(INTEGER);\n break;\n case Opcodes.LADD:\n case Opcodes.LSUB:\n case Opcodes.LMUL:\n case Opcodes.LDIV:\n case Opcodes.LREM:\n case Opcodes.LAND:\n case Opcodes.LOR:\n case Opcodes.LXOR:\n pop(4);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.FALOAD:\n case Opcodes.FADD:\n case Opcodes.FSUB:\n case Opcodes.FMUL:\n case Opcodes.FDIV:\n case Opcodes.FREM:\n case Opcodes.L2F:\n case Opcodes.D2F:\n pop(2);\n push(FLOAT);\n break;\n case Opcodes.DADD:\n case Opcodes.DSUB:\n case Opcodes.DMUL:\n case Opcodes.DDIV:\n case Opcodes.DREM:\n pop(4);\n push(DOUBLE);\n push(TOP);\n break;\n case Opcodes.LSHL:\n case Opcodes.LSHR:\n case Opcodes.LUSHR:\n pop(3);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.IINC:\n setLocal(arg, INTEGER);\n break;\n case Opcodes.I2L:\n case Opcodes.F2L:\n pop(1);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.I2F:\n pop(1);\n push(FLOAT);\n break;\n case Opcodes.I2D:\n case Opcodes.F2D:\n pop(1);\n push(DOUBLE);\n push(TOP);\n break;\n case Opcodes.F2I:\n case Opcodes.ARRAYLENGTH:\n case Opcodes.INSTANCEOF:\n pop(1);\n push(INTEGER);\n break;\n case Opcodes.LCMP:\n case Opcodes.DCMPL:\n case Opcodes.DCMPG:\n pop(4);\n push(INTEGER);\n break;\n case Opcodes.JSR:\n case Opcodes.RET:\n throw new IllegalArgumentException(\"JSR/RET are not supported with computeFrames option\");\n case Opcodes.GETSTATIC:\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.PUTSTATIC:\n pop(argSymbol.value);\n break;\n case Opcodes.GETFIELD:\n pop(1);\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.PUTFIELD:\n pop(argSymbol.value);\n pop();\n break;\n case Opcodes.INVOKEVIRTUAL:\n case Opcodes.INVOKESPECIAL:\n case Opcodes.INVOKESTATIC:\n case Opcodes.INVOKEINTERFACE:\n pop(argSymbol.value);\n if (opcode != Opcodes.INVOKESTATIC) {\n abstractType1 = pop();\n if (opcode == Opcodes.INVOKESPECIAL && argSymbol.name.charAt(0) == '<') {\n addInitializedType(abstractType1);\n }\n }\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.INVOKEDYNAMIC:\n pop(argSymbol.value);\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.NEW:\n push(UNINITIALIZED_KIND | symbolTable.addUninitializedType(argSymbol.value, arg));\n break;\n case Opcodes.NEWARRAY:\n pop();\n switch (arg) {\n case Opcodes.T_BOOLEAN:\n push(ARRAY_OF | BOOLEAN);\n break;\n case Opcodes.T_CHAR:\n push(ARRAY_OF | CHAR);\n break;\n case Opcodes.T_BYTE:\n push(ARRAY_OF | BYTE);\n break;\n case Opcodes.T_SHORT:\n push(ARRAY_OF | SHORT);\n break;\n case Opcodes.T_INT:\n push(ARRAY_OF | INTEGER);\n break;\n case Opcodes.T_FLOAT:\n push(ARRAY_OF | FLOAT);\n break;\n case Opcodes.T_DOUBLE:\n push(ARRAY_OF | DOUBLE);\n break;\n case Opcodes.T_LONG:\n push(ARRAY_OF | LONG);\n break;\n default:\n throw new IllegalArgumentException();\n }\n break;\n case Opcodes.ANEWARRAY:\n String arrayElementType = argSymbol.value;\n pop();\n if (arrayElementType.charAt(0) == '[') {\n push(symbolTable, '[' + arrayElementType);\n } else {\n push(ARRAY_OF | REFERENCE_KIND | symbolTable.addType(arrayElementType));\n }\n break;\n case Opcodes.CHECKCAST:\n String castType = argSymbol.value;\n pop();\n if (castType.charAt(0) == '[') {\n push(symbolTable, castType);\n } else {\n push(REFERENCE_KIND | symbolTable.addType(castType));\n }\n break;\n case Opcodes.MULTIANEWARRAY:\n pop(arg);\n push(symbolTable, argSymbol.value);\n break;\n default:\n throw new IllegalArgumentException();\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Frame merging methods, used in the second step of the stack map frame computation algorithm\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Computes the concrete output type corresponding to a given abstract output type.\n *\n * @param abstractOutputType an abstract output type.\n * @param numStack the size of the input stack, used to resolve abstract output types of\n * STACK_KIND kind.\n * @return the concrete output type corresponding to 'abstractOutputType'.\n */\n private int getConcreteOutputType(final int abstractOutputType, final int numStack) {\n int dim = abstractOutputType & DIM_MASK;\n int kind = abstractOutputType & KIND_MASK;\n if (kind == LOCAL_KIND) {\n // By definition, a LOCAL_KIND type designates the concrete type of a local variable at\n // the beginning of the basic block corresponding to this frame (which is known when\n // this method is called, but was not when the abstract type was computed).\n int concreteOutputType = dim + inputLocals[abstractOutputType & VALUE_MASK];\n if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0 && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) {\n concreteOutputType = TOP;\n }\n return concreteOutputType;\n } else if (kind == STACK_KIND) {\n // By definition, a STACK_KIND type designates the concrete type of a local variable at\n // the beginning of the basic block corresponding to this frame (which is known when\n // this method is called, but was not when the abstract type was computed).\n int concreteOutputType = dim + inputStack[numStack - (abstractOutputType & VALUE_MASK)];\n if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0 && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) {\n concreteOutputType = TOP;\n }\n return concreteOutputType;\n } else {\n return abstractOutputType;\n }\n }\n\n /**\n * Merges the input frame of the given {@link Frame} with the input and output frames of this\n * {@link Frame}. Returns {@literal true} if the given frame has been changed by this operation\n * (the input and output frames of this {@link Frame} are never changed).\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param dstFrame the {@link Frame} whose input frame must be updated. This should be the frame\n * of a successor, in the control flow graph, of the basic block corresponding to this frame.\n * @param catchTypeIndex if 'frame' corresponds to an exception handler basic block, the type\n * table index of the caught exception type, otherwise 0.\n * @return {@literal true} if the input frame of 'frame' has been changed by this operation.\n */\n final boolean merge(final SymbolTable symbolTable, final Frame dstFrame, final int catchTypeIndex) {\n boolean frameChanged = false;\n // Compute the concrete types of the local variables at the end of the basic block corresponding\n // to this frame, by resolving its abstract output types, and merge these concrete types with\n // those of the local variables in the input frame of dstFrame.\n int numLocal = inputLocals.length;\n int numStack = inputStack.length;\n if (dstFrame.inputLocals == null) {\n dstFrame.inputLocals = new int[numLocal];\n frameChanged = true;\n }\n for (int i = 0; i < numLocal; ++i) {\n int concreteOutputType;\n if (outputLocals != null && i < outputLocals.length) {\n int abstractOutputType = outputLocals[i];\n if (abstractOutputType == 0) {\n // If the local variable has never been assigned in this basic block, it is equal to its\n // value at the beginning of the block.\n concreteOutputType = inputLocals[i];\n } else {\n concreteOutputType = getConcreteOutputType(abstractOutputType, numStack);\n }\n } else {\n // If the local variable has never been assigned in this basic block, it is equal to its\n // value at the beginning of the block.\n concreteOutputType = inputLocals[i];\n }\n // concreteOutputType might be an uninitialized type from the input locals or from the input\n // stack. However, if a constructor has been called for this class type in the basic block,\n // then this type is no longer uninitialized at the end of basic block.\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputLocals, i);\n }\n // If dstFrame is an exception handler block, it can be reached from any instruction of the\n // basic block corresponding to this frame, in particular from the first one. Therefore, the\n // input locals of dstFrame should be compatible (i.e. merged) with the input locals of this\n // frame (and the input stack of dstFrame should be compatible, i.e. merged, with a one\n // element stack containing the caught exception type).\n if (catchTypeIndex > 0) {\n for (int i = 0; i < numLocal; ++i) {\n frameChanged |= merge(symbolTable, inputLocals[i], dstFrame.inputLocals, i);\n }\n if (dstFrame.inputStack == null) {\n dstFrame.inputStack = new int[1];\n frameChanged = true;\n }\n frameChanged |= merge(symbolTable, catchTypeIndex, dstFrame.inputStack, 0);\n return frameChanged;\n }\n // Compute the concrete types of the stack operands at the end of the basic block corresponding\n // to this frame, by resolving its abstract output types, and merge these concrete types with\n // those of the stack operands in the input frame of dstFrame.\n int numInputStack = inputStack.length + outputStackStart;\n if (dstFrame.inputStack == null) {\n dstFrame.inputStack = new int[numInputStack + outputStackTop];\n frameChanged = true;\n }\n // First, do this for the stack operands that have not been popped in the basic block\n // corresponding to this frame, and which are therefore equal to their value in the input\n // frame (except for uninitialized types, which may have been initialized).\n for (int i = 0; i < numInputStack; ++i) {\n int concreteOutputType = inputStack[i];\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputStack, i);\n }\n // Then, do this for the stack operands that have pushed in the basic block (this code is the\n // same as the one above for local variables).\n for (int i = 0; i < outputStackTop; ++i) {\n int abstractOutputType = outputStack[i];\n int concreteOutputType = getConcreteOutputType(abstractOutputType, numStack);\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputStack, numInputStack + i);\n }\n return frameChanged;\n }\n\n /**\n * Merges the type at the given index in the given abstract type array with the given type.\n * Returns {@literal true} if the type array has been modified by this operation.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param sourceType the abstract type with which the abstract type array element must be merged.\n * This type should be of {@link #CONSTANT_KIND}, {@link #REFERENCE_KIND} or {@link\n * #UNINITIALIZED_KIND} kind, with positive or {@literal null} array dimensions.\n * @param dstTypes an array of abstract types. These types should be of {@link #CONSTANT_KIND},\n * {@link #REFERENCE_KIND} or {@link #UNINITIALIZED_KIND} kind, with positive or {@literal\n * null} array dimensions.\n * @param dstIndex the index of the type that must be merged in dstTypes.\n * @return {@literal true} if the type array has been modified by this operation.\n */\n private static boolean merge(final SymbolTable symbolTable, final int sourceType, final int[] dstTypes, final int dstIndex) {\n int dstType = dstTypes[dstIndex];\n if (dstType == sourceType) {\n // If the types are equal, merge(sourceType, dstType) = dstType, so there is no change.\n return false;\n }\n int srcType = sourceType;\n if ((sourceType & ~DIM_MASK) == NULL) {\n if (dstType == NULL) {\n return false;\n }\n srcType = NULL;\n }\n if (dstType == 0) {\n // If dstTypes[dstIndex] has never been assigned, merge(srcType, dstType) = srcType.\n dstTypes[dstIndex] = srcType;\n return true;\n }\n int mergedType;\n if ((dstType & DIM_MASK) != 0 || (dstType & KIND_MASK) == REFERENCE_KIND) {\n // If dstType is a reference type of any array dimension.\n if (srcType == NULL) {\n // If srcType is the NULL type, merge(srcType, dstType) = dstType, so there is no change.\n return false;\n } else if ((srcType & (DIM_MASK | KIND_MASK)) == (dstType & (DIM_MASK | KIND_MASK))) {\n // If srcType has the same array dimension and the same kind as dstType.\n if ((dstType & KIND_MASK) == REFERENCE_KIND) {\n // If srcType and dstType are reference types with the same array dimension,\n // merge(srcType, dstType) = dim(srcType) | common super class of srcType and dstType.\n mergedType = (srcType & DIM_MASK) | REFERENCE_KIND | symbolTable.addMergedType(srcType & VALUE_MASK, dstType & VALUE_MASK);\n } else {\n // If srcType and dstType are array types of equal dimension but different element types,\n // merge(srcType, dstType) = dim(srcType) - 1 | java/lang/Object.\n int mergedDim = ELEMENT_OF + (srcType & DIM_MASK);\n mergedType = mergedDim | REFERENCE_KIND | symbolTable.addType(\"java/lang/Object\");\n }\n } else if ((srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND) {\n // If srcType is any other reference or array type,\n // merge(srcType, dstType) = min(srcDdim, dstDim) | java/lang/Object\n // where srcDim is the array dimension of srcType, minus 1 if srcType is an array type\n // with a non reference element type (and similarly for dstDim).\n int srcDim = srcType & DIM_MASK;\n if (srcDim != 0 && (srcType & KIND_MASK) != REFERENCE_KIND) {\n srcDim = ELEMENT_OF + srcDim;\n }\n int dstDim = dstType & DIM_MASK;\n if (dstDim != 0 && (dstType & KIND_MASK) != REFERENCE_KIND) {\n dstDim = ELEMENT_OF + dstDim;\n }\n mergedType = Math.min(srcDim, dstDim) | REFERENCE_KIND | symbolTable.addType(\"java/lang/Object\");\n } else {\n // If srcType is any other type, merge(srcType, dstType) = TOP.\n mergedType = TOP;\n }\n } else if (dstType == NULL) {\n // If dstType is the NULL type, merge(srcType, dstType) = srcType, or TOP if srcType is not a\n // an array type or a reference type.\n mergedType = (srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND ? srcType : TOP;\n } else {\n // If dstType is any other type, merge(srcType, dstType) = TOP whatever srcType.\n mergedType = TOP;\n }\n if (mergedType != dstType) {\n dstTypes[dstIndex] = mergedType;\n return true;\n }\n return false;\n }\n // -----------------------------------------------------------------------------------------------\n // Frame output methods, to generate StackMapFrame attributes\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Makes the given {@link MethodWriter} visit the input frame of this {@link Frame}. The visit is\n * done with the {@link MethodWriter#visitFrameStart}, {@link MethodWriter#visitAbstractType} and\n * {@link MethodWriter#visitFrameEnd} methods.\n *\n * @param methodWriter the {@link MethodWriter} that should visit the input frame of this {@link\n * Frame}.\n */\n final void accept(final MethodWriter methodWriter) {\n // Compute the number of locals, ignoring TOP types that are just after a LONG or a DOUBLE, and\n // all trailing TOP types.\n int[] localTypes = inputLocals;\n int numLocal = 0;\n int numTrailingTop = 0;\n int i = 0;\n while (i < localTypes.length) {\n int localType = localTypes[i];\n i += (localType == LONG || localType == DOUBLE) ? 2 : 1;\n if (localType == TOP) {\n numTrailingTop++;\n } else {\n numLocal += numTrailingTop + 1;\n numTrailingTop = 0;\n }\n }\n // Compute the stack size, ignoring TOP types that are just after a LONG or a DOUBLE.\n int[] stackTypes = inputStack;\n int numStack = 0;\n i = 0;\n while (i < stackTypes.length) {\n int stackType = stackTypes[i];\n i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1;\n numStack++;\n }\n // Visit the frame and its content.\n int frameIndex = methodWriter.visitFrameStart(owner.bytecodeOffset, numLocal, numStack);\n i = 0;\n while (numLocal-- > 0) {\n int localType = localTypes[i];\n i += (localType == LONG || localType == DOUBLE) ? 2 : 1;\n methodWriter.visitAbstractType(frameIndex++, localType);\n }\n i = 0;\n while (numStack-- > 0) {\n int stackType = stackTypes[i];\n i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1;\n methodWriter.visitAbstractType(frameIndex++, stackType);\n }\n methodWriter.visitFrameEnd();\n }\n\n /**\n * Put the given abstract type in the given ByteVector, using the JVMS verification_type_info\n * format used in StackMapTable attributes.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param abstractType an abstract type, restricted to {@link Frame#CONSTANT_KIND}, {@link\n * Frame#REFERENCE_KIND} or {@link Frame#UNINITIALIZED_KIND} types.\n * @param output where the abstract type must be put.\n * @see JVMS\n * 4.7.4\n */\n static void putAbstractType(final SymbolTable symbolTable, final int abstractType, final ByteVector output) {\n int arrayDimensions = (abstractType & Frame.DIM_MASK) >> DIM_SHIFT;\n if (arrayDimensions == 0) {\n int typeValue = abstractType & VALUE_MASK;\n switch (abstractType & KIND_MASK) {\n case CONSTANT_KIND:\n output.putByte(typeValue);\n break;\n case REFERENCE_KIND:\n output.putByte(ITEM_OBJECT).putShort(symbolTable.addConstantClass(symbolTable.getType(typeValue).value).index);\n break;\n case UNINITIALIZED_KIND:\n output.putByte(ITEM_UNINITIALIZED).putShort((int) symbolTable.getType(typeValue).data);\n break;\n default:\n throw new AssertionError();\n }\n } else {\n // Case of an array type, we need to build its descriptor first.\n StringBuilder typeDescriptor = new StringBuilder();\n while (arrayDimensions-- > 0) {\n typeDescriptor.append('[');\n }\n if ((abstractType & KIND_MASK) == REFERENCE_KIND) {\n typeDescriptor.append('L').append(symbolTable.getType(abstractType & VALUE_MASK).value).append(';');\n } else {\n switch (abstractType & VALUE_MASK) {\n case Frame.ITEM_ASM_BOOLEAN:\n typeDescriptor.append('Z');\n break;\n case Frame.ITEM_ASM_BYTE:\n typeDescriptor.append('B');\n break;\n case Frame.ITEM_ASM_CHAR:\n typeDescriptor.append('C');\n break;\n case Frame.ITEM_ASM_SHORT:\n typeDescriptor.append('S');\n break;\n case Frame.ITEM_INTEGER:\n typeDescriptor.append('I');\n break;\n case Frame.ITEM_FLOAT:\n typeDescriptor.append('F');\n break;\n case Frame.ITEM_LONG:\n typeDescriptor.append('J');\n break;\n case Frame.ITEM_DOUBLE:\n typeDescriptor.append('D');\n break;\n default:\n throw new AssertionError();\n }\n }\n output.putByte(ITEM_OBJECT).putShort(symbolTable.addConstantClass(typeDescriptor.toString()).index);\n }\n }\n}\n", "file_name": "Frame.java", "human_label": "Add abstractType to the initializations variable.", "level": "class_runnable", "lineno": "563", "name": "addInitializedType", "oracle_context": "{ \"apis\" : \"[max, arraycopy]\", \"classes\" : \"[int[], initializations]\", \"vars\" : \"[length, initializations, initializationCount]\" }", "package": "net.hasor.utils.asm", "project": "hasor-master" }, { "_id": "6367670a1a6d9265ec0179dc", "all_context": "{ \"class_level\" : \"int COMPUTE_NOTHING;\\nint COMPUTE_MAX_STACK_AND_LOCAL;\\nint COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES;\\nint COMPUTE_INSERTED_FRAMES;\\nint COMPUTE_ALL_FRAMES;\\nint NA;\\nint[] STACK_SIZE_DELTA;\\nSymbolTable symbolTable;\\nint accessFlags;\\nint nameIndex;\\nString name;\\nint descriptorIndex;\\nString descriptor;\\nint maxStack;\\nint maxLocals;\\nByteVector code;\\nHandler firstHandler;\\nHandler lastHandler;\\nint lineNumberTableLength;\\nByteVector lineNumberTable;\\nint localVariableTableLength;\\nByteVector localVariableTable;\\nint localVariableTypeTableLength;\\nByteVector localVariableTypeTable;\\nint stackMapTableNumberOfEntries;\\nByteVector stackMapTableEntries;\\nAnnotationWriter lastCodeRuntimeVisibleTypeAnnotation;\\nAnnotationWriter lastCodeRuntimeInvisibleTypeAnnotation;\\nAttribute firstCodeAttribute;\\nint numberOfExceptions;\\nint[] exceptionIndexTable;\\nint signatureIndex;\\nAnnotationWriter lastRuntimeVisibleAnnotation;\\nAnnotationWriter lastRuntimeInvisibleAnnotation;\\nint visibleAnnotableParameterCount;\\nAnnotationWriter[] lastRuntimeVisibleParameterAnnotations;\\nint invisibleAnnotableParameterCount;\\nAnnotationWriter[] lastRuntimeInvisibleParameterAnnotations;\\nAnnotationWriter lastRuntimeVisibleTypeAnnotation;\\nAnnotationWriter lastRuntimeInvisibleTypeAnnotation;\\nByteVector defaultValue;\\nint parametersCount;\\nByteVector parameters;\\nAttribute firstAttribute;\\nint compute;\\nLabel firstBasicBlock;\\nLabel lastBasicBlock;\\nLabel currentBasicBlock;\\nint relativeStackSize;\\nint maxRelativeStackSize;\\nint currentLocals;\\nint previousFrameOffset;\\nint[] previousFrame;\\nint[] currentFrame;\\nboolean hasSubroutines;\\nboolean hasAsmInstructions;\\nint lastBytecodeOffset;\\nint sourceOffset;\\nint sourceLength;\\nMethodWriter(SymbolTable symbolTable,int access,String name,String descriptor,String signature,String[] exceptions,int compute);\\nhasFrames();\\nhasAsmInstructions();\\nvisitParameter(String name,int access);\\nvisitAnnotationDefault();\\nvisitAnnotation(String descriptor,boolean visible);\\nvisitTypeAnnotation(int typeRef,TypePath typePath,String descriptor,boolean visible);\\nvisitAnnotableParameterCount(int parameterCount,boolean visible);\\nvisitParameterAnnotation(int parameter,String annotationDescriptor,boolean visible);\\nvisitAttribute(Attribute attribute);\\nvisitCode();\\nvisitFrame(int type,int numLocal,Object[] local,int numStack,Object[] stack);\\nvisitInsn(int opcode);\\nvisitIntInsn(int opcode,int operand);\\nvisitVarInsn(int opcode,int var);\\nvisitTypeInsn(int opcode,String type);\\nvisitFieldInsn(int opcode,String owner,String name,String descriptor);\\nvisitMethodInsn(int opcode,String owner,String name,String descriptor,boolean isInterface);\\nvisitInvokeDynamicInsn(String name,String descriptor,Handle bootstrapMethodHandle,Object bootstrapMethodArguments);\\nvisitJumpInsn(int opcode,Label label);\\nvisitLabel(Label label);\\nvisitLdcInsn(Object value);\\nvisitIincInsn(int var,int increment);\\nvisitTableSwitchInsn(int min,int max,Label dflt,Label labels);\\nvisitLookupSwitchInsn(Label dflt,int[] keys,Label[] labels);\\nvisitSwitchInsn(Label dflt,Label[] labels);\\nvisitMultiANewArrayInsn(String descriptor,int numDimensions);\\nvisitInsnAnnotation(int typeRef,TypePath typePath,String descriptor,boolean visible);\\nvisitTryCatchBlock(Label start,Label end,Label handler,String type);\\nvisitTryCatchAnnotation(int typeRef,TypePath typePath,String descriptor,boolean visible);\\nvisitLocalVariable(String name,String descriptor,String signature,Label start,Label end,int index);\\nvisitLocalVariableAnnotation(int typeRef,TypePath typePath,Label[] start,Label[] end,int[] index,String descriptor,boolean visible);\\nvisitLineNumber(int line,Label start);\\nvisitMaxs(int maxStack,int maxLocals);\\ncomputeMaxStackAndLocal();\\nvisitEnd();\\naddSuccessorToCurrentBasicBlock(int info,Label successor);\\nendCurrentBasicBlockWithNoSuccessor();\\nvisitFrameStart(int offset,int numLocal,int numStack);\\nvisitAbstractType(int frameIndex,int abstractType);\\nvisitFrameEnd();\\nputFrame();\\nputAbstractTypes(int start,int end);\\nputFrameType(Object type);\\ncanCopyMethodAttributes(ClassReader source,boolean hasSyntheticAttribute,boolean hasDeprecatedAttribute,int descriptorIndex,int signatureIndex,int exceptionsOffset);\\nsetMethodAttributesSource(int methodInfoOffset,int methodInfoLength);\\ncomputeMethodInfoSize();\\nputMethodInfo(ByteVector output);\\ncollectAttributePrototypes(Set attributePrototypes);\\ncomputeAllFrames();\\n\", \"repo_level\" : \"\" }", "class_name": "MethodWriter", "code": "private void putAbstractTypes(final int start,final int end){\n for (int i=start; i < end; ++i) {\n Frame.putAbstractType(symbolTable,currentFrame[i],stackMapTableEntries);\n }\n}\n", "docstring": "/** \n * Puts some abstract types of {@link #currentFrame} in {@link #stackMapTableEntries} , using theJVMS verification_type_info format used in StackMapTable attributes.\n * @param start index of the first type in {@link #currentFrame} to write.\n * @param end index of last type in {@link #currentFrame} to write (exclusive).\n */\n", "end_lineno": "1743", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage net.hasor.utils.asm;\n/**\n * A {@link MethodVisitor} that generates a corresponding 'method_info' structure, as defined in the\n * Java Virtual Machine Specification (JVMS).\n *\n * @see JVMS\n * 4.6\n * @author Eric Bruneton\n * @author Eugene Kuleshov\n */\nfinal class MethodWriter extends MethodVisitor {\n /** Indicates that nothing must be computed. */\n static final int COMPUTE_NOTHING = 0;\n /**\n * Indicates that the maximum stack size and the maximum number of local variables must be\n * computed, from scratch.\n */\n static final int COMPUTE_MAX_STACK_AND_LOCAL = 1;\n /**\n * Indicates that the maximum stack size and the maximum number of local variables must be\n * computed, from the existing stack map frames. This can be done more efficiently than with the\n * control flow graph algorithm used for {@link #COMPUTE_MAX_STACK_AND_LOCAL}, by using a linear\n * scan of the bytecode instructions.\n */\n static final int COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES = 2;\n /**\n * Indicates that the stack map frames of type F_INSERT must be computed. The other frames are not\n * computed. They should all be of type F_NEW and should be sufficient to compute the content of\n * the F_INSERT frames, together with the bytecode instructions between a F_NEW and a F_INSERT\n * frame - and without any knowledge of the type hierarchy (by definition of F_INSERT).\n */\n static final int COMPUTE_INSERTED_FRAMES = 3;\n /**\n * Indicates that all the stack map frames must be computed. In this case the maximum stack size\n * and the maximum number of local variables is also computed.\n */\n static final int COMPUTE_ALL_FRAMES = 4;\n /** Indicates that {@link #STACK_SIZE_DELTA} is not applicable (not constant or never used). */\n private static final int NA = 0;\n /**\n * The stack size variation corresponding to each JVM opcode. The stack size variation for opcode\n * 'o' is given by the array element at index 'o'.\n *\n * @see JVMS 6\n */\n private static final int[] STACK_SIZE_DELTA = { 0, // nop = 0 (0x0)\n 1, // aconst_null = 1 (0x1)\n 1, // iconst_m1 = 2 (0x2)\n 1, // iconst_0 = 3 (0x3)\n 1, // iconst_1 = 4 (0x4)\n 1, // iconst_2 = 5 (0x5)\n 1, // iconst_3 = 6 (0x6)\n 1, // iconst_4 = 7 (0x7)\n 1, // iconst_5 = 8 (0x8)\n 2, // lconst_0 = 9 (0x9)\n 2, // lconst_1 = 10 (0xa)\n 1, // fconst_0 = 11 (0xb)\n 1, // fconst_1 = 12 (0xc)\n 1, // fconst_2 = 13 (0xd)\n 2, // dconst_0 = 14 (0xe)\n 2, // dconst_1 = 15 (0xf)\n 1, // bipush = 16 (0x10)\n 1, // sipush = 17 (0x11)\n 1, // ldc = 18 (0x12)\n NA, // ldc_w = 19 (0x13)\n NA, // ldc2_w = 20 (0x14)\n 1, // iload = 21 (0x15)\n 2, // lload = 22 (0x16)\n 1, // fload = 23 (0x17)\n 2, // dload = 24 (0x18)\n 1, // aload = 25 (0x19)\n NA, // iload_0 = 26 (0x1a)\n NA, // iload_1 = 27 (0x1b)\n NA, // iload_2 = 28 (0x1c)\n NA, // iload_3 = 29 (0x1d)\n NA, // lload_0 = 30 (0x1e)\n NA, // lload_1 = 31 (0x1f)\n NA, // lload_2 = 32 (0x20)\n NA, // lload_3 = 33 (0x21)\n NA, // fload_0 = 34 (0x22)\n NA, // fload_1 = 35 (0x23)\n NA, // fload_2 = 36 (0x24)\n NA, // fload_3 = 37 (0x25)\n NA, // dload_0 = 38 (0x26)\n NA, // dload_1 = 39 (0x27)\n NA, // dload_2 = 40 (0x28)\n NA, // dload_3 = 41 (0x29)\n NA, // aload_0 = 42 (0x2a)\n NA, // aload_1 = 43 (0x2b)\n NA, // aload_2 = 44 (0x2c)\n NA, // aload_3 = 45 (0x2d)\n -1, // iaload = 46 (0x2e)\n 0, // laload = 47 (0x2f)\n -1, // faload = 48 (0x30)\n 0, // daload = 49 (0x31)\n -1, // aaload = 50 (0x32)\n -1, // baload = 51 (0x33)\n -1, // caload = 52 (0x34)\n -1, // saload = 53 (0x35)\n -1, // istore = 54 (0x36)\n -2, // lstore = 55 (0x37)\n -1, // fstore = 56 (0x38)\n -2, // dstore = 57 (0x39)\n -1, // astore = 58 (0x3a)\n NA, // istore_0 = 59 (0x3b)\n NA, // istore_1 = 60 (0x3c)\n NA, // istore_2 = 61 (0x3d)\n NA, // istore_3 = 62 (0x3e)\n NA, // lstore_0 = 63 (0x3f)\n NA, // lstore_1 = 64 (0x40)\n NA, // lstore_2 = 65 (0x41)\n NA, // lstore_3 = 66 (0x42)\n NA, // fstore_0 = 67 (0x43)\n NA, // fstore_1 = 68 (0x44)\n NA, // fstore_2 = 69 (0x45)\n NA, // fstore_3 = 70 (0x46)\n NA, // dstore_0 = 71 (0x47)\n NA, // dstore_1 = 72 (0x48)\n NA, // dstore_2 = 73 (0x49)\n NA, // dstore_3 = 74 (0x4a)\n NA, // astore_0 = 75 (0x4b)\n NA, // astore_1 = 76 (0x4c)\n NA, // astore_2 = 77 (0x4d)\n NA, // astore_3 = 78 (0x4e)\n -3, // iastore = 79 (0x4f)\n -4, // lastore = 80 (0x50)\n -3, // fastore = 81 (0x51)\n -4, // dastore = 82 (0x52)\n -3, // aastore = 83 (0x53)\n -3, // bastore = 84 (0x54)\n -3, // castore = 85 (0x55)\n -3, // sastore = 86 (0x56)\n -1, // pop = 87 (0x57)\n -2, // pop2 = 88 (0x58)\n 1, // dup = 89 (0x59)\n 1, // dup_x1 = 90 (0x5a)\n 1, // dup_x2 = 91 (0x5b)\n 2, // dup2 = 92 (0x5c)\n 2, // dup2_x1 = 93 (0x5d)\n 2, // dup2_x2 = 94 (0x5e)\n 0, // swap = 95 (0x5f)\n -1, // iadd = 96 (0x60)\n -2, // ladd = 97 (0x61)\n -1, // fadd = 98 (0x62)\n -2, // dadd = 99 (0x63)\n -1, // isub = 100 (0x64)\n -2, // lsub = 101 (0x65)\n -1, // fsub = 102 (0x66)\n -2, // dsub = 103 (0x67)\n -1, // imul = 104 (0x68)\n -2, // lmul = 105 (0x69)\n -1, // fmul = 106 (0x6a)\n -2, // dmul = 107 (0x6b)\n -1, // idiv = 108 (0x6c)\n -2, // ldiv = 109 (0x6d)\n -1, // fdiv = 110 (0x6e)\n -2, // ddiv = 111 (0x6f)\n -1, // irem = 112 (0x70)\n -2, // lrem = 113 (0x71)\n -1, // frem = 114 (0x72)\n -2, // drem = 115 (0x73)\n 0, // ineg = 116 (0x74)\n 0, // lneg = 117 (0x75)\n 0, // fneg = 118 (0x76)\n 0, // dneg = 119 (0x77)\n -1, // ishl = 120 (0x78)\n -1, // lshl = 121 (0x79)\n -1, // ishr = 122 (0x7a)\n -1, // lshr = 123 (0x7b)\n -1, // iushr = 124 (0x7c)\n -1, // lushr = 125 (0x7d)\n -1, // iand = 126 (0x7e)\n -2, // land = 127 (0x7f)\n -1, // ior = 128 (0x80)\n -2, // lor = 129 (0x81)\n -1, // ixor = 130 (0x82)\n -2, // lxor = 131 (0x83)\n 0, // iinc = 132 (0x84)\n 1, // i2l = 133 (0x85)\n 0, // i2f = 134 (0x86)\n 1, // i2d = 135 (0x87)\n -1, // l2i = 136 (0x88)\n -1, // l2f = 137 (0x89)\n 0, // l2d = 138 (0x8a)\n 0, // f2i = 139 (0x8b)\n 1, // f2l = 140 (0x8c)\n 1, // f2d = 141 (0x8d)\n -1, // d2i = 142 (0x8e)\n 0, // d2l = 143 (0x8f)\n -1, // d2f = 144 (0x90)\n 0, // i2b = 145 (0x91)\n 0, // i2c = 146 (0x92)\n 0, // i2s = 147 (0x93)\n -3, // lcmp = 148 (0x94)\n -1, // fcmpl = 149 (0x95)\n -1, // fcmpg = 150 (0x96)\n -3, // dcmpl = 151 (0x97)\n -3, // dcmpg = 152 (0x98)\n -1, // ifeq = 153 (0x99)\n -1, // ifne = 154 (0x9a)\n -1, // iflt = 155 (0x9b)\n -1, // ifge = 156 (0x9c)\n -1, // ifgt = 157 (0x9d)\n -1, // ifle = 158 (0x9e)\n -2, // if_icmpeq = 159 (0x9f)\n -2, // if_icmpne = 160 (0xa0)\n -2, // if_icmplt = 161 (0xa1)\n -2, // if_icmpge = 162 (0xa2)\n -2, // if_icmpgt = 163 (0xa3)\n -2, // if_icmple = 164 (0xa4)\n -2, // if_acmpeq = 165 (0xa5)\n -2, // if_acmpne = 166 (0xa6)\n 0, // goto = 167 (0xa7)\n 1, // jsr = 168 (0xa8)\n 0, // ret = 169 (0xa9)\n -1, // tableswitch = 170 (0xaa)\n -1, // lookupswitch = 171 (0xab)\n -1, // ireturn = 172 (0xac)\n -2, // lreturn = 173 (0xad)\n -1, // freturn = 174 (0xae)\n -2, // dreturn = 175 (0xaf)\n -1, // areturn = 176 (0xb0)\n 0, // return = 177 (0xb1)\n NA, // getstatic = 178 (0xb2)\n NA, // putstatic = 179 (0xb3)\n NA, // getfield = 180 (0xb4)\n NA, // putfield = 181 (0xb5)\n NA, // invokevirtual = 182 (0xb6)\n NA, // invokespecial = 183 (0xb7)\n NA, // invokestatic = 184 (0xb8)\n NA, // invokeinterface = 185 (0xb9)\n NA, // invokedynamic = 186 (0xba)\n 1, // new = 187 (0xbb)\n 0, // newarray = 188 (0xbc)\n 0, // anewarray = 189 (0xbd)\n 0, // arraylength = 190 (0xbe)\n NA, // athrow = 191 (0xbf)\n 0, // checkcast = 192 (0xc0)\n 0, // instanceof = 193 (0xc1)\n -1, // monitorenter = 194 (0xc2)\n -1, // monitorexit = 195 (0xc3)\n NA, // wide = 196 (0xc4)\n NA, // multianewarray = 197 (0xc5)\n -1, // ifnull = 198 (0xc6)\n -1, // ifnonnull = 199 (0xc7)\n NA, // goto_w = 200 (0xc8)\n NA // jsr_w = 201 (0xc9)\n };\n /** Where the constants used in this MethodWriter must be stored. */\n private final SymbolTable symbolTable;\n // Note: fields are ordered as in the method_info structure, and those related to attributes are\n // ordered as in Section 4.7 of the JVMS.\n /**\n * The access_flags field of the method_info JVMS structure. This field can contain ASM specific\n * access flags, such as {@link Opcodes#ACC_DEPRECATED}, which are removed when generating the\n * ClassFile structure.\n */\n private final int accessFlags;\n /** The name_index field of the method_info JVMS structure. */\n private final int nameIndex;\n /** The name of this method. */\n private final String name;\n /** The descriptor_index field of the method_info JVMS structure. */\n private final int descriptorIndex;\n /** The descriptor of this method. */\n private final String descriptor;\n // Code attribute fields and sub attributes:\n /** The max_stack field of the Code attribute. */\n private int maxStack;\n /** The max_locals field of the Code attribute. */\n private int maxLocals;\n /** The 'code' field of the Code attribute. */\n private final ByteVector code = new ByteVector();\n /**\n * The first element in the exception handler list (used to generate the exception_table of the\n * Code attribute). The next ones can be accessed with the {@link Handler#nextHandler} field. May\n * be {@literal null}.\n */\n private Handler firstHandler;\n /**\n * The last element in the exception handler list (used to generate the exception_table of the\n * Code attribute). The next ones can be accessed with the {@link Handler#nextHandler} field. May\n * be {@literal null}.\n */\n private Handler lastHandler;\n /** The line_number_table_length field of the LineNumberTable code attribute. */\n private int lineNumberTableLength;\n /** The line_number_table array of the LineNumberTable code attribute, or {@literal null}. */\n private ByteVector lineNumberTable;\n /** The local_variable_table_length field of the LocalVariableTable code attribute. */\n private int localVariableTableLength;\n /**\n * The local_variable_table array of the LocalVariableTable code attribute, or {@literal null}.\n */\n private ByteVector localVariableTable;\n /** The local_variable_type_table_length field of the LocalVariableTypeTable code attribute. */\n private int localVariableTypeTableLength;\n /**\n * The local_variable_type_table array of the LocalVariableTypeTable code attribute, or {@literal\n * null}.\n */\n private ByteVector localVariableTypeTable;\n /** The number_of_entries field of the StackMapTable code attribute. */\n private int stackMapTableNumberOfEntries;\n /** The 'entries' array of the StackMapTable code attribute. */\n private ByteVector stackMapTableEntries;\n /**\n * The last runtime visible type annotation of the Code attribute. The previous ones can be\n * accessed with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.\n */\n private AnnotationWriter lastCodeRuntimeVisibleTypeAnnotation;\n /**\n * The last runtime invisible type annotation of the Code attribute. The previous ones can be\n * accessed with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.\n */\n private AnnotationWriter lastCodeRuntimeInvisibleTypeAnnotation;\n /**\n * The first non standard attribute of the Code attribute. The next ones can be accessed with the\n * {@link Attribute#nextAttribute} field. May be {@literal null}.\n *\n *

WARNING: this list stores the attributes in the reverse order of their visit.\n * firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link\n * #putMethodInfo} method writes the attributes in the order defined by this list, i.e. in the\n * reverse order specified by the user.\n */\n private Attribute firstCodeAttribute;\n // Other method_info attributes:\n /** The number_of_exceptions field of the Exceptions attribute. */\n private final int numberOfExceptions;\n /** The exception_index_table array of the Exceptions attribute, or {@literal null}. */\n private final int[] exceptionIndexTable;\n /** The signature_index field of the Signature attribute. */\n private final int signatureIndex;\n /**\n * The last runtime visible annotation of this method. The previous ones can be accessed with the\n * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.\n */\n private AnnotationWriter lastRuntimeVisibleAnnotation;\n /**\n * The last runtime invisible annotation of this method. The previous ones can be accessed with\n * the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.\n */\n private AnnotationWriter lastRuntimeInvisibleAnnotation;\n /** The number of method parameters that can have runtime visible annotations, or 0. */\n private int visibleAnnotableParameterCount;\n /**\n * The runtime visible parameter annotations of this method. Each array element contains the last\n * annotation of a parameter (which can be {@literal null} - the previous ones can be accessed\n * with the {@link AnnotationWriter#previousAnnotation} field). May be {@literal null}.\n */\n private AnnotationWriter[] lastRuntimeVisibleParameterAnnotations;\n /** The number of method parameters that can have runtime visible annotations, or 0. */\n private int invisibleAnnotableParameterCount;\n /**\n * The runtime invisible parameter annotations of this method. Each array element contains the\n * last annotation of a parameter (which can be {@literal null} - the previous ones can be\n * accessed with the {@link AnnotationWriter#previousAnnotation} field). May be {@literal null}.\n */\n private AnnotationWriter[] lastRuntimeInvisibleParameterAnnotations;\n /**\n * The last runtime visible type annotation of this method. The previous ones can be accessed with\n * the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.\n */\n private AnnotationWriter lastRuntimeVisibleTypeAnnotation;\n /**\n * The last runtime invisible type annotation of this method. The previous ones can be accessed\n * with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.\n */\n private AnnotationWriter lastRuntimeInvisibleTypeAnnotation;\n /** The default_value field of the AnnotationDefault attribute, or {@literal null}. */\n private ByteVector defaultValue;\n /** The parameters_count field of the MethodParameters attribute. */\n private int parametersCount;\n /** The 'parameters' array of the MethodParameters attribute, or {@literal null}. */\n private ByteVector parameters;\n /**\n * The first non standard attribute of this method. The next ones can be accessed with the {@link\n * Attribute#nextAttribute} field. May be {@literal null}.\n *\n *

WARNING: this list stores the attributes in the reverse order of their visit.\n * firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link\n * #putMethodInfo} method writes the attributes in the order defined by this list, i.e. in the\n * reverse order specified by the user.\n */\n private Attribute firstAttribute;\n // -----------------------------------------------------------------------------------------------\n // Fields used to compute the maximum stack size and number of locals, and the stack map frames\n // -----------------------------------------------------------------------------------------------\n /**\n * Indicates what must be computed. Must be one of {@link #COMPUTE_ALL_FRAMES}, {@link\n * #COMPUTE_INSERTED_FRAMES}, {@link #COMPUTE_MAX_STACK_AND_LOCAL} or {@link #COMPUTE_NOTHING}.\n */\n private final int compute;\n /**\n * The first basic block of the method. The next ones (in bytecode offset order) can be accessed\n * with the {@link Label#nextBasicBlock} field.\n */\n private Label firstBasicBlock;\n /**\n * The last basic block of the method (in bytecode offset order). This field is updated each time\n * a basic block is encountered, and is used to append it at the end of the basic block list.\n */\n private Label lastBasicBlock;\n /**\n * The current basic block, i.e. the basic block of the last visited instruction. When {@link\n * #compute} is equal to {@link #COMPUTE_MAX_STACK_AND_LOCAL} or {@link #COMPUTE_ALL_FRAMES}, this\n * field is {@literal null} for unreachable code. When {@link #compute} is equal to {@link\n * #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES} or {@link #COMPUTE_INSERTED_FRAMES}, this field stays\n * unchanged throughout the whole method (i.e. the whole code is seen as a single basic block;\n * indeed, the existing frames are sufficient by hypothesis to compute any intermediate frame -\n * and the maximum stack size as well - without using any control flow graph).\n */\n private Label currentBasicBlock;\n /**\n * The relative stack size after the last visited instruction. This size is relative to the\n * beginning of {@link #currentBasicBlock}, i.e. the true stack size after the last visited\n * instruction is equal to the {@link Label#inputStackSize} of the current basic block plus {@link\n * #relativeStackSize}. When {@link #compute} is equal to {@link\n * #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link #currentBasicBlock} is always the start of\n * the method, so this relative size is also equal to the absolute stack size after the last\n * visited instruction.\n */\n private int relativeStackSize;\n /**\n * The maximum relative stack size after the last visited instruction. This size is relative to\n * the beginning of {@link #currentBasicBlock}, i.e. the true maximum stack size after the last\n * visited instruction is equal to the {@link Label#inputStackSize} of the current basic block\n * plus {@link #maxRelativeStackSize}.When {@link #compute} is equal to {@link\n * #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link #currentBasicBlock} is always the start of\n * the method, so this relative size is also equal to the absolute maximum stack size after the\n * last visited instruction.\n */\n private int maxRelativeStackSize;\n /** The number of local variables in the last visited stack map frame. */\n private int currentLocals;\n /** The bytecode offset of the last frame that was written in {@link #stackMapTableEntries}. */\n private int previousFrameOffset;\n /**\n * The last frame that was written in {@link #stackMapTableEntries}. This field has the same\n * format as {@link #currentFrame}.\n */\n private int[] previousFrame;\n /**\n * The current stack map frame. The first element contains the bytecode offset of the instruction\n * to which the frame corresponds, the second element is the number of locals and the third one is\n * the number of stack elements. The local variables start at index 3 and are followed by the\n * operand stack elements. In summary frame[0] = offset, frame[1] = numLocal, frame[2] = numStack.\n * Local variables and operand stack entries contain abstract types, as defined in {@link Frame},\n * but restricted to {@link Frame#CONSTANT_KIND}, {@link Frame#REFERENCE_KIND} or {@link\n * Frame#UNINITIALIZED_KIND} abstract types. Long and double types use only one array entry.\n */\n private int[] currentFrame;\n /** Whether this method contains subroutines. */\n private boolean hasSubroutines;\n // -----------------------------------------------------------------------------------------------\n // Other miscellaneous status fields\n // -----------------------------------------------------------------------------------------------\n /** Whether the bytecode of this method contains ASM specific instructions. */\n private boolean hasAsmInstructions;\n /**\n * The start offset of the last visited instruction. Used to set the offset field of type\n * annotations of type 'offset_target' (see JVMS\n * 4.7.20.1).\n */\n private int lastBytecodeOffset;\n /**\n * The offset in bytes in {@link SymbolTable#getSource} from which the method_info for this method\n * (excluding its first 6 bytes) must be copied, or 0.\n */\n private int sourceOffset;\n /**\n * The length in bytes in {@link SymbolTable#getSource} which must be copied to get the\n * method_info for this method (excluding its first 6 bytes for access_flags, name_index and\n * descriptor_index).\n */\n private int sourceLength;\n // -----------------------------------------------------------------------------------------------\n // Constructor and accessors\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Constructs a new {@link MethodWriter}.\n *\n * @param symbolTable where the constants used in this AnnotationWriter must be stored.\n * @param access the method's access flags (see {@link Opcodes}).\n * @param name the method's name.\n * @param descriptor the method's descriptor (see {@link Type}).\n * @param signature the method's signature. May be {@literal null}.\n * @param exceptions the internal names of the method's exceptions. May be {@literal null}.\n * @param compute indicates what must be computed (see #compute).\n */\n MethodWriter(final SymbolTable symbolTable, final int access, final String name, final String descriptor, final String signature, final String[] exceptions, final int compute) {\n super(/* latest api = */ Opcodes.ASM7);\n this.symbolTable = symbolTable;\n this.accessFlags = \"\".equals(name) ? access | Constants.ACC_CONSTRUCTOR : access;\n this.nameIndex = symbolTable.addConstantUtf8(name);\n this.name = name;\n this.descriptorIndex = symbolTable.addConstantUtf8(descriptor);\n this.descriptor = descriptor;\n this.signatureIndex = signature == null ? 0 : symbolTable.addConstantUtf8(signature);\n if (exceptions != null && exceptions.length > 0) {\n numberOfExceptions = exceptions.length;\n this.exceptionIndexTable = new int[numberOfExceptions];\n for (int i = 0; i < numberOfExceptions; ++i) {\n this.exceptionIndexTable[i] = symbolTable.addConstantClass(exceptions[i]).index;\n }\n } else {\n numberOfExceptions = 0;\n this.exceptionIndexTable = null;\n }\n this.compute = compute;\n if (compute != COMPUTE_NOTHING) {\n // Update maxLocals and currentLocals.\n int argumentsSize = Type.getArgumentsAndReturnSizes(descriptor) >> 2;\n if ((access & Opcodes.ACC_STATIC) != 0) {\n --argumentsSize;\n }\n maxLocals = argumentsSize;\n currentLocals = argumentsSize;\n // Create and visit the label for the first basic block.\n firstBasicBlock = new Label();\n visitLabel(firstBasicBlock);\n }\n }\n\n boolean hasFrames() {\n return stackMapTableNumberOfEntries > 0;\n }\n\n boolean hasAsmInstructions() {\n return hasAsmInstructions;\n }\n // -----------------------------------------------------------------------------------------------\n // Implementation of the MethodVisitor abstract class\n // -----------------------------------------------------------------------------------------------\n\n @Override\n public void visitParameter(final String name, final int access) {\n if (parameters == null) {\n parameters = new ByteVector();\n }\n ++parametersCount;\n parameters.putShort((name == null) ? 0 : symbolTable.addConstantUtf8(name)).putShort(access);\n }\n\n @Override\n public AnnotationVisitor visitAnnotationDefault() {\n defaultValue = new ByteVector();\n return new AnnotationWriter(symbolTable, /* useNamedValues = */ false, defaultValue, null);\n }\n\n @Override\n public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {\n if (visible) {\n return lastRuntimeVisibleAnnotation = AnnotationWriter.create(symbolTable, descriptor, lastRuntimeVisibleAnnotation);\n } else {\n return lastRuntimeInvisibleAnnotation = AnnotationWriter.create(symbolTable, descriptor, lastRuntimeInvisibleAnnotation);\n }\n }\n\n @Override\n public AnnotationVisitor visitTypeAnnotation(final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {\n if (visible) {\n return lastRuntimeVisibleTypeAnnotation = AnnotationWriter.create(symbolTable, typeRef, typePath, descriptor, lastRuntimeVisibleTypeAnnotation);\n } else {\n return lastRuntimeInvisibleTypeAnnotation = AnnotationWriter.create(symbolTable, typeRef, typePath, descriptor, lastRuntimeInvisibleTypeAnnotation);\n }\n }\n\n @Override\n public void visitAnnotableParameterCount(final int parameterCount, final boolean visible) {\n if (visible) {\n visibleAnnotableParameterCount = parameterCount;\n } else {\n invisibleAnnotableParameterCount = parameterCount;\n }\n }\n\n @Override\n public AnnotationVisitor visitParameterAnnotation(final int parameter, final String annotationDescriptor, final boolean visible) {\n if (visible) {\n if (lastRuntimeVisibleParameterAnnotations == null) {\n lastRuntimeVisibleParameterAnnotations = new AnnotationWriter[Type.getArgumentTypes(descriptor).length];\n }\n return lastRuntimeVisibleParameterAnnotations[parameter] = AnnotationWriter.create(symbolTable, annotationDescriptor, lastRuntimeVisibleParameterAnnotations[parameter]);\n } else {\n if (lastRuntimeInvisibleParameterAnnotations == null) {\n lastRuntimeInvisibleParameterAnnotations = new AnnotationWriter[Type.getArgumentTypes(descriptor).length];\n }\n return lastRuntimeInvisibleParameterAnnotations[parameter] = AnnotationWriter.create(symbolTable, annotationDescriptor, lastRuntimeInvisibleParameterAnnotations[parameter]);\n }\n }\n\n @Override\n public void visitAttribute(final Attribute attribute) {\n // Store the attributes in the reverse order of their visit by this method.\n if (attribute.isCodeAttribute()) {\n attribute.nextAttribute = firstCodeAttribute;\n firstCodeAttribute = attribute;\n } else {\n attribute.nextAttribute = firstAttribute;\n firstAttribute = attribute;\n }\n }\n\n @Override\n public void visitCode() {\n // Nothing to do.\n }\n\n @Override\n public void visitFrame(final int type, final int numLocal, final Object[] local, final int numStack, final Object[] stack) {\n if (compute == COMPUTE_ALL_FRAMES) {\n return;\n }\n if (compute == COMPUTE_INSERTED_FRAMES) {\n if (currentBasicBlock.frame == null) {\n // This should happen only once, for the implicit first frame (which is explicitly visited\n // in ClassReader if the EXPAND_ASM_INSNS option is used - and COMPUTE_INSERTED_FRAMES\n // can't be set if EXPAND_ASM_INSNS is not used).\n currentBasicBlock.frame = new CurrentFrame(currentBasicBlock);\n currentBasicBlock.frame.setInputFrameFromDescriptor(symbolTable, accessFlags, descriptor, numLocal);\n currentBasicBlock.frame.accept(this);\n } else {\n if (type == Opcodes.F_NEW) {\n currentBasicBlock.frame.setInputFrameFromApiFormat(symbolTable, numLocal, local, numStack, stack);\n }\n // If type is not F_NEW then it is F_INSERT by hypothesis, and currentBlock.frame contains\n // the stack map frame at the current instruction, computed from the last F_NEW frame and\n // the bytecode instructions in between (via calls to CurrentFrame#execute).\n currentBasicBlock.frame.accept(this);\n }\n } else if (type == Opcodes.F_NEW) {\n if (previousFrame == null) {\n int argumentsSize = Type.getArgumentsAndReturnSizes(descriptor) >> 2;\n Frame implicitFirstFrame = new Frame(new Label());\n implicitFirstFrame.setInputFrameFromDescriptor(symbolTable, accessFlags, descriptor, argumentsSize);\n implicitFirstFrame.accept(this);\n }\n currentLocals = numLocal;\n int frameIndex = visitFrameStart(code.length, numLocal, numStack);\n for (int i = 0; i < numLocal; ++i) {\n currentFrame[frameIndex++] = Frame.getAbstractTypeFromApiFormat(symbolTable, local[i]);\n }\n for (int i = 0; i < numStack; ++i) {\n currentFrame[frameIndex++] = Frame.getAbstractTypeFromApiFormat(symbolTable, stack[i]);\n }\n visitFrameEnd();\n } else {\n if (symbolTable.getMajorVersion() < Opcodes.V1_6) {\n throw new IllegalArgumentException(\"Class versions V1_5 or less must use F_NEW frames.\");\n }\n int offsetDelta;\n if (stackMapTableEntries == null) {\n stackMapTableEntries = new ByteVector();\n offsetDelta = code.length;\n } else {\n offsetDelta = code.length - previousFrameOffset - 1;\n if (offsetDelta < 0) {\n if (type == Opcodes.F_SAME) {\n return;\n } else {\n throw new IllegalStateException();\n }\n }\n }\n switch (type) {\n case Opcodes.F_FULL:\n currentLocals = numLocal;\n stackMapTableEntries.putByte(Frame.FULL_FRAME).putShort(offsetDelta).putShort(numLocal);\n for (int i = 0; i < numLocal; ++i) {\n putFrameType(local[i]);\n }\n stackMapTableEntries.putShort(numStack);\n for (int i = 0; i < numStack; ++i) {\n putFrameType(stack[i]);\n }\n break;\n case Opcodes.F_APPEND:\n currentLocals += numLocal;\n stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED + numLocal).putShort(offsetDelta);\n for (int i = 0; i < numLocal; ++i) {\n putFrameType(local[i]);\n }\n break;\n case Opcodes.F_CHOP:\n currentLocals -= numLocal;\n stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED - numLocal).putShort(offsetDelta);\n break;\n case Opcodes.F_SAME:\n if (offsetDelta < 64) {\n stackMapTableEntries.putByte(offsetDelta);\n } else {\n stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED).putShort(offsetDelta);\n }\n break;\n case Opcodes.F_SAME1:\n if (offsetDelta < 64) {\n stackMapTableEntries.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME + offsetDelta);\n } else {\n stackMapTableEntries.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED).putShort(offsetDelta);\n }\n putFrameType(stack[0]);\n break;\n default:\n throw new IllegalArgumentException();\n }\n previousFrameOffset = code.length;\n ++stackMapTableNumberOfEntries;\n }\n if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) {\n relativeStackSize = numStack;\n for (int i = 0; i < numStack; ++i) {\n if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) {\n relativeStackSize++;\n }\n }\n if (relativeStackSize > maxRelativeStackSize) {\n maxRelativeStackSize = relativeStackSize;\n }\n }\n maxStack = Math.max(maxStack, numStack);\n maxLocals = Math.max(maxLocals, currentLocals);\n }\n\n @Override\n public void visitInsn(final int opcode) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n code.putByte(opcode);\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {\n currentBasicBlock.frame.execute(opcode, 0, null, null);\n } else {\n int size = relativeStackSize + STACK_SIZE_DELTA[opcode];\n if (size > maxRelativeStackSize) {\n maxRelativeStackSize = size;\n }\n relativeStackSize = size;\n }\n if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN) || opcode == Opcodes.ATHROW) {\n endCurrentBasicBlockWithNoSuccessor();\n }\n }\n }\n\n @Override\n public void visitIntInsn(final int opcode, final int operand) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n if (opcode == Opcodes.SIPUSH) {\n code.put12(opcode, operand);\n } else { // BIPUSH or NEWARRAY\n code.put11(opcode, operand);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {\n currentBasicBlock.frame.execute(opcode, operand, null, null);\n } else if (opcode != Opcodes.NEWARRAY) {\n // The stack size delta is 1 for BIPUSH or SIPUSH, and 0 for NEWARRAY.\n int size = relativeStackSize + 1;\n if (size > maxRelativeStackSize) {\n maxRelativeStackSize = size;\n }\n relativeStackSize = size;\n }\n }\n }\n\n @Override\n public void visitVarInsn(final int opcode, final int var) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n if (var < 4 && opcode != Opcodes.RET) {\n int optimizedOpcode;\n if (opcode < Opcodes.ISTORE) {\n optimizedOpcode = Constants.ILOAD_0 + ((opcode - Opcodes.ILOAD) << 2) + var;\n } else {\n optimizedOpcode = Constants.ISTORE_0 + ((opcode - Opcodes.ISTORE) << 2) + var;\n }\n code.putByte(optimizedOpcode);\n } else if (var >= 256) {\n code.putByte(Constants.WIDE).put12(opcode, var);\n } else {\n code.put11(opcode, var);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {\n currentBasicBlock.frame.execute(opcode, var, null, null);\n } else {\n if (opcode == Opcodes.RET) {\n // No stack size delta.\n currentBasicBlock.flags |= Label.FLAG_SUBROUTINE_END;\n currentBasicBlock.outputStackSize = (short) relativeStackSize;\n endCurrentBasicBlockWithNoSuccessor();\n } else { // xLOAD or xSTORE\n int size = relativeStackSize + STACK_SIZE_DELTA[opcode];\n if (size > maxRelativeStackSize) {\n maxRelativeStackSize = size;\n }\n relativeStackSize = size;\n }\n }\n }\n if (compute != COMPUTE_NOTHING) {\n int currentMaxLocals;\n if (opcode == Opcodes.LLOAD || opcode == Opcodes.DLOAD || opcode == Opcodes.LSTORE || opcode == Opcodes.DSTORE) {\n currentMaxLocals = var + 2;\n } else {\n currentMaxLocals = var + 1;\n }\n if (currentMaxLocals > maxLocals) {\n maxLocals = currentMaxLocals;\n }\n }\n if (opcode >= Opcodes.ISTORE && compute == COMPUTE_ALL_FRAMES && firstHandler != null) {\n // If there are exception handler blocks, each instruction within a handler range is, in\n // theory, a basic block (since execution can jump from this instruction to the exception\n // handler). As a consequence, the local variable types at the beginning of the handler\n // block should be the merge of the local variable types at all the instructions within the\n // handler range. However, instead of creating a basic block for each instruction, we can\n // get the same result in a more efficient way. Namely, by starting a new basic block after\n // each xSTORE instruction, which is what we do here.\n visitLabel(new Label());\n }\n }\n\n @Override\n public void visitTypeInsn(final int opcode, final String type) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n Symbol typeSymbol = symbolTable.addConstantClass(type);\n code.put12(opcode, typeSymbol.index);\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {\n currentBasicBlock.frame.execute(opcode, lastBytecodeOffset, typeSymbol, symbolTable);\n } else if (opcode == Opcodes.NEW) {\n // The stack size delta is 1 for NEW, and 0 for ANEWARRAY, CHECKCAST, or INSTANCEOF.\n int size = relativeStackSize + 1;\n if (size > maxRelativeStackSize) {\n maxRelativeStackSize = size;\n }\n relativeStackSize = size;\n }\n }\n }\n\n @Override\n public void visitFieldInsn(final int opcode, final String owner, final String name, final String descriptor) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n Symbol fieldrefSymbol = symbolTable.addConstantFieldref(owner, name, descriptor);\n code.put12(opcode, fieldrefSymbol.index);\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {\n currentBasicBlock.frame.execute(opcode, 0, fieldrefSymbol, symbolTable);\n } else {\n int size;\n char firstDescChar = descriptor.charAt(0);\n switch (opcode) {\n case Opcodes.GETSTATIC:\n size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? 2 : 1);\n break;\n case Opcodes.PUTSTATIC:\n size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? -2 : -1);\n break;\n case Opcodes.GETFIELD:\n size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? 1 : 0);\n break;\n case Opcodes.PUTFIELD:\n default:\n size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? -3 : -2);\n break;\n }\n if (size > maxRelativeStackSize) {\n maxRelativeStackSize = size;\n }\n relativeStackSize = size;\n }\n }\n }\n\n @Override\n public void visitMethodInsn(final int opcode, final String owner, final String name, final String descriptor, final boolean isInterface) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n Symbol methodrefSymbol = symbolTable.addConstantMethodref(owner, name, descriptor, isInterface);\n if (opcode == Opcodes.INVOKEINTERFACE) {\n code.put12(Opcodes.INVOKEINTERFACE, methodrefSymbol.index).put11(methodrefSymbol.getArgumentsAndReturnSizes() >> 2, 0);\n } else {\n code.put12(opcode, methodrefSymbol.index);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {\n currentBasicBlock.frame.execute(opcode, 0, methodrefSymbol, symbolTable);\n } else {\n int argumentsAndReturnSize = methodrefSymbol.getArgumentsAndReturnSizes();\n int stackSizeDelta = (argumentsAndReturnSize & 3) - (argumentsAndReturnSize >> 2);\n int size;\n if (opcode == Opcodes.INVOKESTATIC) {\n size = relativeStackSize + stackSizeDelta + 1;\n } else {\n size = relativeStackSize + stackSizeDelta;\n }\n if (size > maxRelativeStackSize) {\n maxRelativeStackSize = size;\n }\n relativeStackSize = size;\n }\n }\n }\n\n @Override\n public void visitInvokeDynamicInsn(final String name, final String descriptor, final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n Symbol invokeDynamicSymbol = symbolTable.addConstantInvokeDynamic(name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments);\n code.put12(Opcodes.INVOKEDYNAMIC, invokeDynamicSymbol.index);\n code.putShort(0);\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {\n currentBasicBlock.frame.execute(Opcodes.INVOKEDYNAMIC, 0, invokeDynamicSymbol, symbolTable);\n } else {\n int argumentsAndReturnSize = invokeDynamicSymbol.getArgumentsAndReturnSizes();\n int stackSizeDelta = (argumentsAndReturnSize & 3) - (argumentsAndReturnSize >> 2) + 1;\n int size = relativeStackSize + stackSizeDelta;\n if (size > maxRelativeStackSize) {\n maxRelativeStackSize = size;\n }\n relativeStackSize = size;\n }\n }\n }\n\n @Override\n public void visitJumpInsn(final int opcode, final Label label) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n // Compute the 'base' opcode, i.e. GOTO or JSR if opcode is GOTO_W or JSR_W, otherwise opcode.\n int baseOpcode = opcode >= Constants.GOTO_W ? opcode - Constants.WIDE_JUMP_OPCODE_DELTA : opcode;\n boolean nextInsnIsJumpTarget = false;\n if ((label.flags & Label.FLAG_RESOLVED) != 0 && label.bytecodeOffset - code.length < Short.MIN_VALUE) {\n // Case of a backward jump with an offset < -32768. In this case we automatically replace GOTO\n // with GOTO_W, JSR with JSR_W and IFxxx with IFNOTxxx GOTO_W L:..., where\n // IFNOTxxx is the \"opposite\" opcode of IFxxx (e.g. IFNE for IFEQ) and where designates\n // the instruction just after the GOTO_W.\n if (baseOpcode == Opcodes.GOTO) {\n code.putByte(Constants.GOTO_W);\n } else if (baseOpcode == Opcodes.JSR) {\n code.putByte(Constants.JSR_W);\n } else {\n // Put the \"opposite\" opcode of baseOpcode. This can be done by flipping the least\n // significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ (with a\n // pre and post offset by 1). The jump offset is 8 bytes (3 for IFNOTxxx, 5 for GOTO_W).\n code.putByte(baseOpcode >= Opcodes.IFNULL ? baseOpcode ^ 1 : ((baseOpcode + 1) ^ 1) - 1);\n code.putShort(8);\n // Here we could put a GOTO_W in theory, but if ASM specific instructions are used in this\n // method or another one, and if the class has frames, we will need to insert a frame after\n // this GOTO_W during the additional ClassReader -> ClassWriter round trip to remove the ASM\n // specific instructions. To not miss this additional frame, we need to use an ASM_GOTO_W\n // here, which has the unfortunate effect of forcing this additional round trip (which in\n // some case would not have been really necessary, but we can't know this at this point).\n code.putByte(Constants.ASM_GOTO_W);\n hasAsmInstructions = true;\n // The instruction after the GOTO_W becomes the target of the IFNOT instruction.\n nextInsnIsJumpTarget = true;\n }\n label.put(code, code.length - 1, true);\n } else if (baseOpcode != opcode) {\n // Case of a GOTO_W or JSR_W specified by the user (normally ClassReader when used to remove\n // ASM specific instructions). In this case we keep the original instruction.\n code.putByte(opcode);\n label.put(code, code.length - 1, true);\n } else {\n // Case of a jump with an offset >= -32768, or of a jump with an unknown offset. In these\n // cases we store the offset in 2 bytes (which will be increased via a ClassReader ->\n // ClassWriter round trip if it turns out that 2 bytes are not sufficient).\n code.putByte(baseOpcode);\n label.put(code, code.length - 1, false);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n Label nextBasicBlock = null;\n if (compute == COMPUTE_ALL_FRAMES) {\n currentBasicBlock.frame.execute(baseOpcode, 0, null, null);\n // Record the fact that 'label' is the target of a jump instruction.\n label.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;\n // Add 'label' as a successor of the current basic block.\n addSuccessorToCurrentBasicBlock(Edge.JUMP, label);\n if (baseOpcode != Opcodes.GOTO) {\n // The next instruction starts a new basic block (except for GOTO: by default the code\n // following a goto is unreachable - unless there is an explicit label for it - and we\n // should not compute stack frame types for its instructions).\n nextBasicBlock = new Label();\n }\n } else if (compute == COMPUTE_INSERTED_FRAMES) {\n currentBasicBlock.frame.execute(baseOpcode, 0, null, null);\n } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) {\n // No need to update maxRelativeStackSize (the stack size delta is always negative).\n relativeStackSize += STACK_SIZE_DELTA[baseOpcode];\n } else {\n if (baseOpcode == Opcodes.JSR) {\n // Record the fact that 'label' designates a subroutine, if not already done.\n if ((label.flags & Label.FLAG_SUBROUTINE_START) == 0) {\n label.flags |= Label.FLAG_SUBROUTINE_START;\n hasSubroutines = true;\n }\n currentBasicBlock.flags |= Label.FLAG_SUBROUTINE_CALLER;\n // Note that, by construction in this method, a block which calls a subroutine has at\n // least two successors in the control flow graph: the first one (added below) leads to\n // the instruction after the JSR, while the second one (added here) leads to the JSR\n // target. Note that the first successor is virtual (it does not correspond to a possible\n // execution path): it is only used to compute the successors of the basic blocks ending\n // with a ret, in {@link Label#addSubroutineRetSuccessors}.\n addSuccessorToCurrentBasicBlock(relativeStackSize + 1, label);\n // The instruction after the JSR starts a new basic block.\n nextBasicBlock = new Label();\n } else {\n // No need to update maxRelativeStackSize (the stack size delta is always negative).\n relativeStackSize += STACK_SIZE_DELTA[baseOpcode];\n addSuccessorToCurrentBasicBlock(relativeStackSize, label);\n }\n }\n // If the next instruction starts a new basic block, call visitLabel to add the label of this\n // instruction as a successor of the current block, and to start a new basic block.\n if (nextBasicBlock != null) {\n if (nextInsnIsJumpTarget) {\n nextBasicBlock.flags |= Label.FLAG_JUMP_TARGET;\n }\n visitLabel(nextBasicBlock);\n }\n if (baseOpcode == Opcodes.GOTO) {\n endCurrentBasicBlockWithNoSuccessor();\n }\n }\n }\n\n @Override\n public void visitLabel(final Label label) {\n // Resolve the forward references to this label, if any.\n hasAsmInstructions |= label.resolve(code.data, code.length);\n // visitLabel starts a new basic block (except for debug only labels), so we need to update the\n // previous and current block references and list of successors.\n if ((label.flags & Label.FLAG_DEBUG_ONLY) != 0) {\n return;\n }\n if (compute == COMPUTE_ALL_FRAMES) {\n if (currentBasicBlock != null) {\n if (label.bytecodeOffset == currentBasicBlock.bytecodeOffset) {\n // We use {@link Label#getCanonicalInstance} to store the state of a basic block in only\n // one place, but this does not work for labels which have not been visited yet.\n // Therefore, when we detect here two labels having the same bytecode offset, we need to\n // - consolidate the state scattered in these two instances into the canonical instance:\n currentBasicBlock.flags |= (label.flags & Label.FLAG_JUMP_TARGET);\n // - make sure the two instances share the same Frame instance (the implementation of\n // {@link Label#getCanonicalInstance} relies on this property; here label.frame should be\n // null):\n label.frame = currentBasicBlock.frame;\n // - and make sure to NOT assign 'label' into 'currentBasicBlock' or 'lastBasicBlock', so\n // that they still refer to the canonical instance for this bytecode offset.\n return;\n }\n // End the current basic block (with one new successor).\n addSuccessorToCurrentBasicBlock(Edge.JUMP, label);\n }\n // Append 'label' at the end of the basic block list.\n if (lastBasicBlock != null) {\n if (label.bytecodeOffset == lastBasicBlock.bytecodeOffset) {\n // Same comment as above.\n lastBasicBlock.flags |= (label.flags & Label.FLAG_JUMP_TARGET);\n // Here label.frame should be null.\n label.frame = lastBasicBlock.frame;\n currentBasicBlock = lastBasicBlock;\n return;\n }\n lastBasicBlock.nextBasicBlock = label;\n }\n lastBasicBlock = label;\n // Make it the new current basic block.\n currentBasicBlock = label;\n // Here label.frame should be null.\n label.frame = new Frame(label);\n } else if (compute == COMPUTE_INSERTED_FRAMES) {\n if (currentBasicBlock == null) {\n // This case should happen only once, for the visitLabel call in the constructor. Indeed, if\n // compute is equal to COMPUTE_INSERTED_FRAMES, currentBasicBlock stays unchanged.\n currentBasicBlock = label;\n } else {\n // Update the frame owner so that a correct frame offset is computed in Frame.accept().\n currentBasicBlock.frame.owner = label;\n }\n } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {\n if (currentBasicBlock != null) {\n // End the current basic block (with one new successor).\n currentBasicBlock.outputStackMax = (short) maxRelativeStackSize;\n addSuccessorToCurrentBasicBlock(relativeStackSize, label);\n }\n // Start a new current basic block, and reset the current and maximum relative stack sizes.\n currentBasicBlock = label;\n relativeStackSize = 0;\n maxRelativeStackSize = 0;\n // Append the new basic block at the end of the basic block list.\n if (lastBasicBlock != null) {\n lastBasicBlock.nextBasicBlock = label;\n }\n lastBasicBlock = label;\n } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES && currentBasicBlock == null) {\n // This case should happen only once, for the visitLabel call in the constructor. Indeed, if\n // compute is equal to COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES, currentBasicBlock stays\n // unchanged.\n currentBasicBlock = label;\n }\n }\n\n @Override\n public void visitLdcInsn(final Object value) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n Symbol constantSymbol = symbolTable.addConstant(value);\n int constantIndex = constantSymbol.index;\n char firstDescriptorChar;\n boolean isLongOrDouble = constantSymbol.tag == Symbol.CONSTANT_LONG_TAG || constantSymbol.tag == Symbol.CONSTANT_DOUBLE_TAG || (constantSymbol.tag == Symbol.CONSTANT_DYNAMIC_TAG && ((firstDescriptorChar = constantSymbol.value.charAt(0)) == 'J' || firstDescriptorChar == 'D'));\n if (isLongOrDouble) {\n code.put12(Constants.LDC2_W, constantIndex);\n } else if (constantIndex >= 256) {\n code.put12(Constants.LDC_W, constantIndex);\n } else {\n code.put11(Opcodes.LDC, constantIndex);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {\n currentBasicBlock.frame.execute(Opcodes.LDC, 0, constantSymbol, symbolTable);\n } else {\n int size = relativeStackSize + (isLongOrDouble ? 2 : 1);\n if (size > maxRelativeStackSize) {\n maxRelativeStackSize = size;\n }\n relativeStackSize = size;\n }\n }\n }\n\n @Override\n public void visitIincInsn(final int var, final int increment) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n if ((var > 255) || (increment > 127) || (increment < -128)) {\n code.putByte(Constants.WIDE).put12(Opcodes.IINC, var).putShort(increment);\n } else {\n code.putByte(Opcodes.IINC).put11(var, increment);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null && (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES)) {\n currentBasicBlock.frame.execute(Opcodes.IINC, var, null, null);\n }\n if (compute != COMPUTE_NOTHING) {\n int currentMaxLocals = var + 1;\n if (currentMaxLocals > maxLocals) {\n maxLocals = currentMaxLocals;\n }\n }\n }\n\n @Override\n public void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label... labels) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n code.putByte(Opcodes.TABLESWITCH).putByteArray(null, 0, (4 - code.length % 4) % 4);\n dflt.put(code, lastBytecodeOffset, true);\n code.putInt(min).putInt(max);\n for (Label label : labels) {\n label.put(code, lastBytecodeOffset, true);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n visitSwitchInsn(dflt, labels);\n }\n\n @Override\n public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n code.putByte(Opcodes.LOOKUPSWITCH).putByteArray(null, 0, (4 - code.length % 4) % 4);\n dflt.put(code, lastBytecodeOffset, true);\n code.putInt(labels.length);\n for (int i = 0; i < labels.length; ++i) {\n code.putInt(keys[i]);\n labels[i].put(code, lastBytecodeOffset, true);\n }\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n visitSwitchInsn(dflt, labels);\n }\n\n private void visitSwitchInsn(final Label dflt, final Label[] labels) {\n if (currentBasicBlock != null) {\n if (compute == COMPUTE_ALL_FRAMES) {\n currentBasicBlock.frame.execute(Opcodes.LOOKUPSWITCH, 0, null, null);\n // Add all the labels as successors of the current basic block.\n addSuccessorToCurrentBasicBlock(Edge.JUMP, dflt);\n dflt.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;\n for (Label label : labels) {\n addSuccessorToCurrentBasicBlock(Edge.JUMP, label);\n label.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;\n }\n } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {\n // No need to update maxRelativeStackSize (the stack size delta is always negative).\n --relativeStackSize;\n // Add all the labels as successors of the current basic block.\n addSuccessorToCurrentBasicBlock(relativeStackSize, dflt);\n for (Label label : labels) {\n addSuccessorToCurrentBasicBlock(relativeStackSize, label);\n }\n }\n // End the current basic block.\n endCurrentBasicBlockWithNoSuccessor();\n }\n }\n\n @Override\n public void visitMultiANewArrayInsn(final String descriptor, final int numDimensions) {\n lastBytecodeOffset = code.length;\n // Add the instruction to the bytecode of the method.\n Symbol descSymbol = symbolTable.addConstantClass(descriptor);\n code.put12(Opcodes.MULTIANEWARRAY, descSymbol.index).putByte(numDimensions);\n // If needed, update the maximum stack size and number of locals, and stack map frames.\n if (currentBasicBlock != null) {\n if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {\n currentBasicBlock.frame.execute(Opcodes.MULTIANEWARRAY, numDimensions, descSymbol, symbolTable);\n } else {\n // No need to update maxRelativeStackSize (the stack size delta is always negative).\n relativeStackSize += 1 - numDimensions;\n }\n }\n }\n\n @Override\n public AnnotationVisitor visitInsnAnnotation(final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {\n if (visible) {\n return lastCodeRuntimeVisibleTypeAnnotation = AnnotationWriter.create(symbolTable, (typeRef & 0xFF0000FF) | (lastBytecodeOffset << 8), typePath, descriptor, lastCodeRuntimeVisibleTypeAnnotation);\n } else {\n return lastCodeRuntimeInvisibleTypeAnnotation = AnnotationWriter.create(symbolTable, (typeRef & 0xFF0000FF) | (lastBytecodeOffset << 8), typePath, descriptor, lastCodeRuntimeInvisibleTypeAnnotation);\n }\n }\n\n @Override\n public void visitTryCatchBlock(final Label start, final Label end, final Label handler, final String type) {\n Handler newHandler = new Handler(start, end, handler, type != null ? symbolTable.addConstantClass(type).index : 0, type);\n if (firstHandler == null) {\n firstHandler = newHandler;\n } else {\n lastHandler.nextHandler = newHandler;\n }\n lastHandler = newHandler;\n }\n\n @Override\n public AnnotationVisitor visitTryCatchAnnotation(final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {\n if (visible) {\n return lastCodeRuntimeVisibleTypeAnnotation = AnnotationWriter.create(symbolTable, typeRef, typePath, descriptor, lastCodeRuntimeVisibleTypeAnnotation);\n } else {\n return lastCodeRuntimeInvisibleTypeAnnotation = AnnotationWriter.create(symbolTable, typeRef, typePath, descriptor, lastCodeRuntimeInvisibleTypeAnnotation);\n }\n }\n\n @Override\n public void visitLocalVariable(final String name, final String descriptor, final String signature, final Label start, final Label end, final int index) {\n if (signature != null) {\n if (localVariableTypeTable == null) {\n localVariableTypeTable = new ByteVector();\n }\n ++localVariableTypeTableLength;\n localVariableTypeTable.putShort(start.bytecodeOffset).putShort(end.bytecodeOffset - start.bytecodeOffset).putShort(symbolTable.addConstantUtf8(name)).putShort(symbolTable.addConstantUtf8(signature)).putShort(index);\n }\n if (localVariableTable == null) {\n localVariableTable = new ByteVector();\n }\n ++localVariableTableLength;\n localVariableTable.putShort(start.bytecodeOffset).putShort(end.bytecodeOffset - start.bytecodeOffset).putShort(symbolTable.addConstantUtf8(name)).putShort(symbolTable.addConstantUtf8(descriptor)).putShort(index);\n if (compute != COMPUTE_NOTHING) {\n char firstDescChar = descriptor.charAt(0);\n int currentMaxLocals = index + (firstDescChar == 'J' || firstDescChar == 'D' ? 2 : 1);\n if (currentMaxLocals > maxLocals) {\n maxLocals = currentMaxLocals;\n }\n }\n }\n\n @Override\n public AnnotationVisitor visitLocalVariableAnnotation(final int typeRef, final TypePath typePath, final Label[] start, final Label[] end, final int[] index, final String descriptor, final boolean visible) {\n // Create a ByteVector to hold a 'type_annotation' JVMS structure.\n // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.20.\n ByteVector typeAnnotation = new ByteVector();\n // Write target_type, target_info, and target_path.\n typeAnnotation.putByte(typeRef >>> 24).putShort(start.length);\n for (int i = 0; i < start.length; ++i) {\n typeAnnotation.putShort(start[i].bytecodeOffset).putShort(end[i].bytecodeOffset - start[i].bytecodeOffset).putShort(index[i]);\n }\n TypePath.put(typePath, typeAnnotation);\n // Write type_index and reserve space for num_element_value_pairs.\n typeAnnotation.putShort(symbolTable.addConstantUtf8(descriptor)).putShort(0);\n if (visible) {\n return lastCodeRuntimeVisibleTypeAnnotation = new AnnotationWriter(symbolTable,\n /* useNamedValues = */ true, typeAnnotation, lastCodeRuntimeVisibleTypeAnnotation);\n } else {\n return lastCodeRuntimeInvisibleTypeAnnotation = new AnnotationWriter(symbolTable,\n /* useNamedValues = */ true, typeAnnotation, lastCodeRuntimeInvisibleTypeAnnotation);\n }\n }\n\n @Override\n public void visitLineNumber(final int line, final Label start) {\n if (lineNumberTable == null) {\n lineNumberTable = new ByteVector();\n }\n ++lineNumberTableLength;\n lineNumberTable.putShort(start.bytecodeOffset);\n lineNumberTable.putShort(line);\n }\n\n @Override\n public void visitMaxs(final int maxStack, final int maxLocals) {\n if (compute == COMPUTE_ALL_FRAMES) {\n computeAllFrames();\n } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {\n computeMaxStackAndLocal();\n } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) {\n this.maxStack = maxRelativeStackSize;\n } else {\n this.maxStack = maxStack;\n this.maxLocals = maxLocals;\n }\n }\n\n /** Computes all the stack map frames of the method, from scratch. */\n private void computeAllFrames() {\n // Complete the control flow graph with exception handler blocks.\n Handler handler = firstHandler;\n while (handler != null) {\n String catchTypeDescriptor = handler.catchTypeDescriptor == null ? \"java/lang/Throwable\" : handler.catchTypeDescriptor;\n int catchType = Frame.getAbstractTypeFromInternalName(symbolTable, catchTypeDescriptor);\n // Mark handlerBlock as an exception handler.\n Label handlerBlock = handler.handlerPc.getCanonicalInstance();\n handlerBlock.flags |= Label.FLAG_JUMP_TARGET;\n // Add handlerBlock as a successor of all the basic blocks in the exception handler range.\n Label handlerRangeBlock = handler.startPc.getCanonicalInstance();\n Label handlerRangeEnd = handler.endPc.getCanonicalInstance();\n while (handlerRangeBlock != handlerRangeEnd) {\n handlerRangeBlock.outgoingEdges = new Edge(catchType, handlerBlock, handlerRangeBlock.outgoingEdges);\n handlerRangeBlock = handlerRangeBlock.nextBasicBlock;\n }\n handler = handler.nextHandler;\n }\n // Create and visit the first (implicit) frame.\n Frame firstFrame = firstBasicBlock.frame;\n firstFrame.setInputFrameFromDescriptor(symbolTable, accessFlags, descriptor, this.maxLocals);\n firstFrame.accept(this);\n // Fix point algorithm: add the first basic block to a list of blocks to process (i.e. blocks\n // whose stack map frame has changed) and, while there are blocks to process, remove one from\n // the list and update the stack map frames of its successor blocks in the control flow graph\n // (which might change them, in which case these blocks must be processed too, and are thus\n // added to the list of blocks to process). Also compute the maximum stack size of the method,\n // as a by-product.\n Label listOfBlocksToProcess = firstBasicBlock;\n listOfBlocksToProcess.nextListElement = Label.EMPTY_LIST;\n int maxStackSize = 0;\n while (listOfBlocksToProcess != Label.EMPTY_LIST) {\n // Remove a basic block from the list of blocks to process.\n Label basicBlock = listOfBlocksToProcess;\n listOfBlocksToProcess = listOfBlocksToProcess.nextListElement;\n basicBlock.nextListElement = null;\n // By definition, basicBlock is reachable.\n basicBlock.flags |= Label.FLAG_REACHABLE;\n // Update the (absolute) maximum stack size.\n int maxBlockStackSize = basicBlock.frame.getInputStackSize() + basicBlock.outputStackMax;\n if (maxBlockStackSize > maxStackSize) {\n maxStackSize = maxBlockStackSize;\n }\n // Update the successor blocks of basicBlock in the control flow graph.\n Edge outgoingEdge = basicBlock.outgoingEdges;\n while (outgoingEdge != null) {\n Label successorBlock = outgoingEdge.successor.getCanonicalInstance();\n boolean successorBlockChanged = basicBlock.frame.merge(symbolTable, successorBlock.frame, outgoingEdge.info);\n if (successorBlockChanged && successorBlock.nextListElement == null) {\n // If successorBlock has changed it must be processed. Thus, if it is not already in the\n // list of blocks to process, add it to this list.\n successorBlock.nextListElement = listOfBlocksToProcess;\n listOfBlocksToProcess = successorBlock;\n }\n outgoingEdge = outgoingEdge.nextEdge;\n }\n }\n // Loop over all the basic blocks and visit the stack map frames that must be stored in the\n // StackMapTable attribute. Also replace unreachable code with NOP* ATHROW, and remove it from\n // exception handler ranges.\n Label basicBlock = firstBasicBlock;\n while (basicBlock != null) {\n if ((basicBlock.flags & (Label.FLAG_JUMP_TARGET | Label.FLAG_REACHABLE)) == (Label.FLAG_JUMP_TARGET | Label.FLAG_REACHABLE)) {\n basicBlock.frame.accept(this);\n }\n if ((basicBlock.flags & Label.FLAG_REACHABLE) == 0) {\n // Find the start and end bytecode offsets of this unreachable block.\n Label nextBasicBlock = basicBlock.nextBasicBlock;\n int startOffset = basicBlock.bytecodeOffset;\n int endOffset = (nextBasicBlock == null ? code.length : nextBasicBlock.bytecodeOffset) - 1;\n if (endOffset >= startOffset) {\n // Replace its instructions with NOP ... NOP ATHROW.\n for (int i = startOffset; i < endOffset; ++i) {\n code.data[i] = Opcodes.NOP;\n }\n code.data[endOffset] = (byte) Opcodes.ATHROW;\n // Emit a frame for this unreachable block, with no local and a Throwable on the stack\n // (so that the ATHROW could consume this Throwable if it were reachable).\n int frameIndex = visitFrameStart(startOffset, /* numLocal = */ 0, /* numStack = */ 1);\n currentFrame[frameIndex] = Frame.getAbstractTypeFromInternalName(symbolTable, \"java/lang/Throwable\");\n visitFrameEnd();\n // Remove this unreachable basic block from the exception handler ranges.\n firstHandler = Handler.removeRange(firstHandler, basicBlock, nextBasicBlock);\n // The maximum stack size is now at least one, because of the Throwable declared above.\n maxStackSize = Math.max(maxStackSize, 1);\n }\n }\n basicBlock = basicBlock.nextBasicBlock;\n }\n this.maxStack = maxStackSize;\n }\n\n /** Computes the maximum stack size of the method. */\n private void computeMaxStackAndLocal() {\n // Complete the control flow graph with exception handler blocks.\n Handler handler = firstHandler;\n while (handler != null) {\n Label handlerBlock = handler.handlerPc;\n Label handlerRangeBlock = handler.startPc;\n Label handlerRangeEnd = handler.endPc;\n // Add handlerBlock as a successor of all the basic blocks in the exception handler range.\n while (handlerRangeBlock != handlerRangeEnd) {\n if ((handlerRangeBlock.flags & Label.FLAG_SUBROUTINE_CALLER) == 0) {\n handlerRangeBlock.outgoingEdges = new Edge(Edge.EXCEPTION, handlerBlock, handlerRangeBlock.outgoingEdges);\n } else {\n // If handlerRangeBlock is a JSR block, add handlerBlock after the first two outgoing\n // edges to preserve the hypothesis about JSR block successors order (see\n // {@link #visitJumpInsn}).\n handlerRangeBlock.outgoingEdges.nextEdge.nextEdge = new Edge(Edge.EXCEPTION, handlerBlock, handlerRangeBlock.outgoingEdges.nextEdge.nextEdge);\n }\n handlerRangeBlock = handlerRangeBlock.nextBasicBlock;\n }\n handler = handler.nextHandler;\n }\n // Complete the control flow graph with the successor blocks of subroutines, if needed.\n if (hasSubroutines) {\n // First step: find the subroutines. This step determines, for each basic block, to which\n // subroutine(s) it belongs. Start with the main \"subroutine\":\n short numSubroutines = 1;\n firstBasicBlock.markSubroutine(numSubroutines);\n // Then, mark the subroutines called by the main subroutine, then the subroutines called by\n // those called by the main subroutine, etc.\n for (short currentSubroutine = 1; currentSubroutine <= numSubroutines; ++currentSubroutine) {\n Label basicBlock = firstBasicBlock;\n while (basicBlock != null) {\n if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0 && basicBlock.subroutineId == currentSubroutine) {\n Label jsrTarget = basicBlock.outgoingEdges.nextEdge.successor;\n if (jsrTarget.subroutineId == 0) {\n // If this subroutine has not been marked yet, find its basic blocks.\n jsrTarget.markSubroutine(++numSubroutines);\n }\n }\n basicBlock = basicBlock.nextBasicBlock;\n }\n }\n // Second step: find the successors in the control flow graph of each subroutine basic block\n // 'r' ending with a RET instruction. These successors are the virtual successors of the basic\n // blocks ending with JSR instructions (see {@link #visitJumpInsn)} that can reach 'r'.\n Label basicBlock = firstBasicBlock;\n while (basicBlock != null) {\n if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0) {\n // By construction, jsr targets are stored in the second outgoing edge of basic blocks\n // that ends with a jsr instruction (see {@link #FLAG_SUBROUTINE_CALLER}).\n Label subroutine = basicBlock.outgoingEdges.nextEdge.successor;\n subroutine.addSubroutineRetSuccessors(basicBlock);\n }\n basicBlock = basicBlock.nextBasicBlock;\n }\n }\n // Data flow algorithm: put the first basic block in a list of blocks to process (i.e. blocks\n // whose input stack size has changed) and, while there are blocks to process, remove one\n // from the list, update the input stack size of its successor blocks in the control flow\n // graph, and add these blocks to the list of blocks to process (if not already done).\n Label listOfBlocksToProcess = firstBasicBlock;\n listOfBlocksToProcess.nextListElement = Label.EMPTY_LIST;\n int maxStackSize = maxStack;\n while (listOfBlocksToProcess != Label.EMPTY_LIST) {\n // Remove a basic block from the list of blocks to process. Note that we don't reset\n // basicBlock.nextListElement to null on purpose, to make sure we don't reprocess already\n // processed basic blocks.\n Label basicBlock = listOfBlocksToProcess;\n listOfBlocksToProcess = listOfBlocksToProcess.nextListElement;\n // Compute the (absolute) input stack size and maximum stack size of this block.\n int inputStackTop = basicBlock.inputStackSize;\n int maxBlockStackSize = inputStackTop + basicBlock.outputStackMax;\n // Update the absolute maximum stack size of the method.\n if (maxBlockStackSize > maxStackSize) {\n maxStackSize = maxBlockStackSize;\n }\n // Update the input stack size of the successor blocks of basicBlock in the control flow\n // graph, and add these blocks to the list of blocks to process, if not already done.\n Edge outgoingEdge = basicBlock.outgoingEdges;\n if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0) {\n // Ignore the first outgoing edge of the basic blocks ending with a jsr: these are virtual\n // edges which lead to the instruction just after the jsr, and do not correspond to a\n // possible execution path (see {@link #visitJumpInsn} and\n // {@link Label#FLAG_SUBROUTINE_CALLER}).\n outgoingEdge = outgoingEdge.nextEdge;\n }\n while (outgoingEdge != null) {\n Label successorBlock = outgoingEdge.successor;\n if (successorBlock.nextListElement == null) {\n successorBlock.inputStackSize = (short) (outgoingEdge.info == Edge.EXCEPTION ? 1 : inputStackTop + outgoingEdge.info);\n successorBlock.nextListElement = listOfBlocksToProcess;\n listOfBlocksToProcess = successorBlock;\n }\n outgoingEdge = outgoingEdge.nextEdge;\n }\n }\n this.maxStack = maxStackSize;\n }\n\n @Override\n public void visitEnd() {\n // Nothing to do.\n }\n // -----------------------------------------------------------------------------------------------\n // Utility methods: control flow analysis algorithm\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Adds a successor to {@link #currentBasicBlock} in the control flow graph.\n *\n * @param info information about the control flow edge to be added.\n * @param successor the successor block to be added to the current basic block.\n */\n private void addSuccessorToCurrentBasicBlock(final int info, final Label successor) {\n currentBasicBlock.outgoingEdges = new Edge(info, successor, currentBasicBlock.outgoingEdges);\n }\n\n /**\n * Ends the current basic block. This method must be used in the case where the current basic\n * block does not have any successor.\n *\n *

WARNING: this method must be called after the currently visited instruction has been put in\n * {@link #code} (if frames are computed, this method inserts a new Label to start a new basic\n * block after the current instruction).\n */\n private void endCurrentBasicBlockWithNoSuccessor() {\n if (compute == COMPUTE_ALL_FRAMES) {\n Label nextBasicBlock = new Label();\n nextBasicBlock.frame = new Frame(nextBasicBlock);\n nextBasicBlock.resolve(code.data, code.length);\n lastBasicBlock.nextBasicBlock = nextBasicBlock;\n lastBasicBlock = nextBasicBlock;\n currentBasicBlock = null;\n } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {\n currentBasicBlock.outputStackMax = (short) maxRelativeStackSize;\n currentBasicBlock = null;\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Utility methods: stack map frames\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Starts the visit of a new stack map frame, stored in {@link #currentFrame}.\n *\n * @param offset the bytecode offset of the instruction to which the frame corresponds.\n * @param numLocal the number of local variables in the frame.\n * @param numStack the number of stack elements in the frame.\n * @return the index of the next element to be written in this frame.\n */\n int visitFrameStart(final int offset, final int numLocal, final int numStack) {\n int frameLength = 3 + numLocal + numStack;\n if (currentFrame == null || currentFrame.length < frameLength) {\n currentFrame = new int[frameLength];\n }\n currentFrame[0] = offset;\n currentFrame[1] = numLocal;\n currentFrame[2] = numStack;\n return 3;\n }\n\n /**\n * Sets an abstract type in {@link #currentFrame}.\n *\n * @param frameIndex the index of the element to be set in {@link #currentFrame}.\n * @param abstractType an abstract type.\n */\n void visitAbstractType(final int frameIndex, final int abstractType) {\n currentFrame[frameIndex] = abstractType;\n }\n\n /**\n * Ends the visit of {@link #currentFrame} by writing it in the StackMapTable entries and by\n * updating the StackMapTable number_of_entries (except if the current frame is the first one,\n * which is implicit in StackMapTable). Then resets {@link #currentFrame} to {@literal null}.\n */\n void visitFrameEnd() {\n if (previousFrame != null) {\n if (stackMapTableEntries == null) {\n stackMapTableEntries = new ByteVector();\n }\n putFrame();\n ++stackMapTableNumberOfEntries;\n }\n previousFrame = currentFrame;\n currentFrame = null;\n }\n\n /** Compresses and writes {@link #currentFrame} in a new StackMapTable entry. */\n private void putFrame() {\n final int numLocal = currentFrame[1];\n final int numStack = currentFrame[2];\n if (symbolTable.getMajorVersion() < Opcodes.V1_6) {\n // Generate a StackMap attribute entry, which are always uncompressed.\n stackMapTableEntries.putShort(currentFrame[0]).putShort(numLocal);\n putAbstractTypes(3, 3 + numLocal);\n stackMapTableEntries.putShort(numStack);\n putAbstractTypes(3 + numLocal, 3 + numLocal + numStack);\n return;\n }\n final int offsetDelta = stackMapTableNumberOfEntries == 0 ? currentFrame[0] : currentFrame[0] - previousFrame[0] - 1;\n final int previousNumlocal = previousFrame[1];\n final int numLocalDelta = numLocal - previousNumlocal;\n int type = Frame.FULL_FRAME;\n if (numStack == 0) {\n switch (numLocalDelta) {\n case -3:\n case -2:\n case -1:\n type = Frame.CHOP_FRAME;\n break;\n case 0:\n type = offsetDelta < 64 ? Frame.SAME_FRAME : Frame.SAME_FRAME_EXTENDED;\n break;\n case 1:\n case 2:\n case 3:\n type = Frame.APPEND_FRAME;\n break;\n default:\n // Keep the FULL_FRAME type.\n break;\n }\n } else if (numLocalDelta == 0 && numStack == 1) {\n type = offsetDelta < 63 ? Frame.SAME_LOCALS_1_STACK_ITEM_FRAME : Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED;\n }\n if (type != Frame.FULL_FRAME) {\n // Verify if locals are the same as in the previous frame.\n int frameIndex = 3;\n for (int i = 0; i < previousNumlocal && i < numLocal; i++) {\n if (currentFrame[frameIndex] != previousFrame[frameIndex]) {\n type = Frame.FULL_FRAME;\n break;\n }\n frameIndex++;\n }\n }\n switch (type) {\n case Frame.SAME_FRAME:\n stackMapTableEntries.putByte(offsetDelta);\n break;\n case Frame.SAME_LOCALS_1_STACK_ITEM_FRAME:\n stackMapTableEntries.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME + offsetDelta);\n putAbstractTypes(3 + numLocal, 4 + numLocal);\n break;\n case Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED:\n stackMapTableEntries.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED).putShort(offsetDelta);\n putAbstractTypes(3 + numLocal, 4 + numLocal);\n break;\n case Frame.SAME_FRAME_EXTENDED:\n stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED).putShort(offsetDelta);\n break;\n case Frame.CHOP_FRAME:\n stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED + numLocalDelta).putShort(offsetDelta);\n break;\n case Frame.APPEND_FRAME:\n stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED + numLocalDelta).putShort(offsetDelta);\n putAbstractTypes(3 + previousNumlocal, 3 + numLocal);\n break;\n case Frame.FULL_FRAME:\n default:\n stackMapTableEntries.putByte(Frame.FULL_FRAME).putShort(offsetDelta).putShort(numLocal);\n putAbstractTypes(3, 3 + numLocal);\n stackMapTableEntries.putShort(numStack);\n putAbstractTypes(3 + numLocal, 3 + numLocal + numStack);\n break;\n }\n }\n\n /**\n * Puts some abstract types of {@link #currentFrame} in {@link #stackMapTableEntries} , using the\n * JVMS verification_type_info format used in StackMapTable attributes.\n *\n * @param start index of the first type in {@link #currentFrame} to write.\n * @param end index of last type in {@link #currentFrame} to write (exclusive).\n */\n private void putAbstractTypes(final int start, final int end) {\n for (int i = start; i < end; ++i) {\n Frame.putAbstractType(symbolTable, currentFrame[i], stackMapTableEntries);\n }\n }\n\n /**\n * Puts the given public API frame element type in {@link #stackMapTableEntries} , using the JVMS\n * verification_type_info format used in StackMapTable attributes.\n *\n * @param type a frame element type described using the same format as in {@link\n * MethodVisitor#visitFrame}, i.e. either {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, {@link\n * Opcodes#FLOAT}, {@link Opcodes#LONG}, {@link Opcodes#DOUBLE}, {@link Opcodes#NULL}, or\n * {@link Opcodes#UNINITIALIZED_THIS}, or the internal name of a class, or a Label designating\n * a NEW instruction (for uninitialized types).\n */\n private void putFrameType(final Object type) {\n if (type instanceof Integer) {\n stackMapTableEntries.putByte(((Integer) type).intValue());\n } else if (type instanceof String) {\n stackMapTableEntries.putByte(Frame.ITEM_OBJECT).putShort(symbolTable.addConstantClass((String) type).index);\n } else {\n stackMapTableEntries.putByte(Frame.ITEM_UNINITIALIZED).putShort(((Label) type).bytecodeOffset);\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Utility methods\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns whether the attributes of this method can be copied from the attributes of the given\n * method (assuming there is no method visitor between the given ClassReader and this\n * MethodWriter). This method should only be called just after this MethodWriter has been created,\n * and before any content is visited. It returns true if the attributes corresponding to the\n * constructor arguments (at most a Signature, an Exception, a Deprecated and a Synthetic\n * attribute) are the same as the corresponding attributes in the given method.\n *\n * @param source the source ClassReader from which the attributes of this method might be copied.\n * @param hasSyntheticAttribute whether the method_info JVMS structure from which the attributes\n * of this method might be copied contains a Synthetic attribute.\n * @param hasDeprecatedAttribute whether the method_info JVMS structure from which the attributes\n * of this method might be copied contains a Deprecated attribute.\n * @param descriptorIndex the descriptor_index field of the method_info JVMS structure from which\n * the attributes of this method might be copied.\n * @param signatureIndex the constant pool index contained in the Signature attribute of the\n * method_info JVMS structure from which the attributes of this method might be copied, or 0.\n * @param exceptionsOffset the offset in 'source.b' of the Exceptions attribute of the method_info\n * JVMS structure from which the attributes of this method might be copied, or 0.\n * @return whether the attributes of this method can be copied from the attributes of the\n * method_info JVMS structure in 'source.b', between 'methodInfoOffset' and 'methodInfoOffset'\n * + 'methodInfoLength'.\n */\n boolean canCopyMethodAttributes(final ClassReader source, final boolean hasSyntheticAttribute, final boolean hasDeprecatedAttribute, final int descriptorIndex, final int signatureIndex, final int exceptionsOffset) {\n // If the method descriptor has changed, with more locals than the max_locals field of the\n // original Code attribute, if any, then the original method attributes can't be copied. A\n // conservative check on the descriptor changes alone ensures this (being more precise is not\n // worth the additional complexity, because these cases should be rare -- if a transform changes\n // a method descriptor, most of the time it needs to change the method's code too).\n if (source != symbolTable.getSource() || descriptorIndex != this.descriptorIndex || signatureIndex != this.signatureIndex || hasDeprecatedAttribute != ((accessFlags & Opcodes.ACC_DEPRECATED) != 0)) {\n return false;\n }\n boolean needSyntheticAttribute = symbolTable.getMajorVersion() < Opcodes.V1_5 && (accessFlags & Opcodes.ACC_SYNTHETIC) != 0;\n if (hasSyntheticAttribute != needSyntheticAttribute) {\n return false;\n }\n if (exceptionsOffset == 0) {\n if (numberOfExceptions != 0) {\n return false;\n }\n } else if (source.readUnsignedShort(exceptionsOffset) == numberOfExceptions) {\n int currentExceptionOffset = exceptionsOffset + 2;\n for (int i = 0; i < numberOfExceptions; ++i) {\n if (source.readUnsignedShort(currentExceptionOffset) != exceptionIndexTable[i]) {\n return false;\n }\n currentExceptionOffset += 2;\n }\n }\n return true;\n }\n\n /**\n * Sets the source from which the attributes of this method will be copied.\n *\n * @param methodInfoOffset the offset in 'symbolTable.getSource()' of the method_info JVMS\n * structure from which the attributes of this method will be copied.\n * @param methodInfoLength the length in 'symbolTable.getSource()' of the method_info JVMS\n * structure from which the attributes of this method will be copied.\n */\n void setMethodAttributesSource(final int methodInfoOffset, final int methodInfoLength) {\n // Don't copy the attributes yet, instead store their location in the source class reader so\n // they can be copied later, in {@link #putMethodInfo}. Note that we skip the 6 header bytes\n // of the method_info JVMS structure.\n this.sourceOffset = methodInfoOffset + 6;\n this.sourceLength = methodInfoLength - 6;\n }\n\n /**\n * Returns the size of the method_info JVMS structure generated by this MethodWriter. Also add the\n * names of the attributes of this method in the constant pool.\n *\n * @return the size in bytes of the method_info JVMS structure.\n */\n int computeMethodInfoSize() {\n // If this method_info must be copied from an existing one, the size computation is trivial.\n if (sourceOffset != 0) {\n // sourceLength excludes the first 6 bytes for access_flags, name_index and descriptor_index.\n return 6 + sourceLength;\n }\n // 2 bytes each for access_flags, name_index, descriptor_index and attributes_count.\n int size = 8;\n // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.\n if (code.length > 0) {\n if (code.length > 65535) {\n throw new MethodTooLargeException(symbolTable.getClassName(), name, descriptor, code.length);\n }\n symbolTable.addConstantUtf8(Constants.CODE);\n // The Code attribute has 6 header bytes, plus 2, 2, 4 and 2 bytes respectively for max_stack,\n // max_locals, code_length and attributes_count, plus the bytecode and the exception table.\n size += 16 + code.length + Handler.getExceptionTableSize(firstHandler);\n if (stackMapTableEntries != null) {\n boolean useStackMapTable = symbolTable.getMajorVersion() >= Opcodes.V1_6;\n symbolTable.addConstantUtf8(useStackMapTable ? Constants.STACK_MAP_TABLE : \"StackMap\");\n // 6 header bytes and 2 bytes for number_of_entries.\n size += 8 + stackMapTableEntries.length;\n }\n if (lineNumberTable != null) {\n symbolTable.addConstantUtf8(Constants.LINE_NUMBER_TABLE);\n // 6 header bytes and 2 bytes for line_number_table_length.\n size += 8 + lineNumberTable.length;\n }\n if (localVariableTable != null) {\n symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TABLE);\n // 6 header bytes and 2 bytes for local_variable_table_length.\n size += 8 + localVariableTable.length;\n }\n if (localVariableTypeTable != null) {\n symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TYPE_TABLE);\n // 6 header bytes and 2 bytes for local_variable_type_table_length.\n size += 8 + localVariableTypeTable.length;\n }\n if (lastCodeRuntimeVisibleTypeAnnotation != null) {\n size += lastCodeRuntimeVisibleTypeAnnotation.computeAnnotationsSize(Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS);\n }\n if (lastCodeRuntimeInvisibleTypeAnnotation != null) {\n size += lastCodeRuntimeInvisibleTypeAnnotation.computeAnnotationsSize(Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS);\n }\n if (firstCodeAttribute != null) {\n size += firstCodeAttribute.computeAttributesSize(symbolTable, code.data, code.length, maxStack, maxLocals);\n }\n }\n if (numberOfExceptions > 0) {\n symbolTable.addConstantUtf8(Constants.EXCEPTIONS);\n size += 8 + 2 * numberOfExceptions;\n }\n size += Attribute.computeAttributesSize(symbolTable, accessFlags, signatureIndex);\n size += AnnotationWriter.computeAnnotationsSize(lastRuntimeVisibleAnnotation, lastRuntimeInvisibleAnnotation, lastRuntimeVisibleTypeAnnotation, lastRuntimeInvisibleTypeAnnotation);\n if (lastRuntimeVisibleParameterAnnotations != null) {\n size += AnnotationWriter.computeParameterAnnotationsSize(Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS, lastRuntimeVisibleParameterAnnotations, visibleAnnotableParameterCount == 0 ? lastRuntimeVisibleParameterAnnotations.length : visibleAnnotableParameterCount);\n }\n if (lastRuntimeInvisibleParameterAnnotations != null) {\n size += AnnotationWriter.computeParameterAnnotationsSize(Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS, lastRuntimeInvisibleParameterAnnotations, invisibleAnnotableParameterCount == 0 ? lastRuntimeInvisibleParameterAnnotations.length : invisibleAnnotableParameterCount);\n }\n if (defaultValue != null) {\n symbolTable.addConstantUtf8(Constants.ANNOTATION_DEFAULT);\n size += 6 + defaultValue.length;\n }\n if (parameters != null) {\n symbolTable.addConstantUtf8(Constants.METHOD_PARAMETERS);\n // 6 header bytes and 1 byte for parameters_count.\n size += 7 + parameters.length;\n }\n if (firstAttribute != null) {\n size += firstAttribute.computeAttributesSize(symbolTable);\n }\n return size;\n }\n\n /**\n * Puts the content of the method_info JVMS structure generated by this MethodWriter into the\n * given ByteVector.\n *\n * @param output where the method_info structure must be put.\n */\n void putMethodInfo(final ByteVector output) {\n boolean useSyntheticAttribute = symbolTable.getMajorVersion() < Opcodes.V1_5;\n int mask = useSyntheticAttribute ? Opcodes.ACC_SYNTHETIC : 0;\n output.putShort(accessFlags & ~mask).putShort(nameIndex).putShort(descriptorIndex);\n // If this method_info must be copied from an existing one, copy it now and return early.\n if (sourceOffset != 0) {\n output.putByteArray(symbolTable.getSource().classFileBuffer, sourceOffset, sourceLength);\n return;\n }\n // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.\n int attributeCount = 0;\n if (code.length > 0) {\n ++attributeCount;\n }\n if (numberOfExceptions > 0) {\n ++attributeCount;\n }\n if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && useSyntheticAttribute) {\n ++attributeCount;\n }\n if (signatureIndex != 0) {\n ++attributeCount;\n }\n if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) {\n ++attributeCount;\n }\n if (lastRuntimeVisibleAnnotation != null) {\n ++attributeCount;\n }\n if (lastRuntimeInvisibleAnnotation != null) {\n ++attributeCount;\n }\n if (lastRuntimeVisibleParameterAnnotations != null) {\n ++attributeCount;\n }\n if (lastRuntimeInvisibleParameterAnnotations != null) {\n ++attributeCount;\n }\n if (lastRuntimeVisibleTypeAnnotation != null) {\n ++attributeCount;\n }\n if (lastRuntimeInvisibleTypeAnnotation != null) {\n ++attributeCount;\n }\n if (defaultValue != null) {\n ++attributeCount;\n }\n if (parameters != null) {\n ++attributeCount;\n }\n if (firstAttribute != null) {\n attributeCount += firstAttribute.getAttributeCount();\n }\n // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.\n output.putShort(attributeCount);\n if (code.length > 0) {\n // 2, 2, 4 and 2 bytes respectively for max_stack, max_locals, code_length and\n // attributes_count, plus the bytecode and the exception table.\n int size = 10 + code.length + Handler.getExceptionTableSize(firstHandler);\n int codeAttributeCount = 0;\n if (stackMapTableEntries != null) {\n // 6 header bytes and 2 bytes for number_of_entries.\n size += 8 + stackMapTableEntries.length;\n ++codeAttributeCount;\n }\n if (lineNumberTable != null) {\n // 6 header bytes and 2 bytes for line_number_table_length.\n size += 8 + lineNumberTable.length;\n ++codeAttributeCount;\n }\n if (localVariableTable != null) {\n // 6 header bytes and 2 bytes for local_variable_table_length.\n size += 8 + localVariableTable.length;\n ++codeAttributeCount;\n }\n if (localVariableTypeTable != null) {\n // 6 header bytes and 2 bytes for local_variable_type_table_length.\n size += 8 + localVariableTypeTable.length;\n ++codeAttributeCount;\n }\n if (lastCodeRuntimeVisibleTypeAnnotation != null) {\n size += lastCodeRuntimeVisibleTypeAnnotation.computeAnnotationsSize(Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS);\n ++codeAttributeCount;\n }\n if (lastCodeRuntimeInvisibleTypeAnnotation != null) {\n size += lastCodeRuntimeInvisibleTypeAnnotation.computeAnnotationsSize(Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS);\n ++codeAttributeCount;\n }\n if (firstCodeAttribute != null) {\n size += firstCodeAttribute.computeAttributesSize(symbolTable, code.data, code.length, maxStack, maxLocals);\n codeAttributeCount += firstCodeAttribute.getAttributeCount();\n }\n output.putShort(symbolTable.addConstantUtf8(Constants.CODE)).putInt(size).putShort(maxStack).putShort(maxLocals).putInt(code.length).putByteArray(code.data, 0, code.length);\n Handler.putExceptionTable(firstHandler, output);\n output.putShort(codeAttributeCount);\n if (stackMapTableEntries != null) {\n boolean useStackMapTable = symbolTable.getMajorVersion() >= Opcodes.V1_6;\n output.putShort(symbolTable.addConstantUtf8(useStackMapTable ? Constants.STACK_MAP_TABLE : \"StackMap\")).putInt(2 + stackMapTableEntries.length).putShort(stackMapTableNumberOfEntries).putByteArray(stackMapTableEntries.data, 0, stackMapTableEntries.length);\n }\n if (lineNumberTable != null) {\n output.putShort(symbolTable.addConstantUtf8(Constants.LINE_NUMBER_TABLE)).putInt(2 + lineNumberTable.length).putShort(lineNumberTableLength).putByteArray(lineNumberTable.data, 0, lineNumberTable.length);\n }\n if (localVariableTable != null) {\n output.putShort(symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TABLE)).putInt(2 + localVariableTable.length).putShort(localVariableTableLength).putByteArray(localVariableTable.data, 0, localVariableTable.length);\n }\n if (localVariableTypeTable != null) {\n output.putShort(symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TYPE_TABLE)).putInt(2 + localVariableTypeTable.length).putShort(localVariableTypeTableLength).putByteArray(localVariableTypeTable.data, 0, localVariableTypeTable.length);\n }\n if (lastCodeRuntimeVisibleTypeAnnotation != null) {\n lastCodeRuntimeVisibleTypeAnnotation.putAnnotations(symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS), output);\n }\n if (lastCodeRuntimeInvisibleTypeAnnotation != null) {\n lastCodeRuntimeInvisibleTypeAnnotation.putAnnotations(symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS), output);\n }\n if (firstCodeAttribute != null) {\n firstCodeAttribute.putAttributes(symbolTable, code.data, code.length, maxStack, maxLocals, output);\n }\n }\n if (numberOfExceptions > 0) {\n output.putShort(symbolTable.addConstantUtf8(Constants.EXCEPTIONS)).putInt(2 + 2 * numberOfExceptions).putShort(numberOfExceptions);\n for (int exceptionIndex : exceptionIndexTable) {\n output.putShort(exceptionIndex);\n }\n }\n Attribute.putAttributes(symbolTable, accessFlags, signatureIndex, output);\n AnnotationWriter.putAnnotations(symbolTable, lastRuntimeVisibleAnnotation, lastRuntimeInvisibleAnnotation, lastRuntimeVisibleTypeAnnotation, lastRuntimeInvisibleTypeAnnotation, output);\n if (lastRuntimeVisibleParameterAnnotations != null) {\n AnnotationWriter.putParameterAnnotations(symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS), lastRuntimeVisibleParameterAnnotations, visibleAnnotableParameterCount == 0 ? lastRuntimeVisibleParameterAnnotations.length : visibleAnnotableParameterCount, output);\n }\n if (lastRuntimeInvisibleParameterAnnotations != null) {\n AnnotationWriter.putParameterAnnotations(symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS), lastRuntimeInvisibleParameterAnnotations, invisibleAnnotableParameterCount == 0 ? lastRuntimeInvisibleParameterAnnotations.length : invisibleAnnotableParameterCount, output);\n }\n if (defaultValue != null) {\n output.putShort(symbolTable.addConstantUtf8(Constants.ANNOTATION_DEFAULT)).putInt(defaultValue.length).putByteArray(defaultValue.data, 0, defaultValue.length);\n }\n if (parameters != null) {\n output.putShort(symbolTable.addConstantUtf8(Constants.METHOD_PARAMETERS)).putInt(1 + parameters.length).putByte(parametersCount).putByteArray(parameters.data, 0, parameters.length);\n }\n if (firstAttribute != null) {\n firstAttribute.putAttributes(symbolTable, output);\n }\n }\n\n /**\n * Collects the attributes of this method into the given set of attribute prototypes.\n *\n * @param attributePrototypes a set of attribute prototypes.\n */\n final void collectAttributePrototypes(final Attribute.Set attributePrototypes) {\n attributePrototypes.addAttributes(firstAttribute);\n attributePrototypes.addAttributes(firstCodeAttribute);\n }\n}\n", "file_name": "MethodWriter.java", "human_label": "Add the elements indexed from start to end in currentFrame to Frame.", "level": "project_runnable", "lineno": "1732", "name": "putAbstractTypes", "oracle_context": "{ \"apis\" : \"[putAbstractType]\", \"classes\" : \"[]\", \"vars\" : \"[symbolTable, currentFrame, stackMapTableEntries]\" }", "package": "net.hasor.utils.asm", "project": "hasor-master" }, { "_id": "636766801a6d9265ec017482", "all_context": "{ \"class_level\" : \"import java.io.DataInput;\\nimport java.io.DataInputStream;\\nimport java.io.EOFException;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nbyte[] buffer;\\nint size;\\nint pointer;\\nClassFileBuffer();\\nClassFileBuffer(int initialCapacity);\\nseek(int position);\\nsize();\\nreadFully(byte bytes);\\nreadFully(byte bytes,int offset,int length);\\nskipBytes(int n);\\nreadByte();\\nreadBoolean();\\nreadUnsignedByte();\\nreadUnsignedShort();\\nreadShort();\\nreadChar();\\nreadInt();\\nreadLong();\\nreadFloat();\\nreadDouble();\\nreadLine();\\nreadUTF();\\nread();\\nresizeIfNeeded();\\ndestroy();\\n\", \"repo_level\" : \"\" }", "class_name": "ClassFileBuffer", "code": "public void readFrom(final InputStream in) throws IOException {\n pointer=0;\n size=0;\n int n;\n do {\n n=in.read(buffer,size,buffer.length - size);\n if (n > 0) {\n size+=n;\n }\n resizeIfNeeded();\n }\n while (n >= 0);\n}\n", "docstring": "/** \n * Clear and fill the buffer of this {@code ClassFileBuffer} with thesupplied byte stream. The read pointer is reset to the start of the byte array.\n */\n", "end_lineno": "100", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n *//* ClassFileBuffer.java\n * \n ******************************************************************************\n *\n * Created: Oct 10, 2011\n * Character encoding: UTF-8\n * \n * Copyright (c) 2011 - XIAM Solutions B.V. The Netherlands, http://www.xiam.nl\n * \n ********************************* LICENSE ************************************\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.atmosphere.util.annotation;\n\nimport java.io.DataInput;\nimport java.io.DataInputStream;\nimport java.io.EOFException;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/**\n * {@code ClassFileBuffer} is used by {@link eu.infomas.annotation.AnnotationDetector} to efficiently\n * read Java ClassFile files from an {@link java.io.InputStream} and parse the content\n * via the {@link java.io.DataInput} interface.\n *
\n * Note that Java ClassFile files can grow really big,\n * {@code com.sun.corba.se.impl.logging.ORBUtilSystemException} is 128.2 kb!\n *\n * @author Ronald K. Muller\n * @since annotation-detector 3.0.0\n */\nfinal class ClassFileBuffer implements DataInput {\n\n private byte[] buffer;\n private int size; // the number of significant bytes read\n private int pointer; // the \"read pointer\"\n\n /**\n * Create a new, empty {@code ClassFileBuffer} with the default initial capacity (8 kb).\n */\n ClassFileBuffer() {\n this(8 * 1024);\n }\n\n /**\n * Create a new, empty {@code ClassFileBuffer} with the specified initial capacity.\n * The initial capacity must be greater than zero. The internal buffer will grow\n * automatically when a higher capacity is required. However, buffer resizing occurs\n * extra overhead. So in good initial capacity is important in performance critical\n * situations.\n */\n ClassFileBuffer(final int initialCapacity) {\n if (initialCapacity < 1) {\n throw new IllegalArgumentException(\"initialCapacity < 1: \" + initialCapacity);\n }\n this.buffer = new byte[initialCapacity];\n }\n\n /**\n * Clear and fill the buffer of this {@code ClassFileBuffer} with the\n * supplied byte stream.\n * The read pointer is reset to the start of the byte array.\n */\n public void readFrom(final InputStream in) throws IOException {\n pointer = 0;\n size = 0;\n int n;\n do {\n n = in.read(buffer, size, buffer.length - size);\n if (n > 0) {\n size += n;\n }\n resizeIfNeeded();\n } while (n >= 0);\n }\n\n /**\n * Sets the file-pointer offset, measured from the beginning of this file,\n * at which the next read or write occurs.\n */\n public void seek(final int position) throws IOException {\n if (position < 0) {\n throw new IllegalArgumentException(\"position < 0: \" + position);\n }\n if (position > size) {\n throw new EOFException();\n }\n this.pointer = position;\n }\n\n /**\n * Return the size (in bytes) of this Java ClassFile file.\n */\n public int size() {\n return size;\n }\n\n // DataInput\n\n @Override\n public void readFully(final byte bytes[]) throws IOException {\n readFully(bytes, 0, bytes.length);\n }\n\n @Override\n public void readFully(final byte bytes[], final int offset, final int length) throws IOException {\n if (length < 0 || offset < 0 || offset + length > bytes.length) {\n throw new IndexOutOfBoundsException();\n }\n if (pointer + length > size) {\n throw new EOFException();\n }\n System.arraycopy(buffer, pointer, bytes, offset, length);\n pointer += length;\n }\n\n @Override\n public int skipBytes(final int n) throws IOException {\n seek(pointer + n);\n return n;\n }\n\n @Override\n public byte readByte() throws IOException {\n if (pointer >= size) {\n throw new EOFException();\n }\n return buffer[pointer++];\n }\n\n @Override\n public boolean readBoolean() throws IOException {\n return readByte() != 0;\n }\n\n @Override\n public int readUnsignedByte() throws IOException {\n if (pointer >= size) {\n throw new EOFException();\n }\n return read();\n }\n\n @Override\n public int readUnsignedShort() throws IOException {\n if (pointer + 2 > size) {\n throw new EOFException();\n }\n return (read() << 8) + read();\n }\n\n @Override\n public short readShort() throws IOException {\n return (short) readUnsignedShort();\n }\n\n @Override\n public char readChar() throws IOException {\n return (char) readUnsignedShort();\n }\n\n @Override\n public int readInt() throws IOException {\n if (pointer + 4 > size) {\n throw new EOFException();\n }\n return (read() << 24) +\n (read() << 16) +\n (read() << 8) +\n read();\n }\n\n @Override\n public long readLong() throws IOException {\n if (pointer + 8 > size) {\n throw new EOFException();\n }\n return (read() << 56) +\n (read() << 48) +\n (read() << 40) +\n (read() << 32) +\n (read() << 24) +\n (read() << 16) +\n (read() << 8) +\n read();\n }\n\n @Override\n public float readFloat() throws IOException {\n return Float.intBitsToFloat(readInt());\n }\n\n @Override\n public double readDouble() throws IOException {\n return Double.longBitsToDouble(readLong());\n }\n\n /**\n * This methods throws an {@link UnsupportedOperationException} because the method\n * is deprecated and not used in the context of this implementation.\n */\n @Override\n @Deprecated\n public String readLine() throws IOException {\n throw new UnsupportedOperationException(\"readLine() is deprecated and not supported\");\n }\n\n @Override\n public String readUTF() throws IOException {\n return DataInputStream.readUTF(this);\n }\n\n // private\n\n private int read() {\n return buffer[pointer++] & 0xff;\n }\n\n private void resizeIfNeeded() {\n if (size >= buffer.length) {\n final byte[] newBuffer = new byte[buffer.length * 2];\n System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);\n buffer = newBuffer;\n }\n }\n\n public void destroy() {\n buffer = null;\n }\n}\n", "file_name": "ClassFileBuffer.java", "human_label": "Read from the buffer.", "level": "class_runnable", "lineno": "84", "name": "readFrom", "oracle_context": "{ \"apis\" : \"[read, resizeIfNeeded, size]\", \"classes\" : \"[buffer]\", \"vars\" : \"[length, pointer, size, buffer]\" }", "package": "org.atmosphere.util.annotation", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "6367670a1a6d9265ec0179d8", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.io.OutputStream;\\nimport java.io.Writer;\\nWriter writer;\\nString encoding;\\nbyte[] buf;\\nWriterOutputStream(Writer writer,String encoding);\\nWriterOutputStream(Writer writer);\\nflush();\\nwrite(byte[] b);\\nwrite(byte[] b,int off,int len);\\nwrite(int b);\\nclose();\\n\", \"repo_level\" : \"\" }", "class_name": "WriterOutputStream", "code": "@Override public void write(final byte[] b) throws IOException {\n if (this.encoding == null) {\n this.writer.write(new String(b));\n }\n else {\n this.writer.write(new String(b,this.encoding));\n }\n}\n", "docstring": "/** \n * @see OutputStream#write(byte[]) \n */\n", "end_lineno": "73", "file_content": "/*\n * Copyright 2008-2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.io.output;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.Writer;\n\n/**\n * 使用OutputStream输出Writer的工具类\n * @version 2009-5-13\n * @author 网络收集\n */\npublic class WriterOutputStream extends OutputStream {\n private Writer writer = null;\n private String encoding = null;\n private byte[] buf = new byte[1];\n //========================================================================================\n\n /**\n * 带Writer和字符编码格式参数的构造函数\n * @param writer - OutputStream使用的Reader\n * @param encoding - OutputStream使用的字符编码格式。\n */\n public WriterOutputStream(final Writer writer, final String encoding) {\n this.writer = writer;\n this.encoding = encoding;\n }\n\n /**\n * 带Writer参数构造函数\n * @param writer - OutputStream使用的Writer\n */\n public WriterOutputStream(final Writer writer) {\n this.writer = writer;\n }\n //========================================================================================\n\n /** @see OutputStream#close() */\n @Override\n public void close() throws IOException {\n this.writer.close();\n this.writer = null;\n this.encoding = null;\n }\n\n /** @see OutputStream#flush() */\n @Override\n public void flush() throws IOException {\n this.writer.flush();\n }\n\n /** @see OutputStream#write(byte[]) */\n @Override\n public void write(final byte[] b) throws IOException {\n if (this.encoding == null) {\n this.writer.write(new String(b));\n } else {\n this.writer.write(new String(b, this.encoding));\n }\n }\n\n /** @see OutputStream#write(byte[], int, int) */\n @Override\n public void write(final byte[] b, final int off, final int len) throws IOException {\n if (this.encoding == null) {\n this.writer.write(new String(b, off, len));\n } else {\n this.writer.write(new String(b, off, len, this.encoding));\n }\n }\n\n /** @see OutputStream#write(int) */\n @Override\n public synchronized void write(final int b) throws IOException {\n this.buf[0] = (byte) b;\n this.write(this.buf);\n }\n}\n", "file_name": "WriterOutputStream.java", "human_label": "Write the byte array b to the buffer based on the encoding.", "level": "class_runnable", "lineno": "65", "name": "write", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[encoding, writer]\" }", "package": "net.hasor.utils.io.output", "project": "hasor-master" }, { "_id": "636766a81a6d9265ec01757b", "all_context": "{ \"class_level\" : \"import com.alibaba.fastjson2.reader.ObjectReader;\\nimport com.alibaba.fastjson2.reader.ObjectReaderImplEnum;\\nimport com.alibaba.fastjson2.reader.ObjectReaderProvider;\\nimport com.alibaba.fastjson2.schema.JSONSchema;\\nimport com.alibaba.fastjson2.util.DateUtils;\\nimport com.alibaba.fastjson2.util.Fnv;\\nimport com.alibaba.fastjson2.util.IOUtils;\\nimport com.alibaba.fastjson2.util.TypeUtils;\\nimport com.alibaba.fastjson2.writer.ObjectWriter;\\nimport com.alibaba.fastjson2.writer.ObjectWriterAdapter;\\nimport java.lang.reflect.Array;\\nimport java.lang.reflect.Type;\\nimport java.math.BigDecimal;\\nimport java.math.BigInteger;\\nimport java.time.Instant;\\nimport java.util.*;\\nimport java.util.function.Function;\\nimport static com.alibaba.fastjson2.JSONObject.NONE_DIRECT_FEATURES;\\nimport static com.alibaba.fastjson2.JSONWriter.Feature.*;\\nlong serialVersionUID;\\nObjectWriter arrayWriter;\\nJSONArray();\\nJSONArray(int initialCapacity);\\nJSONArray(Collection collection);\\nJSONArray(Object items);\\nset(int index,Object element);\\ngetJSONArray(int index);\\ngetJSONObject(int index);\\ngetString(int index);\\ngetDouble(int index);\\ngetDoubleValue(int index);\\ngetFloat(int index);\\ngetFloatValue(int index);\\ngetLong(int index);\\ngetLongValue(int index);\\ngetInteger(int index);\\ngetIntValue(int index);\\ngetShort(int index);\\ngetShortValue(int index);\\ngetByte(int index);\\ngetByteValue(int index);\\ngetBoolean(int index);\\ngetBooleanValue(int index);\\ngetBigInteger(int index);\\ngetBigDecimal(int index);\\ngetDate(int index);\\ngetInstant(int index);\\ntoString(Feature features);\\ntoJSONString(Feature features);\\ntoJSONString(Object object,Feature features);\\ntoJSONBBytes(Feature features);\\nto(Type type);\\nto(Class type);\\ntoJavaObject(Type type);\\ntoList(Class itemClass,Feature features);\\ntoArray(Class itemClass,Feature features);\\ntoJavaList(Class clazz,Feature features);\\ngetObject(int index,Type type,Feature features);\\ngetObject(int index,Class type,Feature features);\\ngetObject(int index,Function creator);\\nfluentAdd(Object element);\\nfluentClear();\\nfluentRemove(int index);\\nfluentSet(int index,Object element);\\nfluentRemove(Object o);\\nfluentRemoveAll(Collection c);\\nfluentAddAll(Collection c);\\nisValid(JSONSchema schema);\\nclone();\\nof(Object items);\\nof(Object item);\\nof(Object first,Object second);\\nof(Object first,Object second,Object third);\\nparseArray(String text,Feature features);\\nparse(String text,Feature features);\\ntoString();\\n\", \"repo_level\" : \"public interface ObjectReader {default T createInstance();\\ndefault T createInstance(long features);\\ndefault T createInstance(Collection collection);\\ndefault T createInstance(Map map,Feature features);\\ndefault T createInstance(Map map,long features);\\ndefault T createInstanceNoneDefaultConstructor(Map values);\\ndefault long getFeatures();\\ndefault String getTypeKey();\\ndefault long getTypeKeyHash();\\ndefault Class getObjectClass();\\ndefault FieldReader getFieldReader(long hashCode);\\ndefault FieldReader getFieldReaderLCase(long hashCode);\\ndefault boolean setFieldValue(Object object,String fieldName,long fieldNameHashCode,int value);\\ndefault boolean setFieldValue(Object object,String fieldName,long fieldNameHashCode,long value);\\ndefault FieldReader getFieldReader(String fieldName);\\ndefault Function getBuildFunction();\\ndefault ObjectReader autoType(Context context,long typeHash);\\ndefault ObjectReader autoType(ObjectReaderProvider provider,long typeHash);\\ndefault T readJSONBObject(JSONReader jsonReader,Type fieldType,Object fieldName,long features);\\ndefault T readArrayMappingJSONBObject(JSONReader jsonReader,Type fieldType,Object fieldName,long features);\\ndefault T readArrayMappingObject(JSONReader jsonReader,Type fieldType,Object fieldName,long features);\\ndefault T readObject(JSONReader jsonReader);\\ndefault T readObject(JSONReader jsonReader,long features);\\n T readObject(JSONReader jsonReader,Type fieldType,Object fieldName,long features);\\n }\\npublic interface ObjectReaderImplEnum {public Class getObjectClass();\\npublic Enum getEnumByHashCode(long hashCode);\\npublic Enum getEnumByOrdinal(int ordinal);\\npublic Object readJSONBObject(JSONReader jsonReader,Type fieldType,Object fieldName,long features);\\npublic Object readObject(JSONReader jsonReader,Type fieldType,Object fieldName,long features);\\n }\\npublic interface ObjectReaderProvider {public void registerIfAbsent(long hashCode,ObjectReader objectReader);\\npublic void addAutoTypeAccept(String name);\\npublic Consumer getAutoTypeHandler();\\npublic void setAutoTypeHandler(Consumer autoTypeHandler);\\npublic Class getMixIn(Class target);\\npublic void mixIn(Class target,Class mixinSource);\\npublic ObjectReader register(Type type,ObjectReader objectReader);\\npublic ObjectReader registerIfAbsent(Type type,ObjectReader objectReader);\\npublic ObjectReader unregisterObjectReader(Type type);\\npublic boolean unregisterObjectReader(Type type,ObjectReader reader);\\npublic boolean register(ObjectReaderModule module);\\npublic boolean unregister(ObjectReaderModule module);\\npublic void cleanup(Class objectClass);\\npublic void cleanup(ClassLoader classLoader);\\npublic ObjectReaderCreator getCreator();\\n void init();\\npublic Function getTypeConvert(Type from,Type to);\\npublic Function registerTypeConvert(Type from,Type to,Function typeConvert);\\npublic ObjectReader getObjectReader(long hashCode);\\npublic ObjectReader getObjectReader(String typeName,Class expectClass,long features);\\nfinal void afterAutoType(String typeName,Class type);\\npublic Class checkAutoType(String typeName,Class expectClass,long features);\\npublic List getModules();\\npublic ObjectReader getObjectReader(Type objectType);\\npublic ObjectReader getObjectReader(Type objectType,boolean fieldBased);\\npublic AutoTypeBeforeHandler getAutoTypeBeforeHandler();\\npublic Map getAutoTypeList();\\npublic void setAutoTypeBeforeHandler(AutoTypeBeforeHandler autoTypeBeforeHandler);\\nprotected boolean removeEldestEntry(Map.Entry eldest);\\n }\\npublic interface JSONSchema {static JSONSchema of(JSONObject input,Class objectClass);\\nstatic Not ofNot(JSONObject input,Class objectClass);\\nstatic JSONSchema parseSchema(String schema);\\nstatic JSONSchema of(JSONObject input);\\nstatic JSONSchema of(JSONObject input,JSONSchema parent);\\nstatic AnyOf anyOf(JSONObject input,Class type);\\nstatic AnyOf anyOf(JSONArray array,Class type);\\nstatic AllOf allOf(JSONObject input,Class type);\\nstatic OneOf oneOf(JSONObject input,Class type);\\nstatic OneOf oneOf(JSONArray array,Class type);\\npublic String getTitle();\\npublic String getDescription();\\nabstract Type getType();\\nabstract ValidateResult validate(Object value);\\npublic boolean isValid(Object value);\\npublic boolean isValid(long value);\\npublic boolean isValid(double value);\\npublic boolean isValid(Double value);\\npublic boolean isValid(float value);\\npublic boolean isValid(Float value);\\npublic boolean isValid(Integer value);\\npublic boolean isValid(Long value);\\npublic ValidateResult validate(long value);\\npublic ValidateResult validate(double value);\\npublic ValidateResult validate(Float value);\\npublic ValidateResult validate(Double value);\\npublic ValidateResult validate(Integer value);\\npublic ValidateResult validate(Long value);\\npublic void assertValidate(Object value);\\npublic void assertValidate(Integer value);\\npublic void assertValidate(Long value);\\npublic void assertValidate(Double value);\\npublic void assertValidate(Float value);\\npublic void assertValidate(long value);\\npublic void assertValidate(double value);\\nstatic Type of(String typeStr);\\n }\\npublic interface DateUtils {static Date parseDate(String str);\\nstatic LocalDateTime parseLocalDateTime(String str);\\nstatic LocalDateTime parseLocalDateTime(String str,int off,int len);\\nstatic LocalDate parseLocalDate(String str);\\nstatic LocalDate parseLocalDate(String str,int off,int len);\\nstatic LocalDate parseLocalDate8(String str,int off);\\nstatic LocalDate parseLocalDate9(String str,int off);\\nstatic LocalDate parseLocalDate10(String str,int off);\\nstatic LocalDate parseLocalDate11(String str,int off);\\nstatic LocalDateTime parseLocalDateTime12(String str,int off);\\nstatic LocalDateTime parseLocalDateTime14(String str,int off);\\nstatic LocalDateTime parseLocalDateTime16(String str,int off);\\nstatic LocalDateTime parseLocalDateTime17(String str,int off);\\nstatic LocalDateTime parseLocalDateTime18(String str,int off);\\nstatic LocalDateTime parseLocalDateTime19(String str,int off);\\nstatic LocalDateTime parseLocalDateTimeX(String str,int offset,int len);\\nstatic ZonedDateTime parseZonedDateTime(String str);\\nstatic ZonedDateTime parseZonedDateTime(String str,int offset,int len);\\nstatic ZonedDateTime parseZonedDateTime(String str,int offset,int len,ZoneId defaultZoneId);\\nstatic ZoneId getZoneId(String zoneIdStr,ZoneId defaultZoneId);\\nstatic long toMillis19(String str,int off,ZoneId zoneId);\\nstatic LocalDateTime localDateTime(char y0,char y1,char y2,char y3,char m0,char m1,char d0,char d1,char h0,char h1,char i0,char i1,char s0,char s1,char S0,char S1,char S2,char S3,char S4,char S5,char S6,char S7,char S8);\\nstatic long millis(ZoneId zoneId,int year,int month,int dom,int hour,int minute,int second,int nanoOfSecond);\\nstatic long utcSeconds(int year,int month,int dom,int hour,int minute,int second);\\nstatic String toString(Date date);\\nstatic String toString(long timeMillis,boolean timeZone,ZoneId zoneId);\\n }\\npublic interface Fnv {static long hashCode64LCase(String name);\\nstatic long hashCode64(String name);\\nstatic long hashCode64(byte name);\\n }\\npublic interface IOUtils {static int stringSize(int x);\\nstatic int stringSize(long x);\\nstatic void getChars(int i,int index,byte[] buf);\\nstatic void getChars(int i,int index,char[] buf);\\nstatic void getChars(long i,int index,byte[] buf);\\nstatic void getChars(long i,int index,char[] buf);\\nstatic int encodeUTF8(byte[] src,int offset,int len,byte[] dst,int dp);\\nstatic int encodeUTF8(char[] src,int offset,int len,byte[] dst,int dp);\\nstatic boolean isNumber(String str);\\nstatic void close(Closeable x);\\nstatic int decodeUTF8(byte[] src,int off,int len,byte[] dst);\\nstatic int decodeUTF8(byte[] src,int off,int len,char[] dst);\\nstatic int getShanghaiZoneOffsetTotalSeconds(long seconds);\\n }\\npublic interface TypeUtils {static Class getMapping(Type type);\\nstatic Date toDate(Object obj);\\nstatic Instant toInstant(Object obj);\\nstatic T cast(Object obj,Type type);\\nstatic T cast(Object obj,Class targetClass);\\nstatic T cast(Object obj,Class targetClass,ObjectReaderProvider provider);\\nstatic String getTypeName(Class type);\\nstatic Class getMapping(String typeName);\\nstatic BigDecimal toBigDecimal(Object value);\\nstatic BigInteger toBigInteger(Object value);\\nstatic Long toLong(Object value);\\nstatic long toLongValue(Object value);\\nstatic Integer toInteger(Object value);\\nstatic Byte toByte(Object value);\\nstatic byte toByteValue(Object value);\\nstatic Short toShort(Object value);\\nstatic short toShortValue(Object value);\\nstatic int toIntValue(Object value);\\nstatic boolean toBooleanValue(Object value);\\nstatic Boolean toBoolean(Object value);\\nstatic float toFloatValue(Object value);\\nstatic Float toFloat(Object value);\\nstatic double toDoubleValue(Object value);\\nstatic Double toDouble(Object value);\\nstatic int compare(Object a,Object b);\\nstatic Object getDefaultValue(Type paramType);\\nstatic Class loadClass(String className);\\nstatic Class getArrayClass(Class componentClass);\\nstatic Class getClass(Type type);\\nstatic boolean isProxy(Class clazz);\\nstatic Map getInnerMap(Map object);\\n }\\npublic interface ObjectWriter {default long getFeatures();\\ndefault List getFieldWriters();\\ndefault FieldWriter getFieldWriter(long hashCode);\\ndefault FieldWriter getFieldWriter(String name);\\ndefault boolean writeTypeInfo(JSONWriter jsonWriter);\\ndefault void writeJSONB(JSONWriter jsonWriter,Object object,Object fieldName,Type fieldType,long features);\\ndefault void writeArrayMappingJSONB(JSONWriter jsonWriter,Object object);\\ndefault void writeArrayMappingJSONB(JSONWriter jsonWriter,Object object,Object fieldName,Type fieldType,long features);\\ndefault void writeArrayMapping(JSONWriter jsonWriter,Object object,Object fieldName,Type fieldType,long features);\\ndefault boolean hasFilter(JSONWriter jsonWriter);\\ndefault void write(JSONWriter jsonWriter,Object object);\\n void write(JSONWriter jsonWriter,Object object,Object fieldName,Type fieldType,long features);\\ndefault void writeWithFilter(JSONWriter jsonWriter,Object object);\\ndefault void writeWithFilter(JSONWriter jsonWriter,Object object,Object fieldName,Type fieldType,long features);\\n }\\npublic interface ObjectWriterAdapter {public long getFeatures();\\npublic FieldWriter getFieldWriter(long hashCode);\\nfinal boolean hasFilter(JSONWriter jsonWriter);\\npublic void setPropertyFilter(PropertyFilter propertyFilter);\\npublic void setValueFilter(ValueFilter valueFilter);\\npublic void setNameFilter(NameFilter nameFilter);\\npublic void setPropertyPreFilter(PropertyPreFilter propertyPreFilter);\\npublic void writeArrayMappingJSONB(JSONWriter jsonWriter,Object object,Object fieldName,Type fieldType,long features);\\npublic void writeJSONB(JSONWriter jsonWriter,Object object,Object fieldName,Type fieldType,long features);\\nprotected void writeClassInfo(JSONWriter jsonWriter);\\npublic void write(JSONWriter jsonWriter,Object object,Object fieldName,Type fieldType,long features);\\npublic Map toMap(Object object);\\npublic List getFieldWriters();\\npublic boolean writeTypeInfo(JSONWriter jsonWriter);\\npublic void writeWithFilter(JSONWriter jsonWriter,Object object,Object fieldName,Type fieldType,long features);\\npublic JSONObject toJSONObject(T object);\\npublic String toString();\\nprotected void errorOnNoneSerializable();\\n }\\n\" }", "class_name": "JSONArray", "code": "@SuppressWarnings(\"unchecked\") public String toString(JSONWriter.Feature... features){\n try (JSONWriter writer=JSONWriter.of(features)){\n if ((writer.context.features & NONE_DIRECT_FEATURES) == 0) {\n writer.write(this);\n }\n else {\n writer.setRootObject(this);\n if (arrayWriter == null) {\n arrayWriter=writer.getObjectWriter(JSONArray.class,JSONArray.class);\n }\n arrayWriter.write(writer,this,null,null,0);\n }\n return writer.toString();\n }\n }\n", "docstring": "/** \n * Serialize to JSON {@link String}\n * @param features features to be enabled in serialization\n * @return JSON {@link String}\n */\n", "end_lineno": "912", "file_content": "package com.alibaba.fastjson2;\n\nimport com.alibaba.fastjson2.reader.ObjectReader;\nimport com.alibaba.fastjson2.reader.ObjectReaderImplEnum;\nimport com.alibaba.fastjson2.reader.ObjectReaderProvider;\nimport com.alibaba.fastjson2.schema.JSONSchema;\nimport com.alibaba.fastjson2.util.DateUtils;\nimport com.alibaba.fastjson2.util.Fnv;\nimport com.alibaba.fastjson2.util.IOUtils;\nimport com.alibaba.fastjson2.util.TypeUtils;\nimport com.alibaba.fastjson2.writer.ObjectWriter;\nimport com.alibaba.fastjson2.writer.ObjectWriterAdapter;\n\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Type;\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.time.Instant;\nimport java.util.*;\nimport java.util.function.Function;\n\nimport static com.alibaba.fastjson2.JSONObject.NONE_DIRECT_FEATURES;\nimport static com.alibaba.fastjson2.JSONWriter.Feature.*;\n\npublic class JSONArray\n extends ArrayList {\n private static final long serialVersionUID = 1L;\n\n static ObjectWriter arrayWriter;\n\n /**\n * default\n */\n public JSONArray() {\n super();\n }\n\n /**\n * @param initialCapacity the initial capacity of the {@link JSONArray}\n * @throws IllegalArgumentException If the specified initial capacity is negative\n */\n public JSONArray(int initialCapacity) {\n super(initialCapacity);\n }\n\n /**\n * @param collection the collection whose elements are to be placed into this {@link JSONArray}\n * @throws NullPointerException If the specified collection is null\n */\n public JSONArray(Collection collection) {\n super(collection);\n }\n\n /**\n * @param items the array whose elements are to be placed into this {@link JSONArray}\n * @throws NullPointerException If the specified items is null\n */\n public JSONArray(Object... items) {\n super(items.length);\n for (Object item : items) {\n super.add(item);\n }\n }\n\n /**\n * Replaces the element at the specified position with the specified element\n *\n *
{@code\n     *    JSONArray array = new JSONArray();\n     *    array.add(-1); // [-1]\n     *    array.add(2); // [-1,2]\n     *    array.set(0, 1); // [1,2]\n     *    array.set(4, 3); // [1,2,null,null,3]\n     *    array.set(-1, -1); // [1,2,null,null,-1]\n     *    array.set(-2, -2); // [1,2,null,-2,-1]\n     *    array.set(-6, -6); // [-6,1,2,null,-2,-1]\n     * }
\n *\n * @param index index of the element to replace\n * @param element element to be stored at the specified position\n * @return the element previously at the specified position\n * @since 2.0.3\n */\n @Override\n public Object set(int index, Object element) {\n int size = super.size();\n if (index < 0) {\n index += size;\n if (index < 0) {\n // left join elem\n super.add(0, element);\n return null;\n }\n return super.set(\n index, element\n );\n }\n\n if (index < size) {\n return super.set(\n index, element\n );\n }\n\n // max expansion (size + 4096)\n if (index < size + 4096) {\n while (index-- != size) {\n super.add(null);\n }\n super.add(element);\n }\n return null;\n }\n\n /**\n * Returns the {@link JSONArray} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link JSONArray} or null\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public JSONArray getJSONArray(int index) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n if (value instanceof JSONArray) {\n return (JSONArray) value;\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return null;\n }\n\n JSONReader reader = JSONReader.of(str);\n return JSONFactory.ARRAY_READER.readObject(reader, null, null, 0);\n }\n\n if (value instanceof Collection) {\n return new JSONArray((Collection) value);\n }\n\n if (value instanceof Object[]) {\n return JSONArray.of((Object[]) value);\n }\n\n Class valueClass = value.getClass();\n if (valueClass.isArray()) {\n int length = Array.getLength(value);\n JSONArray jsonArray = new JSONArray(length);\n for (int i = 0; i < length; i++) {\n Object item = Array.get(value, i);\n jsonArray.add(item);\n }\n return jsonArray;\n }\n\n return null;\n }\n\n /**\n * Returns the {@link JSONObject} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link JSONObject} or null\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n @SuppressWarnings({\"unchecked\", \"rawtypes\"})\n public JSONObject getJSONObject(int index) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n if (value instanceof JSONObject) {\n return (JSONObject) value;\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return null;\n }\n\n JSONReader reader = JSONReader.of(str);\n return JSONFactory.OBJECT_READER.readObject(reader, null, null, 0);\n }\n\n if (value instanceof Map) {\n return new JSONObject((Map) value);\n }\n\n Class valueClass = value.getClass();\n ObjectWriter objectWriter = JSONFactory.getDefaultObjectWriterProvider().getObjectWriter(valueClass);\n if (objectWriter instanceof ObjectWriterAdapter) {\n ObjectWriterAdapter writerAdapter = (ObjectWriterAdapter) objectWriter;\n return writerAdapter.toJSONObject(value);\n }\n\n return null;\n }\n\n /**\n * Returns the {@link String} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link String} or null\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public String getString(int index) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n if (value instanceof String) {\n return (String) value;\n }\n\n if (value instanceof Date) {\n long timeMillis = ((Date) value).getTime();\n return DateUtils.toString(timeMillis, false, IOUtils.DEFAULT_ZONE_ID);\n }\n\n if (value instanceof Boolean\n || value instanceof Character\n || value instanceof Number\n || value instanceof UUID\n || value instanceof Enum) {\n return value.toString();\n }\n\n return JSON.toJSONString(value);\n }\n\n /**\n * Returns the {@link Double} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link Double} or null\n * @throws NumberFormatException If the value of get is {@link String} and it contains no parsable double\n * @throws JSONException Unsupported type conversion to {@link Double}\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public Double getDouble(int index) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n if (value instanceof Double) {\n return (Double) value;\n }\n\n if (value instanceof Number) {\n return ((Number) value).doubleValue();\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return null;\n }\n\n return Double.parseDouble(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to Double\");\n }\n\n /**\n * Returns a double value at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return double\n * @throws NumberFormatException If the value of get is {@link String} and it contains no parsable double\n * @throws JSONException Unsupported type conversion to double value\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public double getDoubleValue(int index) {\n Object value = get(index);\n\n if (value == null) {\n return 0D;\n }\n\n if (value instanceof Number) {\n return ((Number) value).doubleValue();\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return 0D;\n }\n\n return Double.parseDouble(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to double value\");\n }\n\n /**\n * Returns the {@link Float} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link Float} or null\n * @throws NumberFormatException If the value of get is {@link String} and it contains no parsable float\n * @throws JSONException Unsupported type conversion to {@link Float}\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public Float getFloat(int index) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n if (value instanceof Float) {\n return (Float) value;\n }\n\n if (value instanceof Number) {\n return ((Number) value).floatValue();\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return null;\n }\n\n return Float.parseFloat(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to Float\");\n }\n\n /**\n * Returns a float value at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return float\n * @throws NumberFormatException If the value of get is {@link String} and it contains no parsable float\n * @throws JSONException Unsupported type conversion to float value\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public float getFloatValue(int index) {\n Object value = get(index);\n\n if (value == null) {\n return 0F;\n }\n\n if (value instanceof Number) {\n return ((Number) value).floatValue();\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return 0F;\n }\n\n return Float.parseFloat(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to float value\");\n }\n\n /**\n * Returns the {@link Long} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link Long} or null\n * @throws NumberFormatException If the value of get is {@link String} and it contains no parsable long\n * @throws JSONException Unsupported type conversion to {@link Long}\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public Long getLong(int index) {\n Object value = get(index);\n if (value == null) {\n return null;\n }\n\n if (value instanceof Long) {\n return ((Long) value);\n }\n\n if (value instanceof Number) {\n return ((Number) value).longValue();\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return null;\n }\n\n return Long.parseLong(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to Long\");\n }\n\n /**\n * Returns a long value at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return long\n * @throws NumberFormatException If the value of get is {@link String} and it contains no parsable long\n * @throws JSONException Unsupported type conversion to long value\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public long getLongValue(int index) {\n Object value = get(index);\n\n if (value == null) {\n return 0;\n }\n\n if (value instanceof Number) {\n return ((Number) value).longValue();\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return 0;\n }\n\n return Long.parseLong(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to long value\");\n }\n\n /**\n * Returns the {@link Integer} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link Integer} or null\n * @throws NumberFormatException If the value of get is {@link String} and it contains no parsable int\n * @throws JSONException Unsupported type conversion to {@link Integer}\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public Integer getInteger(int index) {\n Object value = get(index);\n if (value == null) {\n return null;\n }\n\n if (value instanceof Integer) {\n return ((Integer) value);\n }\n\n if (value instanceof Number) {\n return ((Number) value).intValue();\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return null;\n }\n\n return Integer.parseInt(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to Integer\");\n }\n\n /**\n * Returns an int value at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return int\n * @throws NumberFormatException If the value of get is {@link String} and it contains no parsable int\n * @throws JSONException Unsupported type conversion to int value\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public int getIntValue(int index) {\n Object value = get(index);\n\n if (value == null) {\n return 0;\n }\n\n if (value instanceof Number) {\n return ((Number) value).intValue();\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return 0;\n }\n\n return Integer.parseInt(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to int value\");\n }\n\n /**\n * Returns the {@link Short} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link Short} or null\n * @throws NumberFormatException If the value of get is {@link String} and it contains no parsable short\n * @throws JSONException Unsupported type conversion to {@link Short}\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public Short getShort(int index) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n if (value instanceof Short) {\n return (Short) value;\n }\n\n if (value instanceof Number) {\n return ((Number) value).shortValue();\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return null;\n }\n\n return Short.parseShort(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to Short\");\n }\n\n /**\n * Returns a short value at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return short\n * @throws NumberFormatException If the value of get is {@link String} and it contains no parsable short\n * @throws JSONException Unsupported type conversion to short value\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public short getShortValue(int index) {\n Object value = get(index);\n\n if (value == null) {\n return 0;\n }\n\n if (value instanceof Number) {\n return ((Number) value).shortValue();\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return 0;\n }\n\n return Short.parseShort(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to short value\");\n }\n\n /**\n * Returns the {@link Byte} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link Byte} or null\n * @throws NumberFormatException If the value of get is {@link String} and it contains no parsable byte\n * @throws JSONException Unsupported type conversion to {@link Byte}\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public Byte getByte(int index) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n if (value instanceof Number) {\n return ((Number) value).byteValue();\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return null;\n }\n\n return Byte.parseByte(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to Byte\");\n }\n\n /**\n * Returns a byte value at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return byte\n * @throws NumberFormatException If the value of get is {@link String} and it contains no parsable byte\n * @throws JSONException Unsupported type conversion to byte value\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public byte getByteValue(int index) {\n Object value = get(index);\n\n if (value == null) {\n return 0;\n }\n\n if (value instanceof Number) {\n return ((Number) value).byteValue();\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return 0;\n }\n\n return Byte.parseByte(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to byte value\");\n }\n\n /**\n * Returns the {@link Boolean} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link Boolean} or null\n * @throws JSONException Unsupported type conversion to {@link Boolean}\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public Boolean getBoolean(int index) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n if (value instanceof Boolean) {\n return (Boolean) value;\n }\n\n if (value instanceof Number) {\n return ((Number) value).intValue() == 1;\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return null;\n }\n\n return \"true\".equalsIgnoreCase(str) || \"1\".equals(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to Boolean\");\n }\n\n /**\n * Returns a boolean value at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return boolean\n * @throws JSONException Unsupported type conversion to boolean value\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public boolean getBooleanValue(int index) {\n Object value = get(index);\n\n if (value == null) {\n return false;\n }\n\n if (value instanceof Boolean) {\n return (Boolean) value;\n }\n\n if (value instanceof Number) {\n return ((Number) value).intValue() == 1;\n }\n\n if (value instanceof String) {\n String str = (String) value;\n return \"true\".equalsIgnoreCase(str) || \"1\".equals(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to boolean value\");\n }\n\n /**\n * Returns the {@link BigInteger} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link BigInteger} or null\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n * @throws JSONException Unsupported type conversion to {@link BigInteger}\n * @throws NumberFormatException If the value of get is {@link String} and it is not a valid representation of {@link BigInteger}\n */\n public BigInteger getBigInteger(int index) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n if (value instanceof Number) {\n if (value instanceof BigInteger) {\n return (BigInteger) value;\n }\n\n if (value instanceof BigDecimal) {\n return ((BigDecimal) value).toBigInteger();\n }\n\n long longValue = ((Number) value).longValue();\n return BigInteger.valueOf(longValue);\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return null;\n }\n\n return new BigInteger(str);\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to BigInteger\");\n }\n\n /**\n * Returns the {@link BigDecimal} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link BigDecimal} or null\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n * @throws JSONException Unsupported type conversion to {@link BigDecimal}\n * @throws NumberFormatException If the value of get is {@link String} and it is not a valid representation of {@link BigDecimal}\n */\n public BigDecimal getBigDecimal(int index) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n if (value instanceof Number) {\n if (value instanceof BigDecimal) {\n return (BigDecimal) value;\n }\n\n if (value instanceof BigInteger) {\n return new BigDecimal((BigInteger) value);\n }\n\n if (value instanceof Float\n || value instanceof Double) {\n // Floating point number have no cached BigDecimal\n return new BigDecimal(value.toString());\n }\n\n long longValue = ((Number) value).longValue();\n return BigDecimal.valueOf(longValue);\n }\n\n if (value instanceof String) {\n String str = (String) value;\n\n if (str.isEmpty() || \"null\".equalsIgnoreCase(str)) {\n return null;\n }\n\n return new BigDecimal(str);\n }\n\n if (value instanceof Boolean) {\n return (boolean) value ? BigDecimal.ONE : BigDecimal.ZERO;\n }\n\n throw new JSONException(\"Can not cast '\" + value.getClass() + \"' to BigDecimal\");\n }\n\n /**\n * Returns the {@link Date} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link Date} or null\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public Date getDate(int index) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n if (value instanceof Date) {\n return (Date) value;\n }\n\n if (value instanceof Number) {\n long millis = ((Number) value).longValue();\n if (millis == 0) {\n return null;\n }\n return new Date(millis);\n }\n\n return TypeUtils.toDate(value);\n }\n\n /**\n * Returns the {@link Instant} at the specified location in this {@link JSONArray}.\n *\n * @param index index of the element to return\n * @return {@link Instant} or null\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n public Instant getInstant(int index) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n if (value instanceof Instant) {\n return (Instant) value;\n }\n\n if (value instanceof Number) {\n long millis = ((Number) value).longValue();\n if (millis == 0) {\n return null;\n }\n return Instant.ofEpochMilli(millis);\n }\n\n return TypeUtils.toInstant(value);\n }\n\n /**\n * Serialize to JSON {@link String}\n *\n * @return JSON {@link String}\n */\n @Override\n @SuppressWarnings(\"unchecked\")\n public String toString() {\n try (JSONWriter writer = JSONWriter.of()) {\n writer.setRootObject(this);\n writer.write(this);\n return writer.toString();\n }\n }\n\n /**\n * Serialize to JSON {@link String}\n *\n * @param features features to be enabled in serialization\n * @return JSON {@link String}\n */\n @SuppressWarnings(\"unchecked\")\n public String toString(JSONWriter.Feature... features) {\n try (JSONWriter writer = JSONWriter.of(features)) {\n if ((writer.context.features & NONE_DIRECT_FEATURES) == 0) {\n writer.write(this);\n } else {\n writer.setRootObject(this);\n if (arrayWriter == null) {\n arrayWriter = writer.getObjectWriter(JSONArray.class, JSONArray.class);\n }\n arrayWriter.write(writer, this, null, null, 0);\n }\n return writer.toString();\n }\n }\n\n /**\n * Serialize to JSON {@link String}\n *\n * @param features features to be enabled in serialization\n * @return JSON {@link String}\n */\n public String toJSONString(JSONWriter.Feature... features) {\n return toString(features);\n }\n\n /**\n * Serialize Java Object to JSON {@link String} with specified {@link JSONReader.Feature}s enabled\n *\n * @param object Java Object to be serialized into JSON {@link String}\n * @param features features to be enabled in serialization\n * @since 2.0.15\n */\n public static String toJSONString(Object object, JSONWriter.Feature... features) {\n return JSON.toJSONString(object, features);\n }\n\n /**\n * Serialize to JSONB bytes\n *\n * @param features features to be enabled in serialization\n * @return JSONB bytes\n */\n @SuppressWarnings(\"unchecked\")\n public byte[] toJSONBBytes(JSONWriter.Feature... features) {\n try (JSONWriter writer = JSONWriter.ofJSONB(features)) {\n writer.setRootObject(this);\n writer.write(this);\n return writer.getBytes();\n }\n }\n\n /**\n * Convert this {@link JSONArray} to the specified Object\n *\n *
{@code\n     * JSONArray array = ...\n     * List users = array.to(new TypeReference>(){}.getType());\n     * }
\n *\n * @param type specify the {@link Type} to be converted\n * @since 2.0.4\n */\n @SuppressWarnings(\"unchecked\")\n public T to(Type type) {\n if (type == String.class) {\n return (T) toString();\n }\n\n ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();\n ObjectReader objectReader = provider.getObjectReader(type);\n return objectReader.createInstance(this);\n }\n\n /**\n * @since 2.0.9\n */\n @SuppressWarnings(\"unchecked\")\n public T to(Class type) {\n if (type == String.class) {\n return (T) toString();\n }\n\n ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();\n ObjectReader objectReader = provider.getObjectReader(type);\n return objectReader.createInstance(this);\n }\n\n /**\n * Convert this {@link JSONArray} to the specified Object\n *\n * @param type specify the {@link Type} to be converted\n * @deprecated since 2.0.4, please use {@link #to(Type)}\n */\n @Deprecated\n public T toJavaObject(Type type) {\n return to(type);\n }\n\n /**\n * Convert all the members of this {@link JSONArray} into the specified Object.\n *\n *
{@code\n     * String json = \"[{\\\"id\\\": 1, \\\"name\\\": \\\"fastjson\\\"}, {\\\"id\\\": 2, \\\"name\\\": \\\"fastjson2\\\"}]\";\n     * JSONArray array = JSON.parseArray(json);\n     * List users = array.toList(User.class);\n     * }
\n *\n * @param itemClass specify the {@code Class} to be converted\n * @param features features to be enabled in parsing\n * @since 2.0.4\n */\n @SuppressWarnings({\"unchecked\", \"rawtypes\"})\n public List toList(Class itemClass, JSONReader.Feature... features) {\n boolean fieldBased = false;\n long featuresValue = 0;\n for (JSONReader.Feature feature : features) {\n featuresValue |= feature.mask;\n if (feature == JSONReader.Feature.FieldBased) {\n fieldBased = true;\n }\n }\n\n ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();\n ObjectReader objectReader = provider.getObjectReader(itemClass, fieldBased);\n\n List list = new ArrayList<>(size());\n for (int i = 0; i < this.size(); i++) {\n Object item = this.get(i);\n\n T classItem;\n if (item instanceof JSONObject) {\n classItem = (T) objectReader.createInstance((Map) item, featuresValue);\n } else if (item instanceof Map) {\n classItem = (T) objectReader.createInstance((Map) item, featuresValue);\n } else if (item == null || itemClass.isInstance(item)) {\n classItem = (T) item;\n } else {\n Class currentItemClass = item.getClass();\n Function typeConvert = provider.getTypeConvert(currentItemClass, itemClass);\n if (typeConvert != null) {\n Object converted = typeConvert.apply(item);\n list.add((T) converted);\n continue;\n }\n\n throw new JSONException(\n currentItemClass + \" cannot be converted to \" + itemClass\n );\n }\n list.add(classItem);\n }\n\n return list;\n }\n\n /**\n * Convert all the members of this {@link JSONArray} into the specified Object.\n *\n *
{@code\n     * String json = \"[{\\\"id\\\": 1, \\\"name\\\": \\\"fastjson\\\"}, {\\\"id\\\": 2, \\\"name\\\": \\\"fastjson2\\\"}]\";\n     * JSONArray array = JSON.parseArray(json);\n     * List users = array.toList(User.class);\n     * }
\n *\n * @param itemClass specify the {@code Class} to be converted\n * @param features features to be enabled in parsing\n * @since 2.0.4\n */\n @SuppressWarnings({\"unchecked\", \"rawtypes\"})\n public T[] toArray(Class itemClass, JSONReader.Feature... features) {\n boolean fieldBased = false;\n long featuresValue = 0;\n for (JSONReader.Feature feature : features) {\n featuresValue |= feature.mask;\n if (feature == JSONReader.Feature.FieldBased) {\n fieldBased = true;\n }\n }\n\n ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();\n ObjectReader objectReader = provider.getObjectReader(itemClass, fieldBased);\n\n T[] list = (T[]) Array.newInstance(itemClass, size());\n for (int i = 0; i < this.size(); i++) {\n Object item = this.get(i);\n\n T classItem;\n if (item instanceof JSONObject) {\n classItem = (T) objectReader.createInstance((Map) item, featuresValue);\n } else if (item instanceof Map) {\n classItem = (T) objectReader.createInstance((Map) item, featuresValue);\n } else if (item == null || itemClass.isInstance(item)) {\n classItem = (T) item;\n } else {\n Class currentItemClass = item.getClass();\n Function typeConvert = provider.getTypeConvert(currentItemClass, itemClass);\n if (typeConvert != null) {\n Object converted = typeConvert.apply(item);\n list[i] = (T) converted;\n continue;\n }\n\n throw new JSONException(\n currentItemClass + \" cannot be converted to \" + itemClass\n );\n }\n list[i] = classItem;\n }\n\n return list;\n }\n\n /**\n * Convert all the members of this {@link JSONArray} into the specified Object.\n *\n * @param clazz specify the {@code Class} to be converted\n * @param features features to be enabled in parsing\n * please use {@link #toList(Class, JSONReader.Feature...)}\n */\n public List toJavaList(Class clazz, JSONReader.Feature... features) {\n return toList(clazz, features);\n }\n\n /**\n * Returns the result of the {@link Type} converter conversion of the element at the specified position in this {@link JSONArray}.\n *\n *
{@code\n     * JSONArray array = ...\n     * User user = array.getObject(0, TypeReference>(){}.getType());\n     * }
\n *\n * @param index index of the element to return\n * @param type specify the {@link Type} to be converted\n * @return {@code } or null\n * @throws JSONException If no suitable conversion method is found\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n @SuppressWarnings({\"unchecked\", \"rawtypes\"})\n public T getObject(int index, Type type, JSONReader.Feature... features) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n Class valueClass = value.getClass();\n ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();\n Function typeConvert = provider.getTypeConvert(valueClass, type);\n\n if (typeConvert != null) {\n return (T) typeConvert.apply(value);\n }\n\n boolean fieldBased = false;\n long featuresValue = 0;\n for (JSONReader.Feature feature : features) {\n featuresValue |= feature.mask;\n if (feature == JSONReader.Feature.FieldBased) {\n fieldBased = true;\n }\n }\n\n if (value instanceof Map) {\n ObjectReader objectReader = provider.getObjectReader(type, fieldBased);\n return objectReader.createInstance((Map) value, featuresValue);\n }\n\n if (value instanceof Collection) {\n ObjectReader objectReader = provider.getObjectReader(type, fieldBased);\n return objectReader.createInstance((Collection) value);\n }\n\n Class clazz = TypeUtils.getMapping(type);\n if (clazz.isInstance(value)) {\n return (T) value;\n }\n\n String json = JSON.toJSONString(value);\n JSONReader jsonReader = JSONReader.of(json);\n jsonReader.context.config(features);\n\n ObjectReader objectReader = provider.getObjectReader(clazz, fieldBased);\n return (T) objectReader.readObject(jsonReader, null, null, 0);\n }\n\n /**\n * Returns the result of the {@link Type} converter conversion of the element at the specified position in this {@link JSONArray}.\n *

\n * {@code User user = jsonArray.getObject(0, User.class);}\n *\n * @param index index of the element to return\n * @param type specify the {@link Class} to be converted\n * @return {@code } or null\n * @throws JSONException If no suitable conversion method is found\n * @throws IndexOutOfBoundsException if the index is out of range {@code (index < 0 || index >= size())}\n */\n @SuppressWarnings({\"unchecked\", \"rawtypes\"})\n public T getObject(int index, Class type, JSONReader.Feature... features) {\n Object value = get(index);\n\n if (value == null) {\n return null;\n }\n\n Class valueClass = value.getClass();\n ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();\n Function typeConvert = provider.getTypeConvert(valueClass, type);\n\n if (typeConvert != null) {\n return (T) typeConvert.apply(value);\n }\n\n boolean fieldBased = false;\n long featuresValue = 0;\n for (JSONReader.Feature feature : features) {\n featuresValue |= feature.mask;\n if (feature == JSONReader.Feature.FieldBased) {\n fieldBased = true;\n }\n }\n\n if (value instanceof Map) {\n ObjectReader objectReader = provider.getObjectReader(type, fieldBased);\n return objectReader.createInstance((Map) value, featuresValue);\n }\n\n if (value instanceof Collection) {\n ObjectReader objectReader = provider.getObjectReader(type, fieldBased);\n return objectReader.createInstance((Collection) value);\n }\n\n Class clazz = TypeUtils.getMapping(type);\n if (clazz.isInstance(value)) {\n return (T) value;\n }\n\n ObjectReader objectReader = null;\n\n if (value instanceof String) {\n String str = (String) value;\n if (str.isEmpty() || \"null\".equals(str)) {\n return null;\n }\n\n if (clazz.isEnum()) {\n objectReader = provider.getObjectReader(clazz, fieldBased);\n if (objectReader instanceof ObjectReaderImplEnum) {\n long hashCode64 = Fnv.hashCode64(str);\n ObjectReaderImplEnum enumReader = (ObjectReaderImplEnum) objectReader;\n return (T) enumReader.getEnumByHashCode(hashCode64);\n }\n }\n }\n\n String json = JSON.toJSONString(value);\n JSONReader jsonReader = JSONReader.of(json);\n jsonReader.context.config(features);\n\n if (objectReader == null) {\n objectReader = provider.getObjectReader(clazz, fieldBased);\n }\n\n T object = (T) objectReader.readObject(jsonReader, null, null, 0L);\n if (!jsonReader.isEnd()) {\n throw new JSONException(\"not support input \" + json);\n }\n return object;\n }\n\n /**\n * @since 2.0.3\n */\n public T getObject(int index, Function creator) {\n JSONObject object = getJSONObject(index);\n\n if (object == null) {\n return null;\n }\n\n return creator.apply(object);\n }\n\n /**\n * Chained addition of elements\n *\n *

\n     * JSONArray array = new JSONArray().fluentAdd(1).fluentAdd(2).fluentAdd(3);\n     * 
\n *\n * @param element element to be appended to this list\n */\n public JSONArray fluentAdd(Object element) {\n add(element);\n return this;\n }\n\n /**\n * @since 2.0.3\n */\n public JSONArray fluentClear() {\n clear();\n return this;\n }\n\n /**\n * @since 2.0.3\n */\n public JSONArray fluentRemove(int index) {\n remove(index);\n return this;\n }\n\n /**\n * @since 2.0.3\n */\n public JSONArray fluentSet(int index, Object element) {\n set(index, element);\n return this;\n }\n\n /**\n * @since 2.0.3\n */\n public JSONArray fluentRemove(Object o) {\n remove(o);\n return this;\n }\n\n /**\n * @since 2.0.3\n */\n public JSONArray fluentRemoveAll(Collection c) {\n removeAll(c);\n return this;\n }\n\n /**\n * @since 2.0.3\n */\n public JSONArray fluentAddAll(Collection c) {\n addAll(c);\n return this;\n }\n\n /**\n * @since 2.0.3\n */\n public boolean isValid(JSONSchema schema) {\n return schema\n .validate(this)\n .isSuccess();\n }\n\n @Override\n public Object clone() {\n return new JSONArray(this);\n }\n\n /**\n * Pack multiple elements as {@link JSONArray}\n *\n *
\n     * JSONArray array = JSONArray.of(1, 2, \"3\", 4F, 5L, 6D, true);\n     * 
\n *\n * @param items element set\n */\n public static JSONArray of(Object... items) {\n return new JSONArray(items);\n }\n\n /**\n * Pack an element as {@link JSONArray}\n *\n *
\n     * JSONArray array = JSONArray.of(\"fastjson\");\n     * 
\n *\n * @param item target element\n */\n public static JSONArray of(Object item) {\n JSONArray array = new JSONArray(1);\n array.add(item);\n return array;\n }\n\n /**\n * Pack two elements as {@link JSONArray}\n *\n *
\n     * JSONArray array = JSONArray.of(\"fastjson\", 2);\n     * 
\n *\n * @param first first element\n * @param second second element\n */\n public static JSONArray of(Object first, Object second) {\n JSONArray array = new JSONArray(2);\n array.add(first);\n array.add(second);\n return array;\n }\n\n /**\n * Pack three elements as {@link JSONArray}\n *\n *
\n     * JSONArray array = JSONArray.of(\"fastjson\", 2, true);\n     * 
\n *\n * @param first first element\n * @param second second element\n * @param third third element\n */\n public static JSONArray of(Object first, Object second, Object third) {\n JSONArray array = new JSONArray(3);\n array.add(first);\n array.add(second);\n array.add(third);\n return array;\n }\n\n /**\n * Parse JSON {@link String} into {@link JSONArray}\n *\n * @param text the JSON {@link String} to be parsed\n * @param features features to be enabled in parsing\n */\n public static JSONArray parseArray(String text, JSONReader.Feature... features) {\n return JSON.parseArray(text, features);\n }\n\n /**\n * Parse JSON {@link String} into {@link JSONArray}\n *\n * @param text the JSON {@link String} to be parsed\n * @param features features to be enabled in parsing\n * @since 2.0.13\n */\n public static JSONArray parse(String text, JSONReader.Feature... features) {\n return JSON.parseArray(text, features);\n }\n}\n", "file_name": "JSONArray.java", "human_label": "Converts the content in JSONWriter to a string.", "level": "self_contained", "lineno": "892", "name": "toString", "oracle_context": "{ \"apis\" : \"[of, write, setRootObject, getObjectWriter, JSONArray]\", \"classes\" : \"[JSONWriter, writer.context]\", \"vars\" : \"[Feature, context, arrayWriter]\" }", "package": "com.alibaba.fastjson2", "project": "fastjson2-main" }, { "_id": "636767021a6d9265ec0178bf", "all_context": "{ \"class_level\" : \"import net.hasor.utils.BeanUtils;\\nimport net.hasor.utils.convert.Converter;\\nCharacterConverter();\\nCharacterConverter(Object defaultValue);\\ngetDefaultType();\\nconvertToType(Class type,Object value);\\nconvertToString(Object value);\\n\", \"repo_level\" : \"public interface BeanUtils {static Object getDefaultValue(Class returnType);\\nstatic Object[] getDefaultValue(Class[] paramArray);\\nstatic Object invokeMethod(Object target,String methodName,Object objects);\\nstatic List findALLFields(Class target);\\nstatic List findALLMethods(Class target);\\nstatic List getFields(Class type);\\nstatic List getMethods(Class type);\\nstatic Field getField(String fieldName,Class type);\\nstatic Method getMethod(Class atClass,String name,Class[] paramType);\\nstatic List getPropertiesAndFields(Class target);\\nstatic List getProperties(Class target);\\nstatic PropertyDescriptor[] getPropertyDescriptors(Class defineType);\\nstatic Method getReadMethod(String property,Class target);\\nstatic Method getWriteMethod(String property,Class target);\\nstatic boolean hasProperty(String propertyName,Class target);\\nstatic boolean hasField(String propertyName,Class target);\\nstatic boolean hasPropertyOrField(String name,Class target);\\nstatic boolean canReadProperty(String propertyName,Class target);\\nstatic boolean canReadPropertyOrField(String propertyName,Class target);\\nstatic boolean canWriteProperty(String propertyName,Class target);\\nstatic boolean canWriteField(String propertyName,Class target);\\nstatic boolean canWritePropertyOrField(String propertyName,Class target);\\nstatic boolean writeProperty(Object object,String attName,Object value);\\nstatic boolean writeField(Object object,String fieldName,Object value);\\nstatic boolean writePropertyOrField(Object object,String attName,Object value);\\nstatic Object readProperty(Object object,String attName);\\nstatic Object readField(Object object,String fieldName);\\nstatic Object readPropertyOrField(Object object,String attName);\\nstatic Class getPropertyType(Class defineType,String attName);\\nstatic Class getFieldType(Class defineType,String attName);\\nstatic Class getPropertyOrFieldType(Class defineType,String attName);\\nstatic void copyProperties(Object dest,Object orig);\\nstatic void copyProperty(Object dest,Object orig,String propertyName);\\n }\\npublic interface Converter {public Object convert(Class type,Object value);\\n }\\n\" }", "class_name": "CharacterConverter", "code": "@Override protected Object convertToType(final Class type,final Object value) throws Exception {\n String string=value.toString();\n if (string.length() == 0) {\n return BeanUtils.getDefaultValue(type);\n }\n else {\n return string.charAt(0);\n }\n}\n", "docstring": "/** \n *

Convert the input object into a java.lang.Character.

\n * @param type Data type to which this value should be converted.\n * @param value The input value to be converted.\n * @return The converted value.\n * @throws Exception if conversion cannot be performed successfully\n * @since 1.8.0\n */\n", "end_lineno": "94", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.convert.convert;\nimport net.hasor.utils.BeanUtils;\nimport net.hasor.utils.convert.Converter;\n\n/**\n * {@link Converter} implementaion that handles conversion\n * to and from java.lang.Character objects.\n *

\n * Can be configured to either return a default value or throw a\n * ConversionException if a conversion error occurs.\n *\n * @author Craig R. McClanahan\n * @version $Revision: 690380 $ $Date: 2008-08-29 21:04:38 +0100 (Fri, 29 Aug 2008) $\n * @since 1.3\n */\npublic final class CharacterConverter extends AbstractConverter {\n /**\n * Construct a java.lang.Character Converter that throws\n * a ConversionException if an error occurs.\n */\n public CharacterConverter() {\n super();\n }\n\n /**\n * Construct a java.lang.Character Converter that returns\n * a default value if an error occurs.\n *\n * @param defaultValue The default value to be returned\n * if the value to be converted is missing or an error\n * occurs converting the value.\n */\n public CharacterConverter(final Object defaultValue) {\n super(defaultValue);\n }\n\n /**\n * Return the default type this Converter handles.\n *\n * @return The default type this Converter handles.\n * @since 1.8.0\n */\n @Override\n protected Class getDefaultType() {\n return Character.class;\n }\n\n /**\n *

Convert a java.lang.Class or object into a String.

\n *\n * @param value The input value to be converted\n * @return the converted String value.\n * @since 1.8.0\n */\n @Override\n protected String convertToString(final Object value) {\n String strValue = value.toString();\n return strValue.length() == 0 ? \"\" : strValue.substring(0, 1);\n }\n\n /**\n *

Convert the input object into a java.lang.Character.

\n *\n * @param type Data type to which this value should be converted.\n * @param value The input value to be converted.\n * @return The converted value.\n * @throws Exception if conversion cannot be performed successfully\n * @since 1.8.0\n */\n @Override\n protected Object convertToType(final Class type, final Object value) throws Exception {\n String string = value.toString();\n if (string.length() == 0) {\n return BeanUtils.getDefaultValue(type);\n } else {\n return string.charAt(0);\n }\n }\n}\n", "file_name": "CharacterConverter.java", "human_label": "If the length of the value string is 0, the default type is returned. Otherwise, the element at the first position of the string is returned.", "level": "project_runnable", "lineno": "77", "name": "convertToType", "oracle_context": "{ \"apis\" : \"[toString, length, getDefaultValue, charAt]\", \"classes\" : \"[String]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils.convert.convert", "project": "hasor-master" }, { "_id": "6367670b1a6d9265ec017a0f", "all_context": "{ \"class_level\" : \"import net.hasor.core.Singleton;\\nimport net.hasor.dataql.UdfSourceAssembly;\\nimport net.hasor.utils.StringUtils;\\nimport java.util.Arrays;\\nimport java.util.List;\\nimport java.util.regex.Matcher;\\nimport java.util.regex.Pattern;\\nPattern linePattern;\\nPattern humpPattern;\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWith(String str,String suffix);\\nendsWithIgnoreCase(String str,String suffix);\\n_startsWith(String str,String prefix,boolean ignoreCase);\\n_endsWith(String str,String suffix,boolean ignoreCase);\\nlineToHump(String str);\\nhumpToLine(String str);\\nfirstCharToUpperCase(String value);\\nfirstCharToLowerCase(String value);\\ntoUpperCase(String value);\\ntoLowerCase(String value);\\nindexOf(String str,String searchStr);\\nindexOfWithStart(String str,String searchStr,int startPos);\\nindexOfIgnoreCase(String str,String searchStr);\\nindexOfIgnoreCaseWithStart(String str,String searchStr,int startPos);\\nlastIndexOf(String str,String searchStr);\\nlastIndexOfWithStart(String str,String searchChar,int startPos);\\nlastIndexOfIgnoreCase(String str,String searchStr);\\nlastIndexOfIgnoreCaseWithStart(String str,String searchStr,int startPos);\\ncontains(String str,String searchStr);\\ncontainsIgnoreCase(String str,String searchStr);\\ncontainsAny(String str,List searchStrArray);\\ncontainsAnyIgnoreCase(String str,List searchStrArray);\\ntrim(String str);\\nsub(String str,int start,int end);\\nleft(String str,int len);\\nright(String str,int len);\\nalignRight(String str,String padChar,int len);\\nalignLeft(String str,String padChar,int len);\\nalignCenter(String str,String padChar,int len);\\ncompareString(String str1,String str2);\\ncompareStringIgnoreCase(String str1,String str2);\\nsplit(String str,String separatorChars);\\njoin(List array,String separator);\\nisEmpty(String str);\\nequalsIgnoreCase(String str1,String str2);\\nstartsWith(String str,String prefix);\\n\", \"repo_level\" : \"public interface UdfSourceAssembly {default Supplier getSupplier(Class targetType,Finder finder);\\ndefault Predicate getPredicate(Class targetType);\\npublic Object[] allParams();\\ndefault Supplier> getUdfResource(Finder finder);\\npublic Class annotationType();\\npublic String value();\\npublic Object call(Hints readOnly,Object values);\\npublic Object call(Hints readOnly,Object values);\\n }\\npublic interface StringUtils {static boolean isEmpty(String str);\\nstatic boolean isNotEmpty(String str);\\nstatic boolean isBlank(String str);\\nstatic boolean isNotBlank(String str);\\nstatic String trim(String str);\\nstatic String trimToNull(String str);\\nstatic String trimToEmpty(String str);\\nstatic String strip(String str);\\nstatic String stripToNull(String str);\\nstatic String stripToEmpty(String str);\\nstatic String strip(String str,String stripChars);\\nstatic String stripStart(String str,String stripChars);\\nstatic String stripEnd(String str,String stripChars);\\nstatic String[] stripAll(String[] strs);\\nstatic String[] stripAll(String[] strs,String stripChars);\\nstatic boolean equals(String str1,String str2);\\nstatic boolean equalsIgnoreCase(String str1,String str2);\\nstatic int indexOf(String str,char searchChar);\\nstatic int indexOf(String str,char searchChar,int startPos);\\nstatic int indexOf(String str,String searchStr);\\nstatic int ordinalIndexOf(String str,String searchStr,int ordinal);\\nstatic int indexOf(String str,String searchStr,int startPos);\\nstatic int indexOfIgnoreCase(String str,String searchStr);\\nstatic int indexOfIgnoreCase(String str,String searchStr,int startPos);\\nstatic int lastIndexOf(String str,char searchChar);\\nstatic int lastIndexOf(String str,char searchChar,int startPos);\\nstatic int lastIndexOf(String str,String searchStr);\\nstatic int lastOrdinalIndexOf(String str,String searchStr,int ordinal);\\nstatic int lastIndexOf(String str,String searchStr,int startPos);\\nstatic int lastIndexOfIgnoreCase(String str,String searchStr);\\nstatic int lastIndexOfIgnoreCase(String str,String searchStr,int startPos);\\nstatic boolean contains(String str,char searchChar);\\nstatic boolean contains(String str,String searchStr);\\nstatic boolean containsIgnoreCase(String str,String searchStr);\\nstatic int indexOfAny(String str,char[] searchChars);\\nstatic int indexOfAny(String str,String searchChars);\\nstatic boolean containsAny(String str,char[] searchChars);\\nstatic boolean containsAny(String str,String searchChars);\\nstatic int indexOfAnyBut(String str,char[] searchChars);\\nstatic int indexOfAnyBut(String str,String searchChars);\\nstatic boolean containsOnly(String str,char[] valid);\\nstatic boolean containsOnly(String str,String validChars);\\nstatic boolean containsNone(String str,char[] searchChars);\\nstatic boolean containsNone(String str,String invalidChars);\\nstatic int indexOfAny(String str,String[] searchStrs);\\nstatic int lastIndexOfAny(String str,String[] searchStrs);\\nstatic String substring(String str,int start);\\nstatic String substring(String str,int start,int end);\\nstatic String left(String str,int len);\\nstatic String right(String str,int len);\\nstatic String mid(String str,int pos,int len);\\nstatic String substringBefore(String str,String separator);\\nstatic String substringAfter(String str,String separator);\\nstatic String substringBeforeLast(String str,String separator);\\nstatic String substringAfterLast(String str,String separator);\\nstatic String substringBetween(String str,String tag);\\nstatic String substringBetween(String str,String open,String close);\\nstatic String[] substringsBetween(String str,String open,String close);\\nstatic String[] splitKeep(String str,char separatorChar);\\nstatic String[] splitKeep(String str,String separatorStr);\\nstatic String[] split(String str);\\nstatic String[] split(String str,char separatorChar);\\nstatic String[] split(String str,String separatorChars);\\nstatic String[] split(String str,String separatorChars,int max);\\nstatic String[] splitByWholeSeparator(String str,String separator);\\nstatic String[] splitByWholeSeparator(String str,String separator,int max);\\nstatic String[] splitByWholeSeparatorPreserveAllTokens(String str,String separator);\\nstatic String[] splitByWholeSeparatorPreserveAllTokens(String str,String separator,int max);\\nstatic String[] splitPreserveAllTokens(String str);\\nstatic String[] splitPreserveAllTokens(String str,char separatorChar);\\nstatic String[] splitPreserveAllTokens(String str,String separatorChars);\\nstatic String[] splitPreserveAllTokens(String str,String separatorChars,int max);\\nstatic String[] splitByCharacterType(String str);\\nstatic String[] splitByCharacterTypeCamelCase(String str);\\nstatic String join(Object[] array);\\nstatic String join(Object[] array,char separator);\\nstatic String join(Object[] array,char separator,int startIndex,int endIndex);\\nstatic String join(Object[] array,String separator);\\nstatic String join(Object[] array,String separator,int startIndex,int endIndex);\\nstatic String deleteWhitespace(String str);\\nstatic String removeStart(String str,String remove);\\nstatic String removeStartIgnoreCase(String str,String remove);\\nstatic String removeEnd(String str,String remove);\\nstatic String removeEndIgnoreCase(String str,String remove);\\nstatic String remove(String str,String remove);\\nstatic String remove(String str,char remove);\\nstatic String replaceOnce(String text,String searchString,String replacement);\\nstatic String replace(String text,String searchString,String replacement);\\nstatic String replace(String text,String searchString,String replacement,int max);\\nstatic String replaceEach(String text,String[] searchList,String[] replacementList);\\nstatic String replaceEachRepeatedly(String text,String[] searchList,String[] replacementList);\\nstatic String replaceChars(String str,char searchChar,char replaceChar);\\nstatic String replaceChars(String str,String searchChars,String replaceChars);\\nstatic String overlay(String str,String overlay,int start,int end);\\nstatic String chomp(String str);\\nstatic String chomp(String str,String separator);\\nstatic String chop(String str);\\nstatic String repeat(char character,int repeat);\\nstatic String repeat(String str,int repeat);\\nstatic String repeat(String str,String separator,int repeat);\\nstatic String rightPad(String str,int size);\\nstatic String rightPad(String str,int size,char padChar);\\nstatic String rightPad(String str,int size,String padStr);\\nstatic String leftPad(String str,int size);\\nstatic String leftPad(String str,int size,char padChar);\\nstatic String leftPad(String str,int size,String padStr);\\nstatic int length(String str);\\nstatic String center(String str,int size);\\nstatic String center(String str,int size,char padChar);\\nstatic String center(String str,int size,String padStr);\\nstatic String upperCase(String str);\\nstatic String upperCase(String str,Locale locale);\\nstatic String lowerCase(String str);\\nstatic String lowerCase(String str,Locale locale);\\nstatic String capitalize(String str);\\nstatic String uncapitalize(String str);\\nstatic String swapCase(String str);\\nstatic int countMatches(String str,String sub);\\nstatic boolean isAlpha(String str);\\nstatic boolean isAlphaSpace(String str);\\nstatic boolean isAlphanumeric(String str);\\nstatic boolean isAlphanumericSpace(String str);\\nstatic boolean isAsciiPrintable(String str);\\nstatic boolean isNumeric(String str);\\nstatic boolean isNumericSpace(String str);\\nstatic boolean isWhitespace(String str);\\nstatic boolean isAllLowerCase(String str);\\nstatic boolean isAllUpperCase(String str);\\nstatic String defaultString(String str);\\nstatic String defaultString(String str,String defaultStr);\\nstatic String defaultIfBlank(String str,String defaultStr);\\nstatic String defaultIfEmpty(String str,String defaultStr);\\nstatic String reverse(String str);\\nstatic String reverseDelimited(String str,char separatorChar);\\nstatic String abbreviate(String str,int maxWidth);\\nstatic String abbreviate(String str,int offset,int maxWidth);\\nstatic String abbreviateMiddle(String str,String middle,int length);\\nstatic String difference(String str1,String str2);\\nstatic int indexOfDifference(String str1,String str2);\\nstatic int indexOfDifference(String[] strs);\\nstatic String getCommonPrefix(String[] strs);\\nstatic int getLevenshteinDistance(String s,String t);\\nstatic boolean startsWith(String str,String prefix);\\nstatic boolean startsWithIgnoreCase(String str,String prefix);\\nstatic boolean startsWithAny(String string,String[] searchStrings);\\nstatic boolean endsWith(String str,String suffix);\\nstatic boolean endsWithIgnoreCase(String str,String suffix);\\nstatic String normalizeSpace(String str);\\nstatic boolean endsWithAny(String string,String[] searchStrings);\\nstatic String firstCharToUpperCase(String value);\\nstatic String firstCharToLowerCase(String value);\\nstatic boolean equalsBlankIgnoreCase(String str1,String str2);\\nstatic String quote(String input);\\nstatic void quote(Appendable buffer,String input);\\nstatic String toString(Object object);\\n }\\n\" }", "class_name": "StringUdfSource", "code": "public static boolean containsAnyIgnoreCase(String str,List searchStrArray){\n if (StringUtils.isEmpty(str) || searchStrArray == null || searchStrArray.isEmpty()) {\n return false;\n }\n for ( String item : searchStrArray) {\n if (containsIgnoreCase(str,item)) {\n return true;\n }\n }\n return false;\n}\n", "docstring": "/** \n * Case in-sensitive Checks if the String contains any character in the given set of string. \n */\n", "end_lineno": "222", "file_content": "/*\n * Copyright 2008-2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.dataql.fx.basic;\nimport net.hasor.core.Singleton;\nimport net.hasor.dataql.UdfSourceAssembly;\nimport net.hasor.utils.StringUtils;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * 字符串函数 import 'net.hasor.dataql.fx.basic.StringUdfSource' as string;\n * @version : 2019-12-12\n */\n@Singleton\npublic class StringUdfSource implements UdfSourceAssembly {\n // startsWith/endsWith\n //-----------------------------------------------------------------------\n\n /** Check if a String starts with a specified prefix. */\n public static boolean startsWith(String str, String prefix) {\n return _startsWith(str, prefix, false);\n }\n\n /** Case insensitive check if a String starts with a specified prefix. */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n return _startsWith(str, prefix, true);\n }\n\n /** Case insensitive check if a String ends with a specified suffix. */\n public static boolean endsWith(String str, String suffix) {\n return _endsWith(str, suffix, false);\n }\n\n /** Case insensitive check if a String ends with a specified suffix. */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n return _endsWith(str, suffix, true);\n }\n\n private static boolean _startsWith(String str, String prefix, boolean ignoreCase) {\n if (str == null || prefix == null) {\n return str == null && prefix == null;\n }\n if (prefix.length() > str.length()) {\n return false;\n }\n return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());\n }\n\n private static boolean _endsWith(String str, String suffix, boolean ignoreCase) {\n if (str == null || suffix == null) {\n return str == null && suffix == null;\n }\n if (suffix.length() > str.length()) {\n return false;\n }\n int strOffset = str.length() - suffix.length();\n return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());\n }\n\n // Hump\n //-----------------------------------------------------------------------\n private static final Pattern linePattern = Pattern.compile(\"_(\\\\w)\");\n private static final Pattern humpPattern = Pattern.compile(\"[A-Z]\");\n\n /** 下划线转驼峰 */\n public static String lineToHump(String str) {\n if (str == null) {\n return null;\n }\n str = str.toLowerCase();\n Matcher matcher = linePattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, matcher.group(1).toUpperCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n\n /** 驼峰转下划线 */\n public static String humpToLine(String str) {\n if (str == null) {\n return null;\n }\n Matcher matcher = humpPattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, \"_\" + matcher.group(0).toLowerCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n // UpperCase/LowerCase\n //-----------------------------------------------------------------------\n\n /** 转换首字母大写 */\n public static String firstCharToUpperCase(String value) {\n return StringUtils.firstCharToUpperCase(value);\n }\n\n /** 转换首字母小写 */\n public static String firstCharToLowerCase(String value) {\n return StringUtils.firstCharToLowerCase(value);\n }\n\n /** 转换大写 */\n public static String toUpperCase(String value) {\n return StringUtils.upperCase(value);\n }\n\n /** 转换小写 */\n public static String toLowerCase(String value) {\n return StringUtils.lowerCase(value);\n }\n // IndexOf/lastIndexOf\n //-----------------------------------------------------------------------\n\n /** Finds the first index within a String, handling null. This method uses {@link String#indexOf(String)}. */\n public static int indexOf(String str, String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr);\n }\n\n /** Finds the first index within a String from a start position, handling null. This method uses {@link String#indexOf(String, int)}. */\n public static int indexOfWithStart(String str, String searchStr, int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr, startPos);\n }\n\n /** Case in-sensitive find of the first index within a String. */\n public static int indexOfIgnoreCase(String str, String searchStr) {\n return StringUtils.indexOfIgnoreCase(str, searchStr, 0);\n }\n\n /** Case in-sensitive find of the first index within a String from the specified position. */\n public static int indexOfIgnoreCaseWithStart(String str, String searchStr, int startPos) {\n return StringUtils.indexOfIgnoreCase(str, searchStr, startPos);\n }\n\n /** Finds the last index within a String, handling null. This method uses {@link String#lastIndexOf(String)}. */\n public static int lastIndexOf(String str, String searchStr) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr);\n }\n\n /** Finds the last index within a String from a start position, handling null. This method uses {@link String#lastIndexOf(String, int)}. */\n public static int lastIndexOfWithStart(String str, String searchChar, int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar, startPos);\n }\n\n /** Case in-sensitive find of the last index within a String from the specified position. */\n public static int lastIndexOfIgnoreCase(String str, String searchStr) {\n return StringUtils.lastIndexOfIgnoreCase(str, searchStr, 0);\n }\n\n /** Case in-sensitive find of the last index within a String from the specified position. */\n public static int lastIndexOfIgnoreCaseWithStart(String str, String searchStr, int startPos) {\n return StringUtils.lastIndexOfIgnoreCase(str, searchStr, startPos);\n }\n // Contains\n //-----------------------------------------------------------------------\n\n /** Checks if String contains a search String, handling null. This method uses {@link String#indexOf(String)}. */\n public static boolean contains(String str, String searchStr) {\n return StringUtils.contains(str, searchStr);\n }\n\n /** Checks if String contains a search String irrespective of case, handling null. Case-insensitivity is defined as by {@link String#equalsIgnoreCase(String)}. */\n public static boolean containsIgnoreCase(String str, String searchStr) {\n return StringUtils.containsIgnoreCase(str, searchStr);\n }\n\n /** Checks if the String contains any character in the given set of string. */\n public static boolean containsAny(String str, List searchStrArray) {\n if (StringUtils.isEmpty(str) || searchStrArray == null || searchStrArray.isEmpty()) {\n return false;\n }\n for (String item : searchStrArray) {\n if (contains(str, item)) {\n return true;\n }\n }\n return false;\n }\n\n /** Case in-sensitive Checks if the String contains any character in the given set of string. */\n public static boolean containsAnyIgnoreCase(String str, List searchStrArray) {\n if (StringUtils.isEmpty(str) || searchStrArray == null || searchStrArray.isEmpty()) {\n return false;\n }\n for (String item : searchStrArray) {\n if (containsIgnoreCase(str, item)) {\n return true;\n }\n }\n return false;\n }\n // trim/Sub/left/right\n //-----------------------------------------------------------------------\n\n /** 截断两边空格,如果为空返回为空。 */\n public static String trim(final String str) {\n return str == null ? null : str.trim();\n }\n\n /** Gets a substring from the specified String avoiding exceptions. */\n public static String sub(String str, int start, int end) {\n return StringUtils.substring(str, start, end);\n }\n\n /** Gets the leftmost len characters of a String. */\n public static String left(String str, int len) {\n return StringUtils.left(str, len);\n }\n\n /** Gets the rightmost len characters of a String. */\n public static String right(String str, int len) {\n return StringUtils.right(str, len);\n }\n // align/pading\n //-----------------------------------------------------------------------\n\n /** 字符串在指定长度下进行右对齐,空出来的字符使用padChar补齐。如果传入多个字符将会取第一个字符。 */\n public static String alignRight(String str, String padChar, int len) {\n if (str != null) {\n if (str.length() > len) {\n return str;\n }\n }\n char pad = padChar.length() == 0 ? ' ' : padChar.charAt(0);\n return StringUtils.rightPad(str, len, pad);\n }\n\n /** 字符串在指定长度下进行左对齐,空出来的字符使用padChar补齐。如果传入多个字符将会取第一个字符。 */\n public static String alignLeft(String str, String padChar, int len) {\n if (str != null) {\n if (str.length() > len) {\n return str;\n }\n }\n char pad = padChar.length() == 0 ? ' ' : padChar.charAt(0);\n return StringUtils.leftPad(str, len, pad);\n }\n\n /** 字符串在指定长度下进行剧中对齐,空出来的字符使用padChar补齐。如果传入多个字符将会取第一个字符。 */\n public static String alignCenter(String str, String padChar, int len) {\n if (str != null) {\n if (str.length() > len) {\n return str;\n }\n }\n char pad = padChar.length() == 0 ? ' ' : padChar.charAt(0);\n return StringUtils.center(str, len, pad);\n }\n // compare\n //-----------------------------------------------------------------------\n\n /**\n * Compares two strings lexicographically.\n * The comparison is based on the Unicode value of each character in\n * the strings. The character sequence represented by this\n * {@code String} object is compared lexicographically to the\n * character sequence represented by the argument string. The result is\n * a negative integer if this {@code String} object\n * lexicographically precedes the argument string. The result is a\n * positive integer if this {@code String} object lexicographically\n * follows the argument string. The result is zero if the strings\n * are equal; {@code compareTo} returns {@code 0} exactly when\n * the {@link #equals(Object)} method would return {@code true}.\n *

\n * This is the definition of lexicographic ordering. If two strings are\n * different, then either they have different characters at some index\n * that is a valid index for both strings, or their lengths are different,\n * or both. If they have different characters at one or more index\n * positions, let k be the smallest such index; then the string\n * whose character at position k has the smaller value, as\n * determined by using the < operator, lexicographically precedes the\n * other string. In this case, {@code compareTo} returns the\n * difference of the two character values at position {@code k} in\n * the two string -- that is, the value:\n *

\n     * this.charAt(k)-anotherString.charAt(k)\n     * 
\n * If there is no index position at which they differ, then the shorter\n * string lexicographically precedes the longer string. In this case,\n * {@code compareTo} returns the difference of the lengths of the\n * strings -- that is, the value:\n *
\n     * this.length()-anotherString.length()\n     * 
\n *\n * @param str1 the {@code String} to be compared.\n * @param str2 the {@code String} to be compared.\n * @return the value {@code 0} if the argument string is equal to\n * this string; a value less than {@code 0} if this string\n * is lexicographically less than the string argument; and a\n * value greater than {@code 0} if this string is\n * lexicographically greater than the string argument.\n */\n public static int compareString(String str1, String str2) {\n str1 = str1 == null ? \"\" : str1;\n str2 = str2 == null ? \"\" : str2;\n return str1.compareTo(str2);\n }\n\n /**\n * Compares two strings lexicographically, ignoring case\n * differences. This method returns an integer whose sign is that of\n * calling {@code compareTo} with normalized versions of the strings\n * where case differences have been eliminated by calling\n * {@code Character.toLowerCase(Character.toUpperCase(character))} on\n * each character.\n *

\n * Note that this method does not take locale into account,\n * and will result in an unsatisfactory ordering for certain locales.\n * The java.text package provides collators to allow\n * locale-sensitive ordering.\n *\n * @param str1 the {@code String} to be compared.\n * @param str2 the {@code String} to be compared.\n * @return a negative integer, zero, or a positive integer as the\n * specified String is greater than, equal to, or less\n * than this String, ignoring case considerations.\n * @see java.text.Collator#compare(String, String)\n * @since 1.2\n */\n public static int compareStringIgnoreCase(String str1, String str2) {\n str1 = str1 == null ? \"\" : str1;\n str2 = str2 == null ? \"\" : str2;\n return str1.compareToIgnoreCase(str2);\n }\n // other\n //-----------------------------------------------------------------------\n\n /**\n *

Splits the provided text into an array, separators specified.\n * This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *
\n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"abc def\", null) = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc def\", \" \")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\", \" \") = [\"abc\", \"def\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\") = [\"ab\", \"cd\", \"ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters, null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n */\n public static List split(String str, String separatorChars) {\n return Arrays.asList(StringUtils.split(str, separatorChars));\n }\n\n /** Joins the elements of the provided array into a single String containing the provided list of elements. */\n public static String join(List array, String separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array.toArray(), separator);\n }\n\n /** Checks if a String is empty (\"\") or null.*/\n public static boolean isEmpty(String str) {\n return str == null || str.length() == 0;\n }\n\n /** 忽略大小写比较相等 */\n public static boolean equalsIgnoreCase(String str1, String str2) {\n return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);\n }\n}\n", "file_name": "StringUdfSource.java", "human_label": "Check whether str contains elements in searchStrArray. If yes, true is returned. If no, false is returned.", "level": "project_runnable", "lineno": "211", "name": "containsAnyIgnoreCase", "oracle_context": "{ \"apis\" : \"[isEmpty, containsIgnoreCase]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.dataql.fx.basic", "project": "hasor-master" }, { "_id": "636766a81a6d9265ec01758e", "all_context": "{ \"class_level\" : \"import java.util.Arrays;\\nint largestPrime;\\nint[] primeCapacities;\\n\", \"repo_level\" : \"\" }", "class_name": "PrimeFinder", "code": "public static int nextPrime(int desiredCapacity){\n if (desiredCapacity >= largestPrime) {\n return largestPrime;\n }\n int i=Arrays.binarySearch(primeCapacities,desiredCapacity);\n if (i < 0) {\n i=-i - 1;\n }\n return primeCapacities[i];\n}\n", "docstring": "/** \n * Returns a prime number which is >= desiredCapacity and very close to desiredCapacity (within 11% if desiredCapacity >= 1000).\n * @param desiredCapacity the capacity desired by the user.\n * @return the capacity which should be used for a hashtable.\n */\n", "end_lineno": "166", "file_content": "// Copyright (c) 1999 CERN - European Organization for Nuclear Research.\n\n// Permission to use, copy, modify, distribute and sell this software\n// and its documentation for any purpose is hereby granted without fee,\n// provided that the above copyright notice appear in all copies and\n// that both that copyright notice and this permission notice appear in\n// supporting documentation. CERN makes no representations about the\n// suitability of this software for any purpose. It is provided \"as is\"\n// without expressed or implied warranty.\npackage com.alibaba.fastjson2.internal.trove.impl;\n\nimport java.util.Arrays;\n\n/*\n * Modified for Trove to use the java.util.Arrays sort/search\n * algorithms instead of those provided with colt.\n */\n\n/**\n * Used to keep hash table capacities prime numbers.\n * Not of interest for users; only for implementors of hashtables.\n *\n *

Choosing prime numbers as hash table capacities is a good idea\n * to keep them working fast, particularly under hash table\n * expansions.\n *\n *

However, JDK 1.2, JGL 3.1 and many other toolkits do nothing to\n * keep capacities prime. This class provides efficient means to\n * choose prime capacities.\n *\n *

Choosing a prime is O(log 300) (binary search in a list\n * of 300 ints). Memory requirements: 1 KB static memory.\n *\n * @author wolfgang.hoschek@cern.ch\n * @version 1.0, 09/24/99\n */\npublic final class PrimeFinder {\n /**\n * The largest prime this class can generate; currently equal to\n * 2,004,663,929.\n *

\n * While Integer.MAX_VALUE is in fact the largest representable\n * prime in the integer space, consumers of this class are\n * intended to create arrays of size returned from\n * {@link #nextPrime}. Since the VM needs to reserve a few bytes\n * for internal overhead, new int[Integer.MAX_VALUE] fails with\n * an \"exceeds VM limits\" exception. So, we pick the second-largest\n * prime as the practical largest.\n */\n public static final int largestPrime;\n\n /**\n * The prime number list consists of 11 chunks.\n *

\n * Each chunk contains prime numbers.\n *

\n * A chunk starts with a prime P1. The next element is a prime\n * P2. P2 is the smallest prime for which holds: P2 >= 2*P1.\n *

\n * The next element is P3, for which the same holds with respect\n * to P2, and so on.\n *

\n * Chunks are chosen such that for any desired capacity >= 1000\n * the list includes a prime number <= desired capacity * 1.11.\n *

\n * Therefore, primes can be retrieved which are quite close to any\n * desired capacity, which in turn avoids wasting memory.\n *

\n * For example, the list includes\n * 1039,1117,1201,1277,1361,1439,1523,1597,1759,1907,2081.\n *

\n * So if you need a prime >= 1040, you will find a prime <=\n * 1040*1.11=1154.\n *

\n * Chunks are chosen such that they are optimized for a hashtable\n * growthfactor of 2.0;\n *

\n * If your hashtable has such a growthfactor then, after initially\n * \"rounding to a prime\" upon hashtable construction, it will\n * later expand to prime capacities such that there exist no\n * better primes.\n *

\n * In total these are about 32*10=320 numbers -> 1 KB of static\n * memory needed.\n *

\n * If you are stingy, then delete every second or fourth chunk.\n */\n\n private static final int[] primeCapacities = {\n //chunk #1\n 5, 11, 23, 47, 97, 197, 397, 797, 1597, 3203, 6421, 12853, 25717, 51437, 102877, 205759,\n 411527, 823117, 1646237, 3292489, 6584983, 13169977, 26339969, 52679969, 105359939,\n 210719881, 421439783, 842879579, 1685759167,\n\n //chunk #2\n 433, 877, 1759, 3527, 7057, 14143, 28289, 56591, 113189, 226379, 452759, 905551, 1811107,\n 3622219, 7244441, 14488931, 28977863, 57955739, 115911563, 231823147, 463646329, 927292699,\n 1854585413,\n\n //chunk #3\n 953, 1907, 3821, 7643, 15287, 30577, 61169, 122347, 244703, 489407, 978821, 1957651, 3915341,\n 7830701, 15661423, 31322867, 62645741, 125291483, 250582987, 501165979, 1002331963,\n 2004663929,\n\n //chunk #4\n 1039, 2081, 4177, 8363, 16729, 33461, 66923, 133853, 267713, 535481, 1070981, 2141977, 4283963,\n 8567929, 17135863, 34271747, 68543509, 137087021, 274174111, 548348231, 1096696463,\n\n //chunk #5\n 31, 67, 137, 277, 557, 1117, 2237, 4481, 8963, 17929, 35863, 71741, 143483, 286973, 573953,\n 1147921, 2295859, 4591721, 9183457, 18366923, 36733847, 73467739, 146935499, 293871013,\n 587742049, 1175484103,\n\n //chunk #6\n 599, 1201, 2411, 4831, 9677, 19373, 38747, 77509, 155027, 310081, 620171, 1240361, 2480729,\n 4961459, 9922933, 19845871, 39691759, 79383533, 158767069, 317534141, 635068283, 1270136683,\n\n //chunk #7\n 311, 631, 1277, 2557, 5119, 10243, 20507, 41017, 82037, 164089, 328213, 656429, 1312867,\n 2625761, 5251529, 10503061, 21006137, 42012281, 84024581, 168049163, 336098327, 672196673,\n 1344393353,\n\n //chunk #8\n 3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899,\n 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557,\n 359339171, 718678369, 1437356741,\n\n //chunk #9\n 43, 89, 179, 359, 719, 1439, 2879, 5779, 11579, 23159, 46327, 92657, 185323, 370661, 741337,\n 1482707, 2965421, 5930887, 11861791, 23723597, 47447201, 94894427, 189788857, 379577741,\n 759155483, 1518310967,\n\n //chunk #10\n 379, 761, 1523, 3049, 6101, 12203, 24407, 48817, 97649, 195311, 390647, 781301, 1562611,\n 3125257, 6250537, 12501169, 25002389, 50004791, 100009607, 200019221, 400038451, 800076929,\n 1600153859\n };\n\n static { //initializer\n // The above prime numbers are formatted for human readability.\n // To find numbers fast, we sort them once and for all.\n\n Arrays.sort(primeCapacities);\n largestPrime = primeCapacities[primeCapacities.length - 1];\n }\n\n /**\n * Returns a prime number which is >= desiredCapacity\n * and very close to desiredCapacity (within 11% if\n * desiredCapacity >= 1000).\n *\n * @param desiredCapacity the capacity desired by the user.\n * @return the capacity which should be used for a hashtable.\n */\n public static int nextPrime(int desiredCapacity) {\n if (desiredCapacity >= largestPrime) {\n return largestPrime;\n }\n int i = Arrays.binarySearch(primeCapacities, desiredCapacity);\n if (i < 0) {\n // desired capacity not found, choose next prime greater\n // than desired capacity\n i = -i - 1; // remember the semantics of binarySearch...\n }\n return primeCapacities[i];\n }\n}\n", "file_name": "PrimeFinder.java", "human_label": "Returns the element at the location specified by desiredCapacity in primeCapacities.", "level": "slib_runnable", "lineno": "147", "name": "nextPrime", "oracle_context": "{ \"apis\" : \"[binarySearch]\", \"classes\" : \"[]\", \"vars\" : \"[largestPrime, primeCapacities]\" }", "package": "com.alibaba.fastjson2.internal.trove.impl", "project": "fastjson2-main" }, { "_id": "6367670a1a6d9265ec0179cf", "all_context": "{ \"class_level\" : \"String CHAR_STRING;\\nString[] CHAR_STRING_ARRAY;\\nCharacter[] CHAR_ARRAY;\\nchar LF;\\nchar CR;\\nCharUtils();\\ntoCharacterObject(String str);\\ntoChar(Character ch);\\ntoChar(Character ch,char defaultValue);\\ntoChar(String str);\\ntoChar(String str,char defaultValue);\\ntoIntValue(char ch);\\ntoIntValue(char ch,int defaultValue);\\ntoIntValue(Character ch);\\ntoIntValue(Character ch,int defaultValue);\\ntoString(char ch);\\ntoString(Character ch);\\nunicodeEscaped(char ch);\\nunicodeEscaped(Character ch);\\nisAscii(char ch);\\nisAsciiPrintable(char ch);\\nisAsciiControl(char ch);\\nisAsciiAlpha(char ch);\\nisAsciiAlphaUpper(char ch);\\nisAsciiAlphaLower(char ch);\\nisAsciiNumeric(char ch);\\nisAsciiAlphanumeric(char ch);\\nisHighSurrogate(char ch);\\nisCharType(Class targetType);\\ntoCharacterObject(char ch);\\n\", \"repo_level\" : \"\" }", "class_name": "CharUtils", "code": "public static char toChar(final Character ch,final char defaultValue){\n if (ch == null) {\n return defaultValue;\n }\n return ch.charValue();\n}\n", "docstring": "/** \n *

Converts the Character to a char handling null.

 CharUtils.toChar(null, 'X') = 'X' CharUtils.toChar(' ', 'X')  = ' ' CharUtils.toChar('A', 'X')  = 'A' 
\n * @param ch the character to convert\n * @param defaultValue the value to use if the Character is null\n * @return the char value of the Character or the default if null\n */\n", "end_lineno": "171", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\n/**\n *

Operations on char primitives and Character objects.

\n *\n *

This class tries to handle null input gracefully.\n * An exception will not be thrown for a null input.\n * Each method documents its behaviour in more detail.

\n *\n *

#ThreadSafe#

\n * @author Apache Software Foundation\n * @since 2.1\n * @version $Id: CharUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class CharUtils {\n private static final String CHAR_STRING = //\n \"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\" +//\n \"\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\" + //\n \"\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\" + //\n \"\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\" +//\n \"\\u0020\\u0021\\\"\\u0023\\u0024\\u0025\\u0026\\u0027\" + //\n \"\\u0028\\u0029\\u002a\\u002b\\u002c\\u002d\\u002e\\u002f\" + //\n \"\\u0030\\u0031\\u0032\\u0033\\u0034\\u0035\\u0036\\u0037\" + //\n \"\\u0038\\u0039\\u003a\\u003b\\u003c\\u003d\\u003e\\u003f\" + //\n \"\\u0040\\u0041\\u0042\\u0043\\u0044\\u0045\\u0046\\u0047\" + //\n \"\\u0048\\u0049\\u004a\\u004b\\u004c\\u004d\\u004e\\u004f\" + //\n \"\\u0050\\u0051\\u0052\\u0053\\u0054\\u0055\\u0056\\u0057\" +//\n \"\\u0058\\u0059\\u005a\\u005b\\\\\\u005d\\u005e\\u005f\" + //\n \"\\u0060\\u0061\\u0062\\u0063\\u0064\\u0065\\u0066\\u0067\" +//\n \"\\u0068\\u0069\\u006a\\u006b\\u006c\\u006d\\u006e\\u006f\" +//\n \"\\u0070\\u0071\\u0072\\u0073\\u0074\\u0075\\u0076\\u0077\" +//\n \"\\u0078\\u0079\\u007a\\u007b\\u007c\\u007d\\u007e\\u007f\";\n private static final String[] CHAR_STRING_ARRAY = new String[128];\n private static final Character[] CHAR_ARRAY = new Character[128];\n /**\n * \n linefeed LF ('\\n').\n *\n * @see JLF: Escape Sequences\n * for Character and String Literals\n * @since 2.2\n */\n public static final char LF = '\\n';\n /**\n * carriage return CR ('\\r').\n *\n * @see JLF: Escape Sequences\n * for Character and String Literals\n * @since 2.2\n */\n public static final char CR = '\\r';\n\n static {\n for (int i = 127; i >= 0; i--) {\n CharUtils.CHAR_STRING_ARRAY[i] = CharUtils.CHAR_STRING.substring(i, i + 1);\n CharUtils.CHAR_ARRAY[i] = new Character((char) i);\n }\n }\n\n /**\n *

CharUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as CharUtils.toString('c');.

\n *\n *

This constructor i public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public CharUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the character to a Character.

\n *\n *

For ASCII 7 bit characters, this uses a cache that will return the\n * same Character object each time.

\n *\n *
\n     *   CharUtils.toCharacterObject(' ')  = ' '\n     *   CharUtils.toCharacterObject('A')  = 'A'\n     * 
\n *\n * @param ch the character to convert\n * @return a Character of the specified character\n */\n public static Character toCharacterObject(final char ch) {\n if (ch < CharUtils.CHAR_ARRAY.length) {\n return CharUtils.CHAR_ARRAY[ch];\n }\n return new Character(ch);\n }\n\n /**\n *

Converts the String to a Character using the first character, returning\n * null for empty Strings.

\n *\n *

For ASCII 7 bit characters, this uses a cache that will return the\n * same Character object each time.

\n *\n *
\n     *   CharUtils.toCharacterObject(null) = null\n     *   CharUtils.toCharacterObject(\"\")   = null\n     *   CharUtils.toCharacterObject(\"A\")  = 'A'\n     *   CharUtils.toCharacterObject(\"BA\") = 'B'\n     * 
\n *\n * @param str the character to convert\n * @return the Character value of the first letter of the String\n */\n public static Character toCharacterObject(final String str) {\n if (StringUtils.isEmpty(str)) {\n return null;\n }\n return CharUtils.toCharacterObject(str.charAt(0));\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the Character to a char throwing an exception for null.

\n *\n *
\n     *   CharUtils.toChar(null) = IllegalArgumentException\n     *   CharUtils.toChar(' ')  = ' '\n     *   CharUtils.toChar('A')  = 'A'\n     * 
\n *\n * @param ch the character to convert\n * @return the char value of the Character\n * @throws IllegalArgumentException if the Character is null\n */\n public static char toChar(final Character ch) {\n if (ch == null) {\n throw new IllegalArgumentException(\"The Character must not be null\");\n }\n return ch.charValue();\n }\n\n /**\n *

Converts the Character to a char handling null.

\n *\n *
\n     *   CharUtils.toChar(null, 'X') = 'X'\n     *   CharUtils.toChar(' ', 'X')  = ' '\n     *   CharUtils.toChar('A', 'X')  = 'A'\n     * 
\n *\n * @param ch the character to convert\n * @param defaultValue the value to use if the Character is null\n * @return the char value of the Character or the default if null\n */\n public static char toChar(final Character ch, final char defaultValue) {\n if (ch == null) {\n return defaultValue;\n }\n return ch.charValue();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the String to a char using the first character, throwing\n * an exception on empty Strings.

\n *\n *
\n     *   CharUtils.toChar(null) = IllegalArgumentException\n     *   CharUtils.toChar(\"\")   = IllegalArgumentException\n     *   CharUtils.toChar(\"A\")  = 'A'\n     *   CharUtils.toChar(\"BA\") = 'B'\n     * 
\n *\n * @param str the character to convert\n * @return the char value of the first letter of the String\n * @throws IllegalArgumentException if the String is empty\n */\n public static char toChar(final String str) {\n if (StringUtils.isEmpty(str)) {\n throw new IllegalArgumentException(\"The String must not be empty\");\n }\n return str.charAt(0);\n }\n\n /**\n *

Converts the String to a char using the first character, defaulting\n * the value on empty Strings.

\n *\n *
\n     *   CharUtils.toChar(null, 'X') = 'X'\n     *   CharUtils.toChar(\"\", 'X')   = 'X'\n     *   CharUtils.toChar(\"A\", 'X')  = 'A'\n     *   CharUtils.toChar(\"BA\", 'X') = 'B'\n     * 
\n *\n * @param str the character to convert\n * @param defaultValue the value to use if the Character is null\n * @return the char value of the first letter of the String or the default if null\n */\n public static char toChar(final String str, final char defaultValue) {\n if (StringUtils.isEmpty(str)) {\n return defaultValue;\n }\n return str.charAt(0);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

\n *\n *

This method coverts the char '1' to the int 1 and so on.

\n *\n *
\n     *   CharUtils.toIntValue('3')  = 3\n     *   CharUtils.toIntValue('A')  = IllegalArgumentException\n     * 
\n *\n * @param ch the character to convert\n * @return the int value of the character\n * @throws IllegalArgumentException if the character is not ASCII numeric\n */\n public static int toIntValue(final char ch) {\n if (CharUtils.isAsciiNumeric(ch) == false) {\n throw new IllegalArgumentException(\"The character \" + ch + \" is not in the range '0' - '9'\");\n }\n return ch - 48;\n }\n\n /**\n *

Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

\n *\n *

This method coverts the char '1' to the int 1 and so on.

\n *\n *
\n     *   CharUtils.toIntValue('3', -1)  = 3\n     *   CharUtils.toIntValue('A', -1)  = -1\n     * 
\n *\n * @param ch the character to convert\n * @param defaultValue the default value to use if the character is not numeric\n * @return the int value of the character\n */\n public static int toIntValue(final char ch, final int defaultValue) {\n if (CharUtils.isAsciiNumeric(ch) == false) {\n return defaultValue;\n }\n return ch - 48;\n }\n\n /**\n *

Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

\n *\n *

This method coverts the char '1' to the int 1 and so on.

\n *\n *
\n     *   CharUtils.toIntValue(null) = IllegalArgumentException\n     *   CharUtils.toIntValue('3')  = 3\n     *   CharUtils.toIntValue('A')  = IllegalArgumentException\n     * 
\n *\n * @param ch the character to convert, not null\n * @return the int value of the character\n * @throws IllegalArgumentException if the Character is not ASCII numeric or is null\n */\n public static int toIntValue(final Character ch) {\n if (ch == null) {\n throw new IllegalArgumentException(\"The character must not be null\");\n }\n return CharUtils.toIntValue(ch.charValue());\n }\n\n /**\n *

Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

\n *\n *

This method coverts the char '1' to the int 1 and so on.

\n *\n *
\n     *   CharUtils.toIntValue(null, -1) = -1\n     *   CharUtils.toIntValue('3', -1)  = 3\n     *   CharUtils.toIntValue('A', -1)  = -1\n     * 
\n *\n * @param ch the character to convert\n * @param defaultValue the default value to use if the character is not numeric\n * @return the int value of the character\n */\n public static int toIntValue(final Character ch, final int defaultValue) {\n if (ch == null) {\n return defaultValue;\n }\n return CharUtils.toIntValue(ch.charValue(), defaultValue);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

Converts the character to a String that contains the one character.

\n *\n *

For ASCII 7 bit characters, this uses a cache that will return the\n * same String object each time.

\n *\n *
\n     *   CharUtils.toString(' ')  = \" \"\n     *   CharUtils.toString('A')  = \"A\"\n     * 
\n *\n * @param ch the character to convert\n * @return a String containing the one specified character\n */\n public static String toString(final char ch) {\n if (ch < 128) {\n return CharUtils.CHAR_STRING_ARRAY[ch];\n }\n return new String(new char[] { ch });\n }\n\n /**\n *

Converts the character to a String that contains the one character.

\n *\n *

For ASCII 7 bit characters, this uses a cache that will return the\n * same String object each time.

\n *\n *

If null is passed in, null will be returned.

\n *\n *
\n     *   CharUtils.toString(null) = null\n     *   CharUtils.toString(' ')  = \" \"\n     *   CharUtils.toString('A')  = \"A\"\n     * 
\n *\n * @param ch the character to convert\n * @return a String containing the one specified character\n */\n public static String toString(final Character ch) {\n if (ch == null) {\n return null;\n }\n return CharUtils.toString(ch.charValue());\n }\n //--------------------------------------------------------------------------\n\n /**\n *

Converts the string to the unicode format '\\u0020'.

\n *\n *

This format is the Java source code format.

\n *\n *
\n     *   CharUtils.unicodeEscaped(' ') = \"\\u0020\"\n     *   CharUtils.unicodeEscaped('A') = \"\\u0041\"\n     * 
\n *\n * @param ch the character to convert\n * @return the escaped unicode string\n */\n public static String unicodeEscaped(final char ch) {\n if (ch < 0x10) {\n return \"\\\\u000\" + Integer.toHexString(ch);\n } else if (ch < 0x100) {\n return \"\\\\u00\" + Integer.toHexString(ch);\n } else if (ch < 0x1000) {\n return \"\\\\u0\" + Integer.toHexString(ch);\n }\n return \"\\\\u\" + Integer.toHexString(ch);\n }\n\n /**\n *

Converts the string to the unicode format '\\u0020'.

\n *\n *

This format is the Java source code format.

\n *\n *

If null is passed in, null will be returned.

\n *\n *
\n     *   CharUtils.unicodeEscaped(null) = null\n     *   CharUtils.unicodeEscaped(' ')  = \"\\u0020\"\n     *   CharUtils.unicodeEscaped('A')  = \"\\u0041\"\n     * 
\n *\n * @param ch the character to convert, may be null\n * @return the escaped unicode string, null if null input\n */\n public static String unicodeEscaped(final Character ch) {\n if (ch == null) {\n return null;\n }\n return CharUtils.unicodeEscaped(ch.charValue());\n }\n //--------------------------------------------------------------------------\n\n /**\n *

Checks whether the character is ASCII 7 bit.

\n *\n *
\n     *   CharUtils.isAscii('a')  = true\n     *   CharUtils.isAscii('A')  = true\n     *   CharUtils.isAscii('3')  = true\n     *   CharUtils.isAscii('-')  = true\n     *   CharUtils.isAscii('\\n') = true\n     *   CharUtils.isAscii('©') = false\n     * 
\n *\n * @param ch the character to check\n * @return true if less than 128\n */\n public static boolean isAscii(final char ch) {\n return ch < 128;\n }\n\n /**\n *

Checks whether the character is ASCII 7 bit printable.

\n *\n *
\n     *   CharUtils.isAsciiPrintable('a')  = true\n     *   CharUtils.isAsciiPrintable('A')  = true\n     *   CharUtils.isAsciiPrintable('3')  = true\n     *   CharUtils.isAsciiPrintable('-')  = true\n     *   CharUtils.isAsciiPrintable('\\n') = false\n     *   CharUtils.isAsciiPrintable('©') = false\n     * 
\n *\n * @param ch the character to check\n * @return true if between 32 and 126 inclusive\n */\n public static boolean isAsciiPrintable(final char ch) {\n return ch >= 32 && ch < 127;\n }\n\n /**\n *

Checks whether the character is ASCII 7 bit control.

\n *\n *
\n     *   CharUtils.isAsciiControl('a')  = false\n     *   CharUtils.isAsciiControl('A')  = false\n     *   CharUtils.isAsciiControl('3')  = false\n     *   CharUtils.isAsciiControl('-')  = false\n     *   CharUtils.isAsciiControl('\\n') = true\n     *   CharUtils.isAsciiControl('©') = false\n     * 
\n *\n * @param ch the character to check\n * @return true if less than 32 or equals 127\n */\n public static boolean isAsciiControl(final char ch) {\n return ch < 32 || ch == 127;\n }\n\n /**\n *

Checks whether the character is ASCII 7 bit alphabetic.

\n *\n *
\n     *   CharUtils.isAsciiAlpha('a')  = true\n     *   CharUtils.isAsciiAlpha('A')  = true\n     *   CharUtils.isAsciiAlpha('3')  = false\n     *   CharUtils.isAsciiAlpha('-')  = false\n     *   CharUtils.isAsciiAlpha('\\n') = false\n     *   CharUtils.isAsciiAlpha('©') = false\n     * 
\n *\n * @param ch the character to check\n * @return true if between 65 and 90 or 97 and 122 inclusive\n */\n public static boolean isAsciiAlpha(final char ch) {\n return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z';\n }\n\n /**\n *

Checks whether the character is ASCII 7 bit alphabetic upper case.

\n *\n *
\n     *   CharUtils.isAsciiAlphaUpper('a')  = false\n     *   CharUtils.isAsciiAlphaUpper('A')  = true\n     *   CharUtils.isAsciiAlphaUpper('3')  = false\n     *   CharUtils.isAsciiAlphaUpper('-')  = false\n     *   CharUtils.isAsciiAlphaUpper('\\n') = false\n     *   CharUtils.isAsciiAlphaUpper('©') = false\n     * 
\n *\n * @param ch the character to check\n * @return true if between 65 and 90 inclusive\n */\n public static boolean isAsciiAlphaUpper(final char ch) {\n return ch >= 'A' && ch <= 'Z';\n }\n\n /**\n *

Checks whether the character is ASCII 7 bit alphabetic lower case.

\n *\n *
\n     *   CharUtils.isAsciiAlphaLower('a')  = true\n     *   CharUtils.isAsciiAlphaLower('A')  = false\n     *   CharUtils.isAsciiAlphaLower('3')  = false\n     *   CharUtils.isAsciiAlphaLower('-')  = false\n     *   CharUtils.isAsciiAlphaLower('\\n') = false\n     *   CharUtils.isAsciiAlphaLower('©') = false\n     * 
\n *\n * @param ch the character to check\n * @return true if between 97 and 122 inclusive\n */\n public static boolean isAsciiAlphaLower(final char ch) {\n return ch >= 'a' && ch <= 'z';\n }\n\n /**\n *

Checks whether the character is ASCII 7 bit numeric.

\n *\n *
\n     *   CharUtils.isAsciiNumeric('a')  = false\n     *   CharUtils.isAsciiNumeric('A')  = false\n     *   CharUtils.isAsciiNumeric('3')  = true\n     *   CharUtils.isAsciiNumeric('-')  = false\n     *   CharUtils.isAsciiNumeric('\\n') = false\n     *   CharUtils.isAsciiNumeric('©') = false\n     * 
\n *\n * @param ch the character to check\n * @return true if between 48 and 57 inclusive\n */\n public static boolean isAsciiNumeric(final char ch) {\n return ch >= '0' && ch <= '9';\n }\n\n /**\n *

Checks whether the character is ASCII 7 bit numeric.

\n *\n *
\n     *   CharUtils.isAsciiAlphanumeric('a')  = true\n     *   CharUtils.isAsciiAlphanumeric('A')  = true\n     *   CharUtils.isAsciiAlphanumeric('3')  = true\n     *   CharUtils.isAsciiAlphanumeric('-')  = false\n     *   CharUtils.isAsciiAlphanumeric('\\n') = false\n     *   CharUtils.isAsciiAlphanumeric('©') = false\n     * 
\n *\n * @param ch the character to check\n * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive\n */\n public static boolean isAsciiAlphanumeric(final char ch) {\n return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9';\n }\n // ----------------- Following code copied from Apache Harmony (Character class)\n\n /**\n * Indicates whether {@code ch} is a high- (or leading-) surrogate code unit\n * that is used for representing supplementary characters in UTF-16\n * encoding.\n *\n * @param ch\n * the character to test.\n * @return {@code true} if {@code ch} is a high-surrogate code unit;\n * {@code false} otherwise.\n */\n static boolean isHighSurrogate(final char ch) {\n return '\\uD800' <= ch && '\\uDBFF' >= ch;\n }\n\n //\n public static boolean isCharType(Class targetType) {\n return targetType.equals(Character.class) || targetType.equals(Character.TYPE);\n }\n}\n", "file_name": "CharUtils.java", "human_label": "Obtains the character value of ch. If ch is null, defaultValue is returned.", "level": "self_contained", "lineno": "153", "name": "toChar", "oracle_context": "{ \"apis\" : \"[charValue]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "6367676b1a6d9265ec0181e2", "all_context": "{ \"class_level\" : \"import java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.List;\\nimport java.util.Map;\\nimport java.util.Properties;\\nEnumeration enumeration;\\nCollections();\\nsize(Collection collection);\\nsize(Map map);\\nisEmpty(Map map);\\narrayToList(Object source);\\nmergeArrayIntoCollection(Object array,Collection collection);\\nmergePropertiesIntoMap(Properties props,Map map);\\ncontains(Iterator iterator,Object element);\\ncontains(Enumeration enumeration,Object element);\\ncontainsInstance(Collection collection,Object element);\\ncontainsAny(Collection source,Collection candidates);\\nfindFirstMatch(Collection source,Collection candidates);\\nfindValueOfType(Collection collection,Class type);\\nfindValueOfType(Collection collection,Class[] types);\\nhasUniqueObject(Collection collection);\\nfindCommonElementType(Collection collection);\\ntoArray(Enumeration enumeration,A[] array);\\ntoIterator(Enumeration enumeration);\\nEnumerationIterator(Enumeration enumeration);\\nhasNext();\\nnext();\\nremove();\\nisEmpty(Collection collection);\\n\", \"repo_level\" : \"\" }", "class_name": "Collections", "code": "public static Object findFirstMatch(Collection source,Collection candidates){\n if (isEmpty(source) || isEmpty(candidates)) {\n return null;\n }\n for ( Object candidate : candidates) {\n if (source.contains(candidate)) {\n return candidate;\n }\n }\n return null;\n}\n", "docstring": "/** \n * Return the first element in 'candidates' that is contained in 'source'. If no element in 'candidates' is present in 'source' returns null. Iteration order is {@link Collection} implementation specific.\n * @param source the source Collection\n * @param candidates the candidates to search for\n * @return the first present object, or null if not found\n */\n", "end_lineno": "222", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\npublic final class Collections {\n\n private Collections(){} //prevent instantiation\n\n /**\n * Return true if the supplied Collection is null\n * or empty. Otherwise, return false.\n * @param collection the Collection to check\n * @return whether the given Collection is empty\n */\n public static boolean isEmpty(Collection collection) {\n return (collection == null || collection.isEmpty());\n }\n\n /**\n * Returns the collection's size or {@code 0} if the collection is {@code null}.\n *\n * @param collection the collection to check.\n * @return the collection's size or {@code 0} if the collection is {@code null}.\n * @since 0.9.2\n */\n public static int size(Collection collection) {\n return collection == null ? 0 : collection.size();\n }\n\n /**\n * Returns the map's size or {@code 0} if the map is {@code null}.\n *\n * @param map the map to check\n * @return the map's size or {@code 0} if the map is {@code null}.\n * @since 0.9.2\n */\n public static int size(Map map) {\n return map == null ? 0 : map.size();\n }\n\n /**\n * Return true if the supplied Map is null\n * or empty. Otherwise, return false.\n * @param map the Map to check\n * @return whether the given Map is empty\n */\n public static boolean isEmpty(Map map) {\n return (map == null || map.isEmpty());\n }\n\n /**\n * Convert the supplied array into a List. A primitive array gets\n * converted into a List of the appropriate wrapper type.\n *

A null source value will be converted to an\n * empty List.\n * @param source the (potentially primitive) array\n * @return the converted List result\n * @see Objects#toObjectArray(Object)\n */\n public static List arrayToList(Object source) {\n return Arrays.asList(Objects.toObjectArray(source));\n }\n\n /**\n * Merge the given array into the given Collection.\n * @param array the array to merge (may be null)\n * @param collection the target Collection to merge the array into\n */\n @SuppressWarnings(\"unchecked\")\n public static void mergeArrayIntoCollection(Object array, Collection collection) {\n if (collection == null) {\n throw new IllegalArgumentException(\"Collection must not be null\");\n }\n Object[] arr = Objects.toObjectArray(array);\n for (Object elem : arr) {\n collection.add(elem);\n }\n }\n\n /**\n * Merge the given Properties instance into the given Map,\n * copying all properties (key-value pairs) over.\n *

Uses Properties.propertyNames() to even catch\n * default properties linked into the original Properties instance.\n * @param props the Properties instance to merge (may be null)\n * @param map the target Map to merge the properties into\n */\n @SuppressWarnings(\"unchecked\")\n public static void mergePropertiesIntoMap(Properties props, Map map) {\n if (map == null) {\n throw new IllegalArgumentException(\"Map must not be null\");\n }\n if (props != null) {\n for (Enumeration en = props.propertyNames(); en.hasMoreElements();) {\n String key = (String) en.nextElement();\n Object value = props.getProperty(key);\n if (value == null) {\n // Potentially a non-String value...\n value = props.get(key);\n }\n map.put(key, value);\n }\n }\n }\n\n\n /**\n * Check whether the given Iterator contains the given element.\n * @param iterator the Iterator to check\n * @param element the element to look for\n * @return true if found, false else\n */\n public static boolean contains(Iterator iterator, Object element) {\n if (iterator != null) {\n while (iterator.hasNext()) {\n Object candidate = iterator.next();\n if (Objects.nullSafeEquals(candidate, element)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Check whether the given Enumeration contains the given element.\n * @param enumeration the Enumeration to check\n * @param element the element to look for\n * @return true if found, false else\n */\n public static boolean contains(Enumeration enumeration, Object element) {\n if (enumeration != null) {\n while (enumeration.hasMoreElements()) {\n Object candidate = enumeration.nextElement();\n if (Objects.nullSafeEquals(candidate, element)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Check whether the given Collection contains the given element instance.\n *

Enforces the given instance to be present, rather than returning\n * true for an equal element as well.\n * @param collection the Collection to check\n * @param element the element to look for\n * @return true if found, false else\n */\n public static boolean containsInstance(Collection collection, Object element) {\n if (collection != null) {\n for (Object candidate : collection) {\n if (candidate == element) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Return true if any element in 'candidates' is\n * contained in 'source'; otherwise returns false.\n * @param source the source Collection\n * @param candidates the candidates to search for\n * @return whether any of the candidates has been found\n */\n public static boolean containsAny(Collection source, Collection candidates) {\n if (isEmpty(source) || isEmpty(candidates)) {\n return false;\n }\n for (Object candidate : candidates) {\n if (source.contains(candidate)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Return the first element in 'candidates' that is contained in\n * 'source'. If no element in 'candidates' is present in\n * 'source' returns null. Iteration order is\n * {@link Collection} implementation specific.\n * @param source the source Collection\n * @param candidates the candidates to search for\n * @return the first present object, or null if not found\n */\n public static Object findFirstMatch(Collection source, Collection candidates) {\n if (isEmpty(source) || isEmpty(candidates)) {\n return null;\n }\n for (Object candidate : candidates) {\n if (source.contains(candidate)) {\n return candidate;\n }\n }\n return null;\n }\n\n /**\n * Find a single value of the given type in the given Collection.\n * @param collection the Collection to search\n * @param type the type to look for\n * @param the generic type parameter for {@code type}\n * @return a value of the given type found if there is a clear match,\n * or null if none or more than one such value found\n */\n @SuppressWarnings(\"unchecked\")\n public static T findValueOfType(Collection collection, Class type) {\n if (isEmpty(collection)) {\n return null;\n }\n T value = null;\n for (Object element : collection) {\n if (type == null || type.isInstance(element)) {\n if (value != null) {\n // More than one value found... no clear single value.\n return null;\n }\n value = (T) element;\n }\n }\n return value;\n }\n\n /**\n * Find a single value of one of the given types in the given Collection:\n * searching the Collection for a value of the first type, then\n * searching for a value of the second type, etc.\n * @param collection the collection to search\n * @param types the types to look for, in prioritized order\n * @return a value of one of the given types found if there is a clear match,\n * or null if none or more than one such value found\n */\n public static Object findValueOfType(Collection collection, Class[] types) {\n if (isEmpty(collection) || Objects.isEmpty(types)) {\n return null;\n }\n for (Class type : types) {\n Object value = findValueOfType(collection, type);\n if (value != null) {\n return value;\n }\n }\n return null;\n }\n\n /**\n * Determine whether the given Collection only contains a single unique object.\n * @param collection the Collection to check\n * @return true if the collection contains a single reference or\n * multiple references to the same instance, false else\n */\n public static boolean hasUniqueObject(Collection collection) {\n if (isEmpty(collection)) {\n return false;\n }\n boolean hasCandidate = false;\n Object candidate = null;\n for (Object elem : collection) {\n if (!hasCandidate) {\n hasCandidate = true;\n candidate = elem;\n }\n else if (candidate != elem) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Find the common element type of the given Collection, if any.\n * @param collection the Collection to check\n * @return the common element type, or null if no clear\n * common type has been found (or the collection was empty)\n */\n public static Class findCommonElementType(Collection collection) {\n if (isEmpty(collection)) {\n return null;\n }\n Class candidate = null;\n for (Object val : collection) {\n if (val != null) {\n if (candidate == null) {\n candidate = val.getClass();\n }\n else if (candidate != val.getClass()) {\n return null;\n }\n }\n }\n return candidate;\n }\n\n /**\n * Marshal the elements from the given enumeration into an array of the given type.\n * Enumeration elements must be assignable to the type of the given array. The array\n * returned will be a different instance than the array given.\n * @param enumeration the collection to convert to an array\n * @param array an array instance that matches the type of array to return\n * @param the element type of the array that will be created\n * @param the element type contained within the enumeration.\n * @return a new array of type {@code A} that contains the elements in the specified {@code enumeration}.\n */\n public static A[] toArray(Enumeration enumeration, A[] array) {\n ArrayList elements = new ArrayList();\n while (enumeration.hasMoreElements()) {\n elements.add(enumeration.nextElement());\n }\n return elements.toArray(array);\n }\n\n /**\n * Adapt an enumeration to an iterator.\n * @param enumeration the enumeration\n * @param the type of elements in the enumeration\n * @return the iterator\n */\n public static Iterator toIterator(Enumeration enumeration) {\n return new EnumerationIterator(enumeration);\n }\n\n /**\n * Iterator wrapping an Enumeration.\n */\n private static class EnumerationIterator implements Iterator {\n\n private Enumeration enumeration;\n\n public EnumerationIterator(Enumeration enumeration) {\n this.enumeration = enumeration;\n }\n\n public boolean hasNext() {\n return this.enumeration.hasMoreElements();\n }\n\n public E next() {\n return this.enumeration.nextElement();\n }\n\n public void remove() throws UnsupportedOperationException {\n throw new UnsupportedOperationException(\"Not supported\");\n }\n }\n}\n\n", "file_name": "Collections.java", "human_label": "Returns the first element in candidates that matches the source.", "level": "class_runnable", "lineno": "203", "name": "findFirstMatch", "oracle_context": "{ \"apis\" : \"[isEmpty, contains]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "6367676b1a6d9265ec0181ee", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static String trimTrailingWhitespace(String str){\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb=new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n}\n", "docstring": "/** \n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n", "end_lineno": "253", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *

\n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
\n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Trim the end space of the str.", "level": "class_runnable", "lineno": "238", "name": "trimTrailingWhitespace", "oracle_context": "{ \"apis\" : \"[hasLength, length, isWhitespace, charAt, deleteCharAt, toString]\", \"classes\" : \"[StringBuilder]\", \"vars\" : \"[]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636767dc1a6d9265ec0186cb", "all_context": "{ \"class_level\" : \"import lombok.Data;\\nimport java.io.File;\\nString taskId;\\nString traceId;\\nString analyzeResultDist;\\ninit();\\nparse(String[] args);\\n\", \"repo_level\" : \"\" }", "class_name": "ExporterConfig", "code": "public void init(){\n File dist=new File(analyzeResultDist);\n if (!dist.exists()) {\n dist.mkdirs();\n return;\n }\n if (dist.isFile()) {\n throw new IllegalArgumentException(analyzeResultDist + \" must be a directory\");\n }\n}\n", "docstring": "/** \n * initialize config, such as check dist path\n */\n", "end_lineno": "67", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.tool.profile.exporter;\n\nimport lombok.Data;\n\nimport java.io.File;\n\n@Data\npublic class ExporterConfig {\n\n // profile task id\n private String taskId;\n\n // profiled trace id\n private String traceId;\n\n // export to file path\n private String analyzeResultDist;\n\n /**\n * parse config from command line\n */\n public static ExporterConfig parse(String[] args) {\n if (args == null || args.length != 3) {\n throw new IllegalArgumentException(\"missing config, please recheck\");\n }\n\n // build config\n ExporterConfig config = new ExporterConfig();\n config.setTaskId(args[0]);\n config.setTraceId(args[1]);\n config.setAnalyzeResultDist(args[2]);\n\n return config;\n }\n\n /**\n * initialize config, such as check dist path\n */\n public void init() {\n File dist = new File(analyzeResultDist);\n if (!dist.exists()) {\n dist.mkdirs();\n return;\n }\n\n if (dist.isFile()) {\n throw new IllegalArgumentException(analyzeResultDist + \" must be a directory\");\n }\n }\n}\n", "file_name": "ExporterConfig.java", "human_label": "Initializes a directory.", "level": "slib_runnable", "lineno": "54", "name": "init", "oracle_context": "{ \"apis\" : \"[exists, mkdirs, isFile]\", \"classes\" : \"[File]\", \"vars\" : \"[analyzeResultDist]\" }", "package": "org.apache.skywalking.oap.server.tool.profile.exporter", "project": "skywalking-master" }, { "_id": "636767a31a6d9265ec018552", "all_context": "{ \"class_level\" : \"import java.io.DataInput;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport java.nio.ByteBuffer;\\nimport java.util.ArrayList;\\nimport java.util.List;\\nimport io.protostuff.StringSerializer.STRING;\\nimport static io.protostuff.WireFormat.TAG_TYPE_BITS;\\nimport static io.protostuff.WireFormat.TAG_TYPE_MASK;\\nimport static io.protostuff.WireFormat.WIRETYPE_END_GROUP;\\nimport static io.protostuff.WireFormat.WIRETYPE_LENGTH_DELIMITED;\\nimport static io.protostuff.WireFormat.WIRETYPE_TAIL_DELIMITER;\\nbyte[] buffer;\\nint bufferSize;\\nint bufferSizeAfterLimit;\\nint bufferPos;\\nInputStream input;\\nint lastTag;\\nint packedLimit;\\nint totalBytesRetired;\\nint currentLimit;\\nboolean decodeNestedMessageAsGroup;\\nint sizeLimit;\\nint DEFAULT_SIZE_LIMIT;\\nint DEFAULT_BUFFER_SIZE;\\nnewInstance(byte[] buf);\\nnewInstance(byte[] buf,int off,int len);\\nreadTag();\\ncheckLastTagWas(int value);\\nskipField(int tag);\\nskipMessage();\\nreadDouble();\\nreadFloat();\\nreadUInt64();\\nreadInt64();\\nreadInt32();\\nreadFixed64();\\nreadFixed32();\\nreadBool();\\nreadString();\\nreadBytes(ByteBuffer bb);\\nmergeObject(T value,Schema schema);\\nmergeObjectEncodedAsGroup(T value,Schema schema);\\nreadBytes();\\nreadUInt32();\\nreadEnum();\\nreadSFixed32();\\nreadSFixed64();\\nreadSInt32();\\nreadSInt64();\\nreadRawVarint32();\\nreadRawVarint32(InputStream input);\\nreadRawVarint32(InputStream input,int firstByte);\\nreadRawVarint32(DataInput input,byte firstByte);\\nreadRawVarint64();\\nreadRawLittleEndian32();\\nreadRawLittleEndian64();\\ndecodeZigZag32(int n);\\ndecodeZigZag64(long n);\\nCodedInput(byte[] buffer,int off,int len,boolean decodeNestedMessageAsGroup);\\nCodedInput(InputStream input,boolean decodeNestedMessageAsGroup);\\nCodedInput(InputStream input,byte[] buffer,boolean decodeNestedMessageAsGroup);\\nCodedInput(InputStream input,byte[] buffer,int offset,int limit,boolean decodeNestedMessageAsGroup);\\nsetSizeLimit(int limit);\\nresetSizeCounter();\\nreset();\\npushLimit(int byteLimit);\\nrecomputeBufferSizeAfterLimit();\\npopLimit(int oldLimit);\\ngetBytesUntilLimit();\\nisCurrentFieldPacked();\\nisAtEnd();\\ngetTotalBytesRead();\\nrefillBuffer(boolean mustSucceed);\\nreadRawByte();\\nreadRawBytes(int size);\\nskipRawBytes(int size);\\nreadFieldNumber(Schema schema);\\ncheckIfPackedField();\\nreadByteArray();\\nhandleUnknownField(int fieldNumber,Schema schema);\\ntransferByteRangeTo(Output output,boolean utf8String,int fieldNumber,boolean repeated);\\ngetLastTag();\\nreadByteBuffer();\\nnewInstance(InputStream input);\\n\", \"repo_level\" : \"\" }", "class_name": "CodedInput", "code": "@Override public String readString() throws IOException {\n final int size=readRawVarint32();\n if (size <= (bufferSize - bufferPos) && size > 0) {\n final String result=STRING.deser(buffer,bufferPos,size);\n bufferPos+=size;\n return result;\n }\n else {\n return STRING.deser(readRawBytes(size));\n }\n}\n", "docstring": "/** \n * Read a {@code string} field value from the stream.\n */\n", "end_lineno": "292", "file_content": "//========================================================================\n//Copyright 2007-2009 David Yu dyuproject@gmail.com\n//------------------------------------------------------------------------\n//Licensed under the Apache License, Version 2.0 (the \"License\");\n//you may not use this file except in compliance with the License.\n//You may obtain a copy of the License at \n//http://www.apache.org/licenses/LICENSE-2.0\n//Unless required by applicable law or agreed to in writing, software\n//distributed under the License is distributed on an \"AS IS\" BASIS,\n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//See the License for the specific language governing permissions and\n//limitations under the License.\n//========================================================================\n\n// Protocol Buffers - Google's data interchange format\n// Copyright 2008 Google Inc. All rights reserved.\n// http://code.google.com/p/protobuf/\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\npackage io.protostuff;\n\nimport java.io.DataInput;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport io.protostuff.StringSerializer.STRING;\n\nimport static io.protostuff.WireFormat.TAG_TYPE_BITS;\nimport static io.protostuff.WireFormat.TAG_TYPE_MASK;\nimport static io.protostuff.WireFormat.WIRETYPE_END_GROUP;\nimport static io.protostuff.WireFormat.WIRETYPE_LENGTH_DELIMITED;\nimport static io.protostuff.WireFormat.WIRETYPE_TAIL_DELIMITER;\n\n/**\n * Reads and decodes protocol message fields.\n *

\n * This class contains two kinds of methods: methods that read specific protocol message constructs and field types\n * (e.g. {@link #readTag()} and {@link #readInt32()}) and methods that read low-level values (e.g.\n * {@link #readRawVarint32()} and {@link #readRawBytes}). If you are reading encoded protocol messages, you should use\n * the former methods, but if you are reading some other format of your own design, use the latter.\n *\n * @author kenton@google.com Kenton Varda\n * @author David Yu\n */\npublic final class CodedInput implements Input\n{\n /**\n * Create a new CodedInput wrapping the given InputStream.\n */\n public static CodedInput newInstance(final InputStream input)\n {\n return new CodedInput(input, false);\n }\n\n /**\n * Create a new CodedInput wrapping the given byte array.\n */\n public static CodedInput newInstance(final byte[] buf)\n {\n return newInstance(buf, 0, buf.length);\n }\n\n /**\n * Create a new CodedInput wrapping the given byte array slice.\n */\n public static CodedInput newInstance(final byte[] buf, final int off,\n final int len)\n {\n return new CodedInput(buf, off, len, false);\n }\n\n // -----------------------------------------------------------------\n\n /**\n * Attempt to read a field tag, returning zero if we have reached EOF. Protocol message parsers use this to read\n * tags, since a protocol message may legally end wherever a tag occurs, and zero is not a valid tag number.\n */\n public int readTag() throws IOException\n {\n if (isAtEnd())\n {\n lastTag = 0;\n return 0;\n }\n\n final int tag = readRawVarint32();\n if (tag >>> TAG_TYPE_BITS == 0)\n {\n // If we actually read zero, that's not a valid tag.\n throw ProtobufException.invalidTag();\n }\n lastTag = tag;\n return tag;\n }\n\n /**\n * Verifies that the last call to readTag() returned the given tag value. This is used to verify that a nested group\n * ended with the correct end tag.\n *\n * @throws ProtobufException\n * {@code value} does not match the last tag.\n */\n public void checkLastTagWas(final int value)\n throws ProtobufException\n {\n if (lastTag != value)\n {\n throw ProtobufException.invalidEndTag();\n }\n }\n\n /**\n * Reads and discards a single field, given its tag value.\n *\n * @return {@code false} if the tag is an endgroup tag, in which case nothing is skipped. Otherwise, returns\n * {@code true}.\n */\n public boolean skipField(final int tag) throws IOException\n {\n switch (WireFormat.getTagWireType(tag))\n {\n case WireFormat.WIRETYPE_VARINT:\n readInt32();\n return true;\n case WireFormat.WIRETYPE_FIXED64:\n readRawLittleEndian64();\n return true;\n case WireFormat.WIRETYPE_LENGTH_DELIMITED:\n skipRawBytes(readRawVarint32());\n return true;\n case WireFormat.WIRETYPE_START_GROUP:\n skipMessage();\n checkLastTagWas(WireFormat.makeTag(WireFormat.getTagFieldNumber(tag),\n WireFormat.WIRETYPE_END_GROUP));\n return true;\n case WireFormat.WIRETYPE_END_GROUP:\n return false;\n case WireFormat.WIRETYPE_FIXED32:\n readRawLittleEndian32();\n return true;\n default:\n throw ProtobufException.invalidWireType();\n }\n }\n\n /**\n * Reads and discards an entire message. This will read either until EOF or until an endgroup tag, whichever comes\n * first.\n */\n public void skipMessage() throws IOException\n {\n while (true)\n {\n final int tag = readTag();\n if (tag == 0 || !skipField(tag))\n {\n return;\n }\n }\n }\n\n // -----------------------------------------------------------------\n\n /**\n * Read a {@code double} field value from the stream.\n */\n @Override\n public double readDouble() throws IOException\n {\n checkIfPackedField();\n return Double.longBitsToDouble(readRawLittleEndian64());\n }\n\n /**\n * Read a {@code float} field value from the stream.\n */\n @Override\n public float readFloat() throws IOException\n {\n checkIfPackedField();\n return Float.intBitsToFloat(readRawLittleEndian32());\n }\n\n /**\n * Read a {@code uint64} field value from the stream.\n */\n @Override\n public long readUInt64() throws IOException\n {\n checkIfPackedField();\n return readRawVarint64();\n }\n\n /**\n * Read an {@code int64} field value from the stream.\n */\n @Override\n public long readInt64() throws IOException\n {\n checkIfPackedField();\n return readRawVarint64();\n }\n\n /**\n * Read an {@code int32} field value from the stream.\n */\n @Override\n public int readInt32() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32();\n }\n\n /**\n * Read a {@code fixed64} field value from the stream.\n */\n @Override\n public long readFixed64() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian64();\n }\n\n /**\n * Read a {@code fixed32} field value from the stream.\n */\n @Override\n public int readFixed32() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian32();\n }\n\n /**\n * Read a {@code bool} field value from the stream.\n */\n @Override\n public boolean readBool() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32() != 0;\n }\n\n /**\n * Read a {@code string} field value from the stream.\n */\n @Override\n public String readString() throws IOException\n {\n final int size = readRawVarint32();\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer, so\n // just copy directly from it.\n final String result = STRING.deser(buffer, bufferPos, size);\n bufferPos += size;\n return result;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n return STRING.deser(readRawBytes(size));\n }\n }\n\n /**\n * Read a {@code string} field value from the stream into a ByteBuffer.\n */\n @Override\n public void readBytes(final ByteBuffer bb) throws IOException\n {\n final int size = readRawVarint32();\n\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer, so\n // just copy directly from it.\n bb.limit(size);\n bb.put(buffer, bufferPos, size);\n bufferPos += size;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n bb.put(readRawBytes(size));\n }\n }\n\n @Override\n public T mergeObject(T value, final Schema schema) throws IOException\n {\n if (decodeNestedMessageAsGroup)\n return mergeObjectEncodedAsGroup(value, schema);\n\n final int length = readRawVarint32();\n // if (recursionDepth >= recursionLimit) {\n // throw ProtobufException.recursionLimitExceeded();\n // }\n final int oldLimit = pushLimit(length);\n // ++recursionDepth;\n\n if (value == null)\n {\n value = schema.newMessage();\n }\n schema.mergeFrom(this, value);\n if (!schema.isInitialized(value))\n {\n throw new UninitializedMessageException(value, schema);\n }\n checkLastTagWas(0);\n // --recursionDepth;\n popLimit(oldLimit);\n return value;\n }\n\n /**\n * Reads a message field value from the stream (using the {@code group} encoding).\n */\n private T mergeObjectEncodedAsGroup(T value, final Schema schema) throws IOException\n {\n // if (recursionDepth >= recursionLimit) {\n // throw ProtobufException.recursionLimitExceeded();\n // }\n // ++recursionDepth;\n\n if (value == null)\n {\n value = schema.newMessage();\n }\n schema.mergeFrom(this, value);\n if (!schema.isInitialized(value))\n {\n throw new UninitializedMessageException(value, schema);\n }\n // handling is in #readFieldNumber\n checkLastTagWas(0);\n // --recursionDepth;\n return value;\n }\n\n /*\n * @ Reads a {@code group} field value from the stream and merges it into the given {@link UnknownFieldSet}.\n * \n * @deprecated UnknownFieldSet.Builder now implements MessageLite.Builder, so you can just call {@link #readGroup}.\n */\n /*\n * @Deprecated public void readUnknownGroup(final int fieldNumber, final MessageLite.Builder builder) throws\n * IOException { // We know that UnknownFieldSet will ignore any ExtensionRegistry so it // is safe to pass null\n * here. (We can't call // ExtensionRegistry.getEmptyRegistry() because that would make this // class depend on\n * ExtensionRegistry, which is not part of the lite // library.) readGroup(fieldNumber, builder, null); }\n */\n\n /**\n * Read a {@code bytes} field value from the stream.\n */\n @Override\n public ByteString readBytes() throws IOException\n {\n final int size = readRawVarint32();\n if (size == 0)\n {\n return ByteString.EMPTY;\n }\n\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer, so\n // just copy directly from it.\n final ByteString result = ByteString.copyFrom(buffer, bufferPos, size);\n bufferPos += size;\n return result;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n // return ByteString.copyFrom(readRawBytes(size));\n return ByteString.wrap(readRawBytes(size));\n }\n }\n\n /**\n * Read a {@code uint32} field value from the stream.\n */\n @Override\n public int readUInt32() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32();\n }\n\n /**\n * Read an enum field value from the stream. Caller is responsible for converting the numeric value to an actual\n * enum.\n */\n @Override\n public int readEnum() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32();\n }\n\n /**\n * Read an {@code sfixed32} field value from the stream.\n */\n @Override\n public int readSFixed32() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian32();\n }\n\n /**\n * Read an {@code sfixed64} field value from the stream.\n */\n @Override\n public long readSFixed64() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian64();\n }\n\n /**\n * Read an {@code sint32} field value from the stream.\n */\n @Override\n public int readSInt32() throws IOException\n {\n checkIfPackedField();\n return decodeZigZag32(readRawVarint32());\n }\n\n /**\n * Read an {@code sint64} field value from the stream.\n */\n @Override\n public long readSInt64() throws IOException\n {\n checkIfPackedField();\n return decodeZigZag64(readRawVarint64());\n }\n\n // =================================================================\n\n /**\n * Read a raw Varint from the stream. If larger than 32 bits, discard the upper bits.\n */\n public int readRawVarint32() throws IOException\n {\n byte tmp = readRawByte();\n if (tmp >= 0)\n {\n return tmp;\n }\n int result = tmp & 0x7f;\n if ((tmp = readRawByte()) >= 0)\n {\n result |= tmp << 7;\n }\n else\n {\n result |= (tmp & 0x7f) << 7;\n if ((tmp = readRawByte()) >= 0)\n {\n result |= tmp << 14;\n }\n else\n {\n result |= (tmp & 0x7f) << 14;\n if ((tmp = readRawByte()) >= 0)\n {\n result |= tmp << 21;\n }\n else\n {\n result |= (tmp & 0x7f) << 21;\n result |= (tmp = readRawByte()) << 28;\n if (tmp < 0)\n {\n // Discard upper 32 bits.\n for (int i = 0; i < 5; i++)\n {\n if (readRawByte() >= 0)\n {\n return result;\n }\n }\n throw ProtobufException.malformedVarint();\n }\n }\n }\n }\n return result;\n }\n\n /**\n * Reads a varint from the input one byte at a time, so that it does not read any bytes after the end of the varint.\n * If you simply wrapped the stream in a CodedInput and used {@link #readRawVarint32(InputStream)} then you would\n * probably end up reading past the end of the varint since CodedInput buffers its input.\n */\n static int readRawVarint32(final InputStream input) throws IOException\n {\n final int firstByte = input.read();\n if (firstByte == -1)\n {\n throw ProtobufException.truncatedMessage();\n }\n\n if ((firstByte & 0x80) == 0)\n {\n return firstByte;\n }\n return readRawVarint32(input, firstByte);\n }\n\n /**\n * Reads a varint from the input one byte at a time, so that it does not read any bytes after the end of the varint.\n * If you simply wrapped the stream in a CodedInput and used {@link #readRawVarint32(InputStream)} then you would\n * probably end up reading past the end of the varint since CodedInput buffers its input.\n */\n static int readRawVarint32(final InputStream input, final int firstByte) throws IOException\n {\n int result = firstByte & 0x7f;\n int offset = 7;\n for (; offset < 32; offset += 7)\n {\n final int b = input.read();\n if (b == -1)\n {\n throw ProtobufException.truncatedMessage();\n }\n result |= (b & 0x7f) << offset;\n if ((b & 0x80) == 0)\n {\n return result;\n }\n }\n // Keep reading up to 64 bits.\n for (; offset < 64; offset += 7)\n {\n final int b = input.read();\n if (b == -1)\n {\n throw ProtobufException.truncatedMessage();\n }\n if ((b & 0x80) == 0)\n {\n return result;\n }\n }\n throw ProtobufException.malformedVarint();\n }\n\n /**\n * Reads a varint from the input one byte at a time from a {@link DataInput}, so that it does not read any bytes\n * after the end of the varint.\n */\n static int readRawVarint32(final DataInput input, final byte firstByte) throws IOException\n {\n int result = firstByte & 0x7f;\n int offset = 7;\n for (; offset < 32; offset += 7)\n {\n final byte b = input.readByte();\n result |= (b & 0x7f) << offset;\n if ((b & 0x80) == 0)\n {\n return result;\n }\n }\n // Keep reading up to 64 bits.\n for (; offset < 64; offset += 7)\n {\n final byte b = input.readByte();\n if ((b & 0x80) == 0)\n {\n return result;\n }\n }\n throw ProtobufException.malformedVarint();\n }\n\n /**\n * Read a raw Varint from the stream.\n */\n public long readRawVarint64() throws IOException\n {\n int shift = 0;\n long result = 0;\n while (shift < 64)\n {\n final byte b = readRawByte();\n result |= (long) (b & 0x7F) << shift;\n if ((b & 0x80) == 0)\n {\n return result;\n }\n shift += 7;\n }\n throw ProtobufException.malformedVarint();\n }\n\n /**\n * Read a 32-bit little-endian integer from the stream.\n */\n public int readRawLittleEndian32() throws IOException\n {\n final byte b1 = readRawByte();\n final byte b2 = readRawByte();\n final byte b3 = readRawByte();\n final byte b4 = readRawByte();\n return (((int) b1 & 0xff)) |\n (((int) b2 & 0xff) << 8) |\n (((int) b3 & 0xff) << 16) |\n (((int) b4 & 0xff) << 24);\n }\n\n /**\n * Read a 64-bit little-endian integer from the stream.\n */\n public long readRawLittleEndian64() throws IOException\n {\n final byte b1 = readRawByte();\n final byte b2 = readRawByte();\n final byte b3 = readRawByte();\n final byte b4 = readRawByte();\n final byte b5 = readRawByte();\n final byte b6 = readRawByte();\n final byte b7 = readRawByte();\n final byte b8 = readRawByte();\n return (((long) b1 & 0xff)) |\n (((long) b2 & 0xff) << 8) |\n (((long) b3 & 0xff) << 16) |\n (((long) b4 & 0xff) << 24) |\n (((long) b5 & 0xff) << 32) |\n (((long) b6 & 0xff) << 40) |\n (((long) b7 & 0xff) << 48) |\n (((long) b8 & 0xff) << 56);\n }\n\n /**\n * Decode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers into values that can be efficiently encoded\n * with varint. (Otherwise, negative values must be sign-extended to 64 bits to be varint encoded, thus always\n * taking 10 bytes on the wire.)\n *\n * @param n\n * An unsigned 32-bit integer, stored in a signed int because Java has no explicit unsigned support.\n * @return A signed 32-bit integer.\n */\n public static int decodeZigZag32(final int n)\n {\n return (n >>> 1) ^ -(n & 1);\n }\n\n /**\n * Decode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers into values that can be efficiently encoded\n * with varint. (Otherwise, negative values must be sign-extended to 64 bits to be varint encoded, thus always\n * taking 10 bytes on the wire.)\n *\n * @param n\n * An unsigned 64-bit integer, stored in a signed int because Java has no explicit unsigned support.\n * @return A signed 64-bit integer.\n */\n public static long decodeZigZag64(final long n)\n {\n return (n >>> 1) ^ -(n & 1);\n }\n\n // -----------------------------------------------------------------\n\n private final byte[] buffer;\n private int bufferSize;\n private int bufferSizeAfterLimit;\n private int bufferPos;\n private final InputStream input;\n private int lastTag;\n private int packedLimit = 0;\n\n /**\n * The total number of bytes read before the current buffer. The total bytes read up to the current position can be\n * computed as {@code totalBytesRetired + bufferPos}. This value may be negative if reading started in the middle of\n * the current buffer (e.g. if the constructor that takes a byte array and an offset was used).\n */\n private int totalBytesRetired;\n\n /**\n * The absolute position of the end of the current message.\n */\n private int currentLimit = Integer.MAX_VALUE;\n\n // ** See setRecursionLimit() */\n // private int recursionDepth;\n // private int recursionLimit = DEFAULT_RECURSION_LIMIT;\n\n /**\n * If true, the nested messages are group-encoded\n */\n public final boolean decodeNestedMessageAsGroup;\n\n /**\n * See setSizeLimit()\n */\n private int sizeLimit = DEFAULT_SIZE_LIMIT;\n\n // static final int DEFAULT_RECURSION_LIMIT = 64;\n static final int DEFAULT_SIZE_LIMIT = 64 << 20; // 64MB\n static final int DEFAULT_BUFFER_SIZE = 4096;\n\n public CodedInput(final byte[] buffer, final int off, final int len,\n boolean decodeNestedMessageAsGroup)\n {\n this.buffer = buffer;\n bufferSize = off + len;\n bufferPos = off;\n totalBytesRetired = -off;\n input = null;\n this.decodeNestedMessageAsGroup = decodeNestedMessageAsGroup;\n }\n\n public CodedInput(final InputStream input, boolean decodeNestedMessageAsGroup)\n {\n this(input, new byte[DEFAULT_BUFFER_SIZE], 0, 0, decodeNestedMessageAsGroup);\n }\n\n public CodedInput(final InputStream input, byte[] buffer,\n boolean decodeNestedMessageAsGroup)\n {\n this(input, buffer, 0, 0, decodeNestedMessageAsGroup);\n }\n\n public CodedInput(final InputStream input, byte[] buffer, int offset, int limit,\n boolean decodeNestedMessageAsGroup)\n {\n this.buffer = buffer;\n bufferSize = limit;\n bufferPos = offset;\n totalBytesRetired = -offset;\n this.input = input;\n this.decodeNestedMessageAsGroup = decodeNestedMessageAsGroup;\n }\n\n /*\n * Set the maximum message recursion depth. In order to prevent malicious messages from causing stack overflows,\n * {@code CodedInput} limits how deeply messages may be nested. The default limit is 64.\n * \n * @return the old limit.\n * \n * public int setRecursionLimit(final int limit) { if (limit < 0) { throw new IllegalArgumentException(\n * \"Recursion limit cannot be negative: \" + limit); } final int oldLimit = recursionLimit; recursionLimit = limit;\n * return oldLimit; }\n */\n\n /**\n * Set the maximum message size. In order to prevent malicious messages from exhausting memory or causing integer\n * overflows, {@code CodedInput} limits how large a message may be. The default limit is 64MB. You should set this\n * limit as small as you can without harming your app's functionality. Note that size limits only apply when reading\n * from an {@code InputStream}, not when constructed around a raw byte array.\n *

\n * If you want to read several messages from a single CodedInput, you could call {@link #resetSizeCounter()} after\n * each one to avoid hitting the size limit.\n *\n * @return the old limit.\n */\n public int setSizeLimit(final int limit)\n {\n if (limit < 0)\n {\n throw new IllegalArgumentException(\n \"Size limit cannot be negative: \" + limit);\n }\n final int oldLimit = sizeLimit;\n sizeLimit = limit;\n return oldLimit;\n }\n\n /**\n * Resets the current size counter to zero (see {@link #setSizeLimit(int)}). The field {@code totalBytesRetired}\n * will be negative if the initial position was not zero.\n */\n public void resetSizeCounter()\n {\n totalBytesRetired = -bufferPos;\n }\n\n /**\n * Resets the buffer position and limit to re-use this CodedInput object.\n */\n public void reset()\n {\n this.bufferSize = 0;\n this.bufferPos = 0;\n this.bufferSizeAfterLimit = 0;\n this.currentLimit = Integer.MAX_VALUE;\n this.lastTag = 0;\n this.packedLimit = 0;\n this.sizeLimit = DEFAULT_SIZE_LIMIT;\n resetSizeCounter();\n }\n\n /**\n * Note that {@code pushLimit()} does NOT affect how many bytes the {@code CodedInputStream} reads from an\n * underlying {@code InputStream} when refreshing its buffer. If you need to prevent reading past a certain point in\n * the underlying {@code InputStream} (e.g. because you expect it to contain more data after the end of the message\n * which you need to handle differently) then you must place a wrapper around your {@code InputStream} which limits\n * the amount of data that can be read from it.\n *\n * @return the old limit.\n */\n public int pushLimit(int byteLimit) throws ProtobufException\n {\n if (byteLimit < 0)\n {\n throw ProtobufException.negativeSize();\n }\n byteLimit += totalBytesRetired + bufferPos;\n final int oldLimit = currentLimit;\n if (byteLimit > oldLimit)\n {\n throw ProtobufException.truncatedMessage();\n }\n currentLimit = byteLimit;\n\n recomputeBufferSizeAfterLimit();\n\n return oldLimit;\n }\n\n private void recomputeBufferSizeAfterLimit()\n {\n bufferSize += bufferSizeAfterLimit;\n final int bufferEnd = totalBytesRetired + bufferSize;\n if (bufferEnd > currentLimit)\n {\n // Limit is in current buffer.\n bufferSizeAfterLimit = bufferEnd - currentLimit;\n bufferSize -= bufferSizeAfterLimit;\n }\n else\n {\n bufferSizeAfterLimit = 0;\n }\n }\n\n /**\n * Discards the current limit, returning to the previous limit.\n *\n * @param oldLimit\n * The old limit, as returned by {@code pushLimit}.\n */\n public void popLimit(final int oldLimit)\n {\n currentLimit = oldLimit;\n recomputeBufferSizeAfterLimit();\n }\n\n /**\n * Returns the number of bytes to be read before the current limit. If no limit is set, returns -1.\n */\n public int getBytesUntilLimit()\n {\n if (currentLimit == Integer.MAX_VALUE)\n {\n return -1;\n }\n\n final int currentAbsolutePosition = totalBytesRetired + bufferPos;\n return currentLimit - currentAbsolutePosition;\n }\n\n /**\n * Return true if currently reading packed field\n */\n public boolean isCurrentFieldPacked()\n {\n return packedLimit != 0 && packedLimit != getTotalBytesRead();\n }\n\n /**\n * Returns true if the stream has reached the end of the input. This is the case if either the end of the underlying\n * input source has been reached or if the stream has reached a limit created using {@link #pushLimit(int)}.\n */\n public boolean isAtEnd() throws IOException\n {\n return bufferPos == bufferSize && !refillBuffer(false);\n }\n\n /**\n * The total bytes read up to the current position. Calling {@link #resetSizeCounter()} resets this value to zero.\n */\n public int getTotalBytesRead()\n {\n return totalBytesRetired + bufferPos;\n }\n\n /**\n * Called with {@code this.buffer} is empty to read more bytes from the input. If {@code mustSucceed} is true,\n * refillBuffer() guarantees that either there will be at least one byte in the buffer when it returns or it will\n * throw an exception. If {@code mustSucceed} is false, refillBuffer() returns false if no more bytes were\n * available.\n */\n private boolean refillBuffer(final boolean mustSucceed) throws IOException\n {\n if (bufferPos < bufferSize)\n {\n throw new IllegalStateException(\n \"refillBuffer() called when buffer wasn't empty.\");\n }\n\n if (totalBytesRetired + bufferSize == currentLimit)\n {\n // Oops, we hit a limit.\n if (mustSucceed)\n {\n throw ProtobufException.truncatedMessage();\n }\n else\n {\n return false;\n }\n }\n\n totalBytesRetired += bufferSize;\n\n bufferPos = 0;\n bufferSize = (input == null) ? -1 : input.read(buffer);\n if (bufferSize == 0 || bufferSize < -1)\n {\n throw new IllegalStateException(\n \"InputStream#read(byte[]) returned invalid result: \" + bufferSize +\n \"\\nThe InputStream implementation is buggy.\");\n }\n if (bufferSize == -1)\n {\n bufferSize = 0;\n if (mustSucceed)\n {\n throw ProtobufException.truncatedMessage();\n }\n else\n {\n return false;\n }\n }\n else\n {\n recomputeBufferSizeAfterLimit();\n final int totalBytesRead =\n totalBytesRetired + bufferSize + bufferSizeAfterLimit;\n if (totalBytesRead > sizeLimit || totalBytesRead < 0)\n {\n throw ProtobufException.sizeLimitExceeded();\n }\n return true;\n }\n }\n\n /**\n * Read one byte from the input.\n *\n * @throws ProtobufException\n * The end of the stream or the current limit was reached.\n */\n public byte readRawByte() throws IOException\n {\n if (bufferPos == bufferSize)\n {\n refillBuffer(true);\n }\n return buffer[bufferPos++];\n }\n\n /**\n * Read a fixed size of bytes from the input.\n *\n * @throws ProtobufException\n * The end of the stream or the current limit was reached.\n */\n public byte[] readRawBytes(final int size) throws IOException\n {\n if (size < 0)\n {\n throw ProtobufException.negativeSize();\n }\n\n if (totalBytesRetired + bufferPos + size > currentLimit)\n {\n // Read to the end of the stream anyway.\n skipRawBytes(currentLimit - totalBytesRetired - bufferPos);\n // Then fail.\n throw ProtobufException.truncatedMessage();\n }\n\n if (size <= bufferSize - bufferPos)\n {\n // We have all the bytes we need already.\n final byte[] bytes = new byte[size];\n System.arraycopy(buffer, bufferPos, bytes, 0, size);\n bufferPos += size;\n return bytes;\n }\n else if (size < buffer.length)\n {\n // Reading more bytes than are in the buffer, but not an excessive number\n // of bytes. We can safely allocate the resulting array ahead of time.\n\n // First copy what we have.\n final byte[] bytes = new byte[size];\n int pos = bufferSize - bufferPos;\n System.arraycopy(buffer, bufferPos, bytes, 0, pos);\n bufferPos = bufferSize;\n\n // We want to use refillBuffer() and then copy from the buffer into our\n // byte array rather than reading directly into our byte array because\n // the input may be unbuffered.\n refillBuffer(true);\n\n while (size - pos > bufferSize)\n {\n System.arraycopy(buffer, 0, bytes, pos, bufferSize);\n pos += bufferSize;\n bufferPos = bufferSize;\n refillBuffer(true);\n }\n\n System.arraycopy(buffer, 0, bytes, pos, size - pos);\n bufferPos = size - pos;\n\n return bytes;\n }\n else\n {\n // The size is very large. For security reasons, we can't allocate the\n // entire byte array yet. The size comes directly from the input, so a\n // maliciously-crafted message could provide a bogus very large size in\n // order to trick the app into allocating a lot of memory. We avoid this\n // by allocating and reading only a small chunk at a time, so that the\n // malicious message must actually *be* extremely large to cause\n // problems. Meanwhile, we limit the allowed size of a message elsewhere.\n\n // Remember the buffer markers since we'll have to copy the bytes out of\n // it later.\n final int originalBufferPos = bufferPos;\n final int originalBufferSize = bufferSize;\n\n // Mark the current buffer consumed.\n totalBytesRetired += bufferSize;\n bufferPos = 0;\n bufferSize = 0;\n\n // Read all the rest of the bytes we need.\n int sizeLeft = size - (originalBufferSize - originalBufferPos);\n final List chunks = new ArrayList();\n\n while (sizeLeft > 0)\n {\n final byte[] chunk = new byte[Math.min(sizeLeft, buffer.length)];\n int pos = 0;\n while (pos < chunk.length)\n {\n final int n = (input == null) ? -1 :\n input.read(chunk, pos, chunk.length - pos);\n if (n == -1)\n {\n throw ProtobufException.truncatedMessage();\n }\n totalBytesRetired += n;\n pos += n;\n }\n sizeLeft -= chunk.length;\n chunks.add(chunk);\n }\n\n // OK, got everything. Now concatenate it all into one buffer.\n final byte[] bytes = new byte[size];\n\n // Start by copying the leftover bytes from this.buffer.\n int pos = originalBufferSize - originalBufferPos;\n System.arraycopy(buffer, originalBufferPos, bytes, 0, pos);\n\n // And now all the chunks.\n for (final byte[] chunk : chunks)\n {\n System.arraycopy(chunk, 0, bytes, pos, chunk.length);\n pos += chunk.length;\n }\n\n // Done.\n return bytes;\n }\n }\n\n /**\n * Reads and discards {@code size} bytes.\n *\n * @throws ProtobufException\n * The end of the stream or the current limit was reached.\n */\n public void skipRawBytes(final int size) throws IOException\n {\n if (size < 0)\n {\n throw ProtobufException.negativeSize();\n }\n\n if (totalBytesRetired + bufferPos + size > currentLimit)\n {\n // Read to the end of the stream anyway.\n skipRawBytes(currentLimit - totalBytesRetired - bufferPos);\n // Then fail.\n throw ProtobufException.truncatedMessage();\n }\n\n if (size <= bufferSize - bufferPos)\n {\n // We have all the bytes we need already.\n bufferPos += size;\n }\n else\n {\n // Skipping more bytes than are in the buffer. First skip what we have.\n int pos = bufferSize - bufferPos;\n bufferPos = bufferSize;\n\n // Keep refilling the buffer until we get to the point we wanted to skip\n // to. This has the side effect of ensuring the limits are updated\n // correctly.\n refillBuffer(true);\n while (size - pos > bufferSize)\n {\n pos += bufferSize;\n bufferPos = bufferSize;\n refillBuffer(true);\n }\n\n bufferPos = size - pos;\n }\n }\n\n // START EXTRA\n @Override\n public int readFieldNumber(Schema schema) throws IOException\n {\n if (isAtEnd())\n {\n lastTag = 0;\n return 0;\n }\n\n // are we reading packed field?\n if (isCurrentFieldPacked())\n {\n if (packedLimit < getTotalBytesRead())\n throw ProtobufException.misreportedSize();\n\n // Return field number while reading packed field\n return lastTag >>> TAG_TYPE_BITS;\n }\n\n packedLimit = 0;\n final int tag = readRawVarint32();\n final int fieldNumber = tag >>> TAG_TYPE_BITS;\n if (fieldNumber == 0)\n {\n if (decodeNestedMessageAsGroup && WIRETYPE_TAIL_DELIMITER == (tag & TAG_TYPE_MASK))\n {\n // protostuff's tail delimiter for streaming\n // 2 options: length-delimited or tail-delimited.\n lastTag = 0;\n return 0;\n }\n // If we actually read zero, that's not a valid tag.\n throw ProtobufException.invalidTag();\n }\n if (decodeNestedMessageAsGroup && WIRETYPE_END_GROUP == (tag & TAG_TYPE_MASK))\n {\n lastTag = 0;\n return 0;\n }\n\n lastTag = tag;\n return fieldNumber;\n }\n\n /**\n * Check if this field have been packed into a length-delimited field. If so, update internal state to reflect that\n * packed fields are being read.\n *\n * @throws IOException\n */\n private void checkIfPackedField() throws IOException\n {\n // Do we have the start of a packed field?\n if (packedLimit == 0 && WireFormat.getTagWireType(lastTag) == WIRETYPE_LENGTH_DELIMITED)\n {\n final int length = readRawVarint32();\n if (length < 0)\n throw ProtobufException.negativeSize();\n\n this.packedLimit = getTotalBytesRead() + length;\n }\n }\n\n @Override\n public byte[] readByteArray() throws IOException\n {\n final int size = readRawVarint32();\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer, so\n // just copy directly from it.\n final byte[] copy = new byte[size];\n System.arraycopy(buffer, bufferPos, copy, 0, size);\n bufferPos += size;\n return copy;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n return readRawBytes(size);\n }\n }\n\n @Override\n public void handleUnknownField(int fieldNumber, Schema schema) throws IOException\n {\n skipField(lastTag);\n }\n\n @Override\n public void transferByteRangeTo(Output output, boolean utf8String, int fieldNumber,\n boolean repeated) throws IOException\n {\n final int size = readRawVarint32();\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer\n output.writeByteRange(utf8String, fieldNumber, buffer, bufferPos, size, repeated);\n bufferPos += size;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n output.writeByteRange(utf8String, fieldNumber, readRawBytes(size), 0, size, repeated);\n }\n }\n\n /**\n * Returns the last tag.\n */\n public int getLastTag()\n {\n return lastTag;\n }\n\n /**\n * Reads a byte array/ByteBuffer value.\n */\n @Override\n public ByteBuffer readByteBuffer() throws IOException\n {\n return ByteBuffer.wrap(readByteArray());\n }\n\n // END EXTRA\n}\n", "file_name": "CodedInput.java", "human_label": "Read string from a buffer.", "level": "project_runnable", "lineno": "272", "name": "readString", "oracle_context": "{ \"apis\" : \"[readRawVarint32, deser, readRawBytes]\", \"classes\" : \"[String]\", \"vars\" : \"[bufferSize, bufferPos, buffer]\" }", "package": "io.protostuff", "project": "protostuff-master" }, { "_id": "636767a61a6d9265ec0185b7", "all_context": "{ \"class_level\" : \"import java.math.BigInteger;\\nimport java.nio.ByteBuffer;\\nimport java.nio.charset.Charset;\\nCharset UTF8;\\nCharset ISO_8859_1;\\nlong serialVersionUID;\\nTextFormat();\\nunescapeBytes(CharSequence input);\\nInvalidEscapeSequenceException(String description);\\nescapeText(String input);\\nunescapeText(String input);\\nisOctal(char c);\\nisHex(char c);\\ndigitValue(char c);\\nparseInt32(String text);\\nparseUInt32(String text);\\nparseInt64(String text);\\nparseUInt64(String text);\\nparseInteger(String text,boolean isSigned,boolean isLong);\\nescapeBytes(ByteBuffer input);\\n\", \"repo_level\" : \"\" }", "class_name": "TextFormat", "code": "private static int digitValue(final char c){\n if ('0' <= c && c <= '9') {\n return c - '0';\n }\n else if ('a' <= c && c <= 'z') {\n return c - 'a' + 10;\n }\n else {\n return c - 'A' + 10;\n }\n}\n", "docstring": "/** \n * Interpret a character as a digit (in any base up to 36) and return the numeric value. This is like {@code Character.digit()} but we don't accept non-ASCII digits.\n */\n", "end_lineno": "318", "file_content": "//========================================================================\n//Copyright 2007-2009 David Yu dyuproject@gmail.com\n//------------------------------------------------------------------------\n//Licensed under the Apache License, Version 2.0 (the \"License\");\n//you may not use this file except in compliance with the License.\n//You may obtain a copy of the License at \n//http://www.apache.org/licenses/LICENSE-2.0\n//Unless required by applicable law or agreed to in writing, software\n//distributed under the License is distributed on an \"AS IS\" BASIS,\n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//See the License for the specific language governing permissions and\n//limitations under the License.\n//========================================================================\n\n// Protocol Buffers - Google's data interchange format\n// Copyright 2008 Google Inc. All rights reserved.\n// http://code.google.com/p/protobuf/\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\npackage io.protostuff.parser;\n\nimport java.math.BigInteger;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.Charset;\n\n/**\n * Provide ascii text parsing and formatting support for proto2 instances. The implementation largely follows\n * google/protobuf/text_format.cc.\n * \n * @author wenboz@google.com Wenbo Zhu\n * @author kenton@google.com Kenton Varda\n * @author David Yu\n */\npublic final class TextFormat\n{\n private TextFormat()\n {\n }\n\n static final Charset UTF8 = Charset.forName(\"UTF-8\"), ISO_8859_1 = Charset.forName(\"ISO-8859-1\");\n\n // =================================================================\n // Utility functions\n //\n // Some of these methods are package-private because Descriptors.java uses\n // them.\n\n /**\n * Escapes bytes in the format used in protocol buffer text format, which is the same as the format used for C\n * string literals. All bytes that are not printable 7-bit ASCII characters are escaped, as well as backslash,\n * single-quote, and double-quote characters. Characters for which no defined short-hand escape sequence is defined\n * will be escaped using 3-digit octal sequences.\n */\n static StringBuilder escapeBytes(ByteBuffer input)\n {\n // input.flip();\n int length = input.limit();\n final StringBuilder builder = new StringBuilder(length);\n for (int i = 0; i < length; i++)\n {\n final byte b = input.get(i);\n switch (b)\n {\n // Java does not recognize \\a or \\v, apparently.\n case 0x07:\n builder.append(\"\\\\007\");\n break;\n case '\\b':\n builder.append(\"\\\\b\");\n break;\n case '\\f':\n builder.append(\"\\\\f\");\n break;\n case '\\n':\n builder.append(\"\\\\n\");\n break;\n case '\\r':\n builder.append(\"\\\\r\");\n break;\n case '\\t':\n builder.append(\"\\\\t\");\n break;\n case 0x0b:\n builder.append(\"\\\\013\");\n break;\n case '\\\\':\n builder.append(\"\\\\\\\\\");\n break;\n case '\\'':\n builder.append(\"\\\\\\'\");\n break;\n case '\"':\n builder.append(\"\\\\\\\"\");\n break;\n default:\n if (b >= 0x20)\n {\n builder.append((char) b);\n }\n else\n {\n builder.append('\\\\');\n builder.append((char) ('0' + ((b >>> 6) & 3)));\n builder.append((char) ('0' + ((b >>> 3) & 7)));\n builder.append((char) ('0' + (b & 7)));\n }\n break;\n }\n }\n return builder;\n }\n\n /**\n * Un-escape a byte sequence as escaped using {@link #escapeBytes(ByteString)}. Two-digit hex escapes (starting with\n * \"\\x\") are also recognized.\n */\n static ByteBuffer unescapeBytes(final CharSequence input)\n {\n int pos = 0, len = input.length();\n final byte[] result = new byte[len];\n ByteBuffer buffer = ByteBuffer.wrap(result);\n for (int i = 0; i < len; i++)\n {\n char c = input.charAt(i);\n if (c == '\\\\')\n {\n if (i + 1 < len)\n {\n ++i;\n c = input.charAt(i);\n if (isOctal(c))\n {\n // Octal escape.\n int code = digitValue(c);\n if (i + 1 < len && isOctal(input.charAt(i + 1)))\n {\n ++i;\n code = code * 8 + digitValue(input.charAt(i));\n }\n if (i + 1 < len && isOctal(input.charAt(i + 1)))\n {\n ++i;\n code = code * 8 + digitValue(input.charAt(i));\n }\n result[pos++] = (byte) code;\n }\n else\n {\n switch (c)\n {\n case 'a':\n result[pos++] = 0x07;\n break;\n case 'b':\n result[pos++] = '\\b';\n break;\n case 'f':\n result[pos++] = '\\f';\n break;\n case 'n':\n result[pos++] = '\\n';\n break;\n case 'r':\n result[pos++] = '\\r';\n break;\n case 't':\n result[pos++] = '\\t';\n break;\n case 'v':\n result[pos++] = 0x0b;\n break;\n case '\\\\':\n result[pos++] = '\\\\';\n break;\n case '\\'':\n result[pos++] = '\\'';\n break;\n case '\"':\n result[pos++] = '\\\"';\n break;\n\n case 'x':\n // hex escape\n int code = 0;\n if (i + 1 < len && isHex(input.charAt(i + 1)))\n {\n ++i;\n code = digitValue(input.charAt(i));\n }\n else\n {\n throw new InvalidEscapeSequenceException(\n \"Invalid escape sequence: '\\\\x' with no digits\");\n }\n if (i + 1 < len && isHex(input.charAt(i + 1)))\n {\n ++i;\n code = code * 16 + digitValue(input.charAt(i));\n }\n result[pos++] = (byte) code;\n break;\n\n default:\n throw new InvalidEscapeSequenceException(\n \"Invalid escape sequence: '\\\\\" + c + '\\'');\n }\n }\n }\n else\n {\n throw new InvalidEscapeSequenceException(\n \"Invalid escape sequence: '\\\\' at end of string.\");\n }\n }\n else\n {\n result[pos++] = (byte) c;\n }\n }\n buffer.limit(pos);\n return buffer;\n }\n\n /**\n * Thrown by {@link TextFormat#unescapeBytes} and {@link TextFormat#unescapeText} when an invalid escape sequence is\n * seen.\n */\n static class InvalidEscapeSequenceException extends RuntimeException\n {\n private static final long serialVersionUID = -8164033650142593305L;\n\n InvalidEscapeSequenceException(final String description)\n {\n super(description);\n }\n }\n\n /**\n * Like {@link #escapeBytes(ByteString)}, but escapes a text string. Non-ASCII characters are first encoded as\n * UTF-8, then each byte is escaped individually as a 3-digit octal escape. Yes, it's weird.\n */\n static String escapeText(final String input)\n {\n return escapeBytes(ByteBuffer.wrap(input.getBytes(ISO_8859_1))).toString();\n }\n\n /**\n * Un-escape a text string as escaped using {@link #escapeText(String)}. Two-digit hex escapes (starting with \"\\x\")\n * are also recognized.\n */\n static String unescapeText(String input)\n {\n ByteBuffer buffer = unescapeBytes(input);\n return new String(buffer.array(), buffer.position(), buffer.limit(), ISO_8859_1);\n }\n\n /**\n * Is this an octal digit?\n */\n private static boolean isOctal(final char c)\n {\n return '0' <= c && c <= '7';\n }\n\n /**\n * Is this a hex digit?\n */\n private static boolean isHex(final char c)\n {\n return ('0' <= c && c <= '9') ||\n ('a' <= c && c <= 'f') ||\n ('A' <= c && c <= 'F');\n }\n\n /**\n * Interpret a character as a digit (in any base up to 36) and return the numeric value. This is like\n * {@code Character.digit()} but we don't accept non-ASCII digits.\n */\n private static int digitValue(final char c)\n {\n if ('0' <= c && c <= '9')\n {\n return c - '0';\n }\n else if ('a' <= c && c <= 'z')\n {\n return c - 'a' + 10;\n }\n else\n {\n return c - 'A' + 10;\n }\n }\n\n /**\n * Parse a 32-bit signed integer from the text. Unlike the Java standard {@code Integer.parseInt()}, this function\n * recognizes the prefixes \"0x\" and \"0\" to signify hexidecimal and octal numbers, respectively.\n */\n static int parseInt32(final String text) throws NumberFormatException\n {\n return (int) parseInteger(text, true, false);\n }\n\n /**\n * Parse a 32-bit unsigned integer from the text. Unlike the Java standard {@code Integer.parseInt()}, this function\n * recognizes the prefixes \"0x\" and \"0\" to signify hexidecimal and octal numbers, respectively. The result is\n * coerced to a (signed) {@code int} when returned since Java has no unsigned integer type.\n */\n static int parseUInt32(final String text) throws NumberFormatException\n {\n return (int) parseInteger(text, false, false);\n }\n\n /**\n * Parse a 64-bit signed integer from the text. Unlike the Java standard {@code Integer.parseInt()}, this function\n * recognizes the prefixes \"0x\" and \"0\" to signify hexidecimal and octal numbers, respectively.\n */\n static long parseInt64(final String text) throws NumberFormatException\n {\n return parseInteger(text, true, true);\n }\n\n /**\n * Parse a 64-bit unsigned integer from the text. Unlike the Java standard {@code Integer.parseInt()}, this function\n * recognizes the prefixes \"0x\" and \"0\" to signify hexidecimal and octal numbers, respectively. The result is\n * coerced to a (signed) {@code long} when returned since Java has no unsigned long type.\n */\n static long parseUInt64(final String text) throws NumberFormatException\n {\n return parseInteger(text, false, true);\n }\n\n private static long parseInteger(final String text,\n final boolean isSigned,\n final boolean isLong)\n throws NumberFormatException\n {\n int pos = 0;\n\n boolean negative = false;\n if (text.startsWith(\"-\", pos))\n {\n if (!isSigned)\n {\n throw new NumberFormatException(\"Number must be positive: \" + text);\n }\n ++pos;\n negative = true;\n }\n\n int radix = 10;\n if (text.startsWith(\"0x\", pos))\n {\n pos += 2;\n radix = 16;\n }\n else if (text.startsWith(\"0\", pos))\n {\n radix = 8;\n }\n\n final String numberText = text.substring(pos);\n\n long result = 0;\n if (numberText.length() < 16)\n {\n // Can safely assume no overflow.\n result = Long.parseLong(numberText, radix);\n if (negative)\n {\n result = -result;\n }\n\n // Check bounds.\n // No need to check for 64-bit numbers since they'd have to be 16 chars\n // or longer to overflow.\n if (!isLong)\n {\n if (isSigned)\n {\n if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)\n {\n throw new NumberFormatException(\n \"Number out of range for 32-bit signed integer: \" + text);\n }\n }\n else\n {\n if (result >= (1L << 32) || result < 0)\n {\n throw new NumberFormatException(\n \"Number out of range for 32-bit unsigned integer: \" + text);\n }\n }\n }\n }\n else\n {\n BigInteger bigValue = new BigInteger(numberText, radix);\n if (negative)\n {\n bigValue = bigValue.negate();\n }\n\n // Check bounds.\n if (!isLong)\n {\n if (isSigned)\n {\n if (bigValue.bitLength() > 31)\n {\n throw new NumberFormatException(\n \"Number out of range for 32-bit signed integer: \" + text);\n }\n }\n else\n {\n if (bigValue.bitLength() > 32)\n {\n throw new NumberFormatException(\n \"Number out of range for 32-bit unsigned integer: \" + text);\n }\n }\n }\n else\n {\n if (isSigned)\n {\n if (bigValue.bitLength() > 63)\n {\n throw new NumberFormatException(\n \"Number out of range for 64-bit signed integer: \" + text);\n }\n }\n else\n {\n if (bigValue.bitLength() > 64)\n {\n throw new NumberFormatException(\n \"Number out of range for 64-bit unsigned integer: \" + text);\n }\n }\n }\n\n result = bigValue.longValue();\n }\n\n return result;\n }\n}\n", "file_name": "TextFormat.java", "human_label": "Obtains the number corresponding to the character c.", "level": "self_contained", "lineno": "300", "name": "digitValue", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "io.protostuff.parser", "project": "protostuff-master" }, { "_id": "636767e01a6d9265ec018755", "all_context": "{ \"class_level\" : \"import com.google.gson.Gson;\\nimport com.google.gson.JsonObject;\\nimport io.netty.handler.codec.http.HttpHeaderValues;\\nimport lombok.extern.slf4j.Slf4j;\\nimport org.apache.commons.codec.binary.Base64;\\nimport org.apache.http.HttpHeaders;\\nimport org.apache.http.HttpStatus;\\nimport org.apache.http.StatusLine;\\nimport org.apache.http.client.config.RequestConfig;\\nimport org.apache.http.client.methods.CloseableHttpResponse;\\nimport org.apache.http.client.methods.HttpPost;\\nimport org.apache.http.entity.ContentType;\\nimport org.apache.http.entity.StringEntity;\\nimport org.apache.http.impl.client.CloseableHttpClient;\\nimport org.apache.http.impl.client.HttpClients;\\nimport org.apache.http.util.EntityUtils;\\nimport org.apache.skywalking.oap.server.library.util.StringUtil;\\nimport org.apache.skywalking.oap.server.core.alarm.AlarmCallback;\\nimport org.apache.skywalking.oap.server.core.alarm.AlarmMessage;\\nimport org.apache.skywalking.oap.server.core.alarm.provider.AlarmRulesWatcher;\\nimport javax.crypto.Mac;\\nimport javax.crypto.spec.SecretKeySpec;\\nimport java.io.IOException;\\nimport java.security.InvalidKeyException;\\nimport java.security.NoSuchAlgorithmException;\\nimport java.util.Arrays;\\nimport java.util.HashMap;\\nimport java.util.List;\\nimport java.util.Map;\\nimport java.util.stream.Collectors;\\nint HTTP_CONNECT_TIMEOUT;\\nint HTTP_CONNECTION_REQUEST_TIMEOUT;\\nint HTTP_SOCKET_TIMEOUT;\\nAlarmRulesWatcher alarmRulesWatcher;\\nRequestConfig requestConfig;\\nFeishuHookCallback(AlarmRulesWatcher alarmRulesWatcher);\\ngetRequestBody(WebHookUrl webHookUrl,AlarmMessage alarmMessage);\\nbuildContent(JsonObject jsonObject);\\nsign(Long timestamp,String secret);\\nsendAlarmMessage(CloseableHttpClient httpClient,String url,String requestBody);\\ndoAlarm(List alarmMessages);\\n\", \"repo_level\" : \"public interface StringUtil {static boolean isEmpty(String str);\\nstatic boolean isNotEmpty(String str);\\nstatic boolean isBlank(String str);\\nstatic boolean isNotBlank(String str);\\nstatic void setIfPresent(String value,Consumer setter);\\nstatic String join(char delimiter,String strings);\\nstatic boolean substringMatch(CharSequence str,int index,CharSequence substring);\\nstatic String cut(String str,int threshold);\\nstatic String trim(String str,char ch);\\n }\\npublic interface AlarmCallback { void doAlarm(List alarmMessage);\\n }\\npublic interface AlarmMessage { }\\npublic interface AlarmRulesWatcher {public void notify(ConfigChangeEvent value);\\n void notify(Rules newRules);\\npublic String value();\\npublic List getRules();\\npublic List getCompositeRules();\\npublic List getWebHooks();\\npublic GRPCAlarmSetting getGrpchookSetting();\\npublic SlackSettings getSlackSettings();\\npublic WechatSettings getWechatSettings();\\npublic DingtalkSettings getDingtalkSettings();\\npublic FeishuSettings getFeishuSettings();\\npublic WeLinkSettings getWeLinkSettings();\\npublic PagerDutySettings getPagerDutySettings();\\npublic DiscordSettings getDiscordSettings();\\n }\\n\" }", "class_name": "FeishuHookCallback", "code": "private Map buildContent(JsonObject jsonObject){\n Map content=new HashMap<>();\n content.put(\"msg_type\",jsonObject.get(\"msg_type\").getAsString());\n if (jsonObject.get(\"ats\") != null) {\n String ats=jsonObject.get(\"ats\").getAsString();\n String text=jsonObject.get(\"content\").getAsJsonObject().get(\"text\").getAsString();\n List collect=Arrays.stream(ats.split(\",\")).map(String::trim).collect(Collectors.toList());\n for ( String userId : collect) {\n text+=\"\";\n }\n jsonObject.get(\"content\").getAsJsonObject().addProperty(\"text\",text);\n }\n content.put(\"content\",jsonObject.get(\"content\").getAsJsonObject());\n return content;\n}\n", "docstring": "/** \n * build content,if it has ats someone set the ats\n */\n", "end_lineno": "139", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.core.alarm.provider.feishu;\n\nimport com.google.gson.Gson;\nimport com.google.gson.JsonObject;\nimport io.netty.handler.codec.http.HttpHeaderValues;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.commons.codec.binary.Base64;\nimport org.apache.http.HttpHeaders;\nimport org.apache.http.HttpStatus;\nimport org.apache.http.StatusLine;\nimport org.apache.http.client.config.RequestConfig;\nimport org.apache.http.client.methods.CloseableHttpResponse;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.entity.ContentType;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.util.EntityUtils;\nimport org.apache.skywalking.oap.server.library.util.StringUtil;\nimport org.apache.skywalking.oap.server.core.alarm.AlarmCallback;\nimport org.apache.skywalking.oap.server.core.alarm.AlarmMessage;\nimport org.apache.skywalking.oap.server.core.alarm.provider.AlarmRulesWatcher;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\nimport java.io.IOException;\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\n/**\n * Use SkyWalking alarm feishu webhook API.\n */\n@Slf4j\npublic class FeishuHookCallback implements AlarmCallback {\n\n private static final int HTTP_CONNECT_TIMEOUT = 1000;\n private static final int HTTP_CONNECTION_REQUEST_TIMEOUT = 1000;\n private static final int HTTP_SOCKET_TIMEOUT = 10000;\n private AlarmRulesWatcher alarmRulesWatcher;\n private RequestConfig requestConfig;\n\n public FeishuHookCallback(final AlarmRulesWatcher alarmRulesWatcher) {\n this.alarmRulesWatcher = alarmRulesWatcher;\n this.requestConfig = RequestConfig.custom()\n .setConnectTimeout(HTTP_CONNECT_TIMEOUT)\n .setConnectionRequestTimeout(HTTP_CONNECTION_REQUEST_TIMEOUT)\n .setSocketTimeout(HTTP_SOCKET_TIMEOUT)\n .build();\n }\n\n /**\n * Send alarm message if the settings not empty\n */\n @Override\n public void doAlarm(List alarmMessages) {\n if (this.alarmRulesWatcher.getFeishuSettings() == null || this.alarmRulesWatcher.getFeishuSettings().getWebhooks().isEmpty()) {\n return;\n }\n CloseableHttpClient httpClient = HttpClients.custom().build();\n try {\n FeishuSettings feishuSettings = this.alarmRulesWatcher.getFeishuSettings();\n feishuSettings.getWebhooks().forEach(webHookUrl -> {\n alarmMessages.forEach(alarmMessage -> {\n String requestBody = getRequestBody(webHookUrl, alarmMessage);\n sendAlarmMessage(httpClient, webHookUrl.getUrl(), requestBody);\n });\n });\n } finally {\n try {\n httpClient.close();\n } catch (IOException e) {\n log.error(e.getMessage(), e);\n }\n }\n }\n\n /**\n * deal requestBody,if it has sign set the sign\n */\n private String getRequestBody(FeishuSettings.WebHookUrl webHookUrl, AlarmMessage alarmMessage) {\n String requestBody = String.format(\n this.alarmRulesWatcher.getFeishuSettings().getTextTemplate(), alarmMessage.getAlarmMessage()\n );\n Gson gson = new Gson();\n JsonObject jsonObject = gson.fromJson(requestBody, JsonObject.class);\n Map content = buildContent(jsonObject);\n if (!StringUtil.isBlank(webHookUrl.getSecret())) {\n Long timestamp = System.currentTimeMillis() / 1000;\n content.put(\"timestamp\", timestamp);\n try {\n content.put(\"sign\", sign(timestamp, webHookUrl.getSecret()));\n } catch (NoSuchAlgorithmException | InvalidKeyException e) {\n throw new RuntimeException(e);\n }\n }\n return gson.toJson(content);\n }\n\n /**\n * build content,if it has ats someone set the ats\n */\n private Map buildContent(JsonObject jsonObject) {\n Map content = new HashMap<>();\n content.put(\"msg_type\", jsonObject.get(\"msg_type\").getAsString());\n if (jsonObject.get(\"ats\") != null) {\n String ats = jsonObject.get(\"ats\").getAsString();\n String text = jsonObject.get(\"content\").getAsJsonObject().get(\"text\").getAsString();\n List collect = Arrays.stream(ats.split(\",\"))\n .map(String::trim).collect(Collectors.toList());\n for (String userId : collect) {\n text += \"\";\n }\n jsonObject.get(\"content\").getAsJsonObject().addProperty(\"text\", text);\n }\n content.put(\"content\", jsonObject.get(\"content\").getAsJsonObject());\n return content;\n }\n\n /**\n * Sign webhook url using HmacSHA256 algorithm\n */\n private String sign(final Long timestamp, String secret) throws NoSuchAlgorithmException, InvalidKeyException {\n String stringToSign = timestamp + \"\\n\" + secret;\n Mac mac = Mac.getInstance(\"HmacSHA256\");\n mac.init(new SecretKeySpec(stringToSign.getBytes(), \"HmacSHA256\"));\n byte[] signData = mac.doFinal();\n return Base64.encodeBase64String(signData);\n }\n\n /**\n * Send alarm message to remote endpoint\n */\n private void sendAlarmMessage(CloseableHttpClient httpClient, String url, String requestBody) {\n CloseableHttpResponse httpResponse = null;\n try {\n HttpPost post = new HttpPost(url);\n post.setConfig(requestConfig);\n post.setHeader(HttpHeaders.ACCEPT, HttpHeaderValues.APPLICATION_JSON.toString());\n post.setHeader(HttpHeaders.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON.toString());\n StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);\n post.setEntity(entity);\n httpResponse = httpClient.execute(post);\n StatusLine statusLine = httpResponse.getStatusLine();\n if (statusLine != null && statusLine.getStatusCode() != HttpStatus.SC_OK) {\n log.error(\"send feishu alarm to {} failure. Response code: {}, Response content: {}\", url, statusLine.getStatusCode(),\n EntityUtils.toString(httpResponse.getEntity()));\n }\n } catch (Throwable e) {\n log.error(\"send feishu alarm to {} failure.\", url, e);\n } finally {\n if (httpResponse != null) {\n try {\n httpResponse.close();\n } catch (IOException e) {\n log.error(e.getMessage(), e);\n }\n\n }\n }\n }\n}\n", "file_name": "FeishuHookCallback.java", "human_label": "Put the \"content\" from the jsonObject to the content.", "level": "project_runnable", "lineno": "121", "name": "buildContent", "oracle_context": "{ \"apis\" : \"[put, getAsString, get, getAsJsonObject, map, stream, split, toList, addProperty]\", \"classes\" : \"[Map, String, List]\", \"vars\" : \"[]\" }", "package": "org.apache.skywalking.oap.server.core.alarm.provider.feishu", "project": "skywalking-master" }, { "_id": "6367667f1a6d9265ec017458", "all_context": "{ \"class_level\" : \"import org.atmosphere.annotation.Processor;\\nimport org.atmosphere.cache.BroadcasterCacheInspector;\\nimport org.atmosphere.cache.DefaultBroadcasterCache;\\nimport org.atmosphere.cache.UUIDBroadcasterCache;\\nimport org.atmosphere.config.ApplicationConfiguration;\\nimport org.atmosphere.config.AtmosphereHandlerConfig;\\nimport org.atmosphere.config.AtmosphereHandlerProperty;\\nimport org.atmosphere.config.FrameworkConfiguration;\\nimport org.atmosphere.container.BlockingIOCometSupport;\\nimport org.atmosphere.container.Tomcat7BIOSupportWithWebSocket;\\nimport org.atmosphere.container.WebLogicServlet30WithWebSocket;\\nimport org.atmosphere.handler.AbstractReflectorAtmosphereHandler;\\nimport org.atmosphere.handler.ReflectorServletProcessor;\\nimport org.atmosphere.inject.InjectableObjectFactory;\\nimport org.atmosphere.interceptor.AndroidAtmosphereInterceptor;\\nimport org.atmosphere.interceptor.CacheHeadersInterceptor;\\nimport org.atmosphere.interceptor.CorsInterceptor;\\nimport org.atmosphere.interceptor.HeartbeatInterceptor;\\nimport org.atmosphere.interceptor.IdleResourceInterceptor;\\nimport org.atmosphere.interceptor.InvokationOrder;\\nimport org.atmosphere.interceptor.JSONPAtmosphereInterceptor;\\nimport org.atmosphere.interceptor.JavaScriptProtocol;\\nimport org.atmosphere.interceptor.OnDisconnectInterceptor;\\nimport org.atmosphere.interceptor.PaddingAtmosphereInterceptor;\\nimport org.atmosphere.interceptor.SSEAtmosphereInterceptor;\\nimport org.atmosphere.interceptor.WebSocketMessageSuspendInterceptor;\\nimport org.atmosphere.util.AtmosphereConfigReader;\\nimport org.atmosphere.util.DefaultEndpointMapper;\\nimport org.atmosphere.util.DefaultUUIDProvider;\\nimport org.atmosphere.util.EndpointMapper;\\nimport org.atmosphere.util.ExecutorsFactory;\\nimport org.atmosphere.util.IOUtils;\\nimport org.atmosphere.util.IntrospectionUtils;\\nimport org.atmosphere.util.ServletContextFactory;\\nimport org.atmosphere.util.UUIDProvider;\\nimport org.atmosphere.util.Utils;\\nimport org.atmosphere.util.Version;\\nimport org.atmosphere.util.VoidServletConfig;\\nimport org.atmosphere.util.analytics.FocusPoint;\\nimport org.atmosphere.util.analytics.JGoogleAnalyticsTracker;\\nimport org.atmosphere.util.analytics.ModuleDetection;\\nimport org.atmosphere.websocket.DefaultWebSocketFactory;\\nimport org.atmosphere.websocket.DefaultWebSocketProcessor;\\nimport org.atmosphere.websocket.WebSocket;\\nimport org.atmosphere.websocket.WebSocketFactory;\\nimport org.atmosphere.websocket.WebSocketHandler;\\nimport org.atmosphere.websocket.WebSocketProcessor;\\nimport org.atmosphere.websocket.WebSocketProtocol;\\nimport org.atmosphere.websocket.protocol.SimpleHttpProtocol;\\nimport org.slf4j.Logger;\\nimport org.slf4j.LoggerFactory;\\nimport javax.servlet.Servlet;\\nimport javax.servlet.ServletConfig;\\nimport javax.servlet.ServletContext;\\nimport javax.servlet.ServletException;\\nimport java.io.BufferedReader;\\nimport java.io.File;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport java.io.InputStreamReader;\\nimport java.io.UnsupportedEncodingException;\\nimport java.net.HttpURLConnection;\\nimport java.net.MalformedURLException;\\nimport java.net.URI;\\nimport java.net.URL;\\nimport java.net.URLClassLoader;\\nimport java.net.URLDecoder;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collections;\\nimport java.util.Comparator;\\nimport java.util.Enumeration;\\nimport java.util.HashMap;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nimport java.util.Objects;\\nimport java.util.concurrent.ConcurrentHashMap;\\nimport java.util.concurrent.ConcurrentLinkedQueue;\\nimport java.util.concurrent.ExecutorService;\\nimport java.util.concurrent.ThreadPoolExecutor;\\nimport java.util.concurrent.atomic.AtomicBoolean;\\nimport static org.atmosphere.cpr.ApplicationConfig.ALLOW_QUERYSTRING_AS_REQUEST;\\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER;\\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER_MAPPING;\\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER_PATH;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CACHE;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CLASS;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_FACTORY;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_LIFECYCLE_POLICY;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_SHAREABLE_LISTENERS;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_WAIT_TIME;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCAST_FILTER_CLASSES;\\nimport static org.atmosphere.cpr.ApplicationConfig.CONTENT_TYPE_FIRST_RESPONSE;\\nimport static org.atmosphere.cpr.ApplicationConfig.DISABLE_ONSTATE_EVENT;\\nimport static org.atmosphere.cpr.ApplicationConfig.META_SERVICE_PATH;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_ALLOW_SESSION_TIMEOUT_REMOVAL;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_ATMOSPHERE_XML;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_BLOCKING_COMETSUPPORT;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_COMET_SUPPORT;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_NATIVE_COMETSUPPORT;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SERVLET_MAPPING;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SESSION_SUPPORT;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_THROW_EXCEPTION_ON_CLONED_REQUEST;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_USE_STREAM;\\nimport static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID;\\nimport static org.atmosphere.cpr.ApplicationConfig.USE_SERVLET_CONTEXT_PARAMETERS;\\nimport static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROCESSOR;\\nimport static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROTOCOL;\\nimport static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_SUPPORT;\\nimport static org.atmosphere.cpr.Broadcaster.ROOT_MASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.ATMOSPHERE_CONFIG;\\nimport static org.atmosphere.cpr.FrameworkConfig.CDI_INJECTOR;\\nimport static org.atmosphere.cpr.FrameworkConfig.GUICE_INJECTOR;\\nimport static org.atmosphere.cpr.FrameworkConfig.HAZELCAST_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.INJECT_LIBARY;\\nimport static org.atmosphere.cpr.FrameworkConfig.JERSEY_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.JERSEY_CONTAINER;\\nimport static org.atmosphere.cpr.FrameworkConfig.JGROUPS_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.JMS_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.KAFKA_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.RABBITMQ_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.REDIS_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.RMI_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.SPRING_INJECTOR;\\nimport static org.atmosphere.cpr.FrameworkConfig.THROW_EXCEPTION_ON_CLONED_REQUEST;\\nimport static org.atmosphere.cpr.FrameworkConfig.XMPP_BROADCASTER;\\nimport static org.atmosphere.cpr.HeaderConfig.ATMOSPHERE_POST_BODY;\\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_TRACKING_ID;\\nimport static org.atmosphere.util.IOUtils.realPath;\\nimport static org.atmosphere.websocket.WebSocket.WEBSOCKET_SUSPEND;\\nString DEFAULT_ATMOSPHERE_CONFIG_PATH;\\nString DEFAULT_LIB_PATH;\\nString DEFAULT_HANDLER_PATH;\\nString META_SERVICE;\\nString MAPPING_REGEX;\\nString ASYNC_IO;\\nLogger logger;\\nList broadcasterFilters;\\nList asyncSupportListeners;\\nList atmosphereResourceListeners;\\nArrayList possibleComponentsCandidate;\\nHashMap initParams;\\nAtmosphereConfig config;\\nAtomicBoolean isCometSupportConfigured;\\nboolean isFilter;\\nMap atmosphereHandlers;\\nConcurrentLinkedQueue broadcasterTypes;\\nConcurrentLinkedQueue objectFactoryType;\\nConcurrentLinkedQueue inspectors;\\nString mappingRegex;\\nboolean useNativeImplementation;\\nboolean useBlockingImplementation;\\nboolean useStreamForFlushingComments;\\nboolean useServlet30;\\nAsyncSupport asyncSupport;\\nString broadcasterClassName;\\nboolean isCometSupportSpecified;\\nboolean isBroadcasterSpecified;\\nboolean isSessionSupportSpecified;\\nboolean isThrowExceptionOnClonedRequestSpecified;\\nBroadcasterFactory broadcasterFactory;\\nString broadcasterFactoryClassName;\\nString broadcasterCacheClassName;\\nboolean webSocketEnabled;\\nString broadcasterLifeCyclePolicy;\\nString webSocketProtocolClassName;\\nWebSocketProtocol webSocketProtocol;\\nString handlersPath;\\nServletConfig servletConfig;\\nboolean autoDetectHandlers;\\nboolean hasNewWebSocketProtocol;\\nString atmosphereDotXmlPath;\\nString metaServicePath;\\nLinkedList interceptors;\\nboolean scanDone;\\nString annotationProcessorClassName;\\nList broadcasterListeners;\\nString webSocketProcessorClassName;\\nboolean webSocketProtocolInitialized;\\nEndpointMapper endpointMapper;\\nString libPath;\\nboolean isInit;\\nboolean sharedThreadPools;\\nList packages;\\nLinkedList annotationPackages;\\nboolean allowAllClassesScan;\\nboolean annotationFound;\\nboolean executeFirstSet;\\nAtmosphereObjectFactory objectFactory;\\nAtomicBoolean isDestroyed;\\nboolean externalizeDestroy;\\nAnnotationProcessor annotationProcessor;\\nList excludedInterceptors;\\nLinkedList broadcasterCacheListeners;\\nList filterManipulators;\\nAtmosphereResourceFactory arFactory;\\nMetaBroadcaster metaBroadcaster;\\nAtmosphereResourceSessionFactory sessionFactory;\\nString defaultSerializerClassName;\\nClass defaultSerializerClass;\\nList frameworkListeners;\\nUUIDProvider uuidProvider;\\nThread shutdownHook;\\nList> DEFAULT_ATMOSPHERE_INTERCEPTORS;\\nWebSocketFactory webSocketFactory;\\nIllegalStateException initializationError;\\nAtmosphereHandler REFLECTOR_ATMOSPHEREHANDLER;\\nAtmosphereHandler atmosphereHandler;\\nBroadcaster broadcaster;\\nString mapping;\\nboolean create;\\nboolean needRequestScopedInjection;\\nboolean wilcardMapping;\\nMetaServiceProcedure procedure;\\nAtomicBoolean done;\\nonRequest(AtmosphereResource resource);\\ndestroy();\\nsetAndConfigureAtmosphereResourceFactory(AtmosphereResourceFactory arFactory);\\nAtmosphereHandlerWrapper(BroadcasterFactory broadcasterFactory,AtmosphereHandler atmosphereHandler,String mapping,AtmosphereConfig config);\\nhookInjection(AtmosphereConfig config);\\nAtmosphereHandlerWrapper(AtmosphereHandler atmosphereHandler,Broadcaster broadcaster,AtmosphereConfig config);\\ntoString();\\nneedRequestScopedInjection();\\nwildcardMapping();\\napply(AtmosphereFramework fwk,Class clazz);\\napply(AtmosphereFramework fwk,Class c);\\nconfigure(AtmosphereConfig config);\\nnewClassInstance(Class classType,Class defaultType);\\nallowInjectionOf(Object o);\\nAtmosphereFramework();\\nAtmosphereFramework(ServletConfig sc);\\nAtmosphereFramework(boolean isFilter,boolean autoDetectHandlers);\\nnewAtmosphereConfig();\\npopulateBroadcasterType();\\npopulateObjectFactoryType();\\naddAtmosphereHandler(String mapping,AtmosphereHandler h,List l);\\naddAtmosphereHandler(String mapping,AtmosphereHandler h,Broadcaster broadcaster,List l);\\naddAtmosphereHandler(String mapping,AtmosphereHandler h,String broadcasterId,List l);\\ncreateWrapperAndConfigureHandler(AtmosphereHandler h,String mapping,List l);\\naddAtmosphereHandler(String mapping,AtmosphereHandler h);\\naddMapping(String path,AtmosphereHandlerWrapper w);\\nnormalizePath(String path);\\naddAtmosphereHandler(String mapping,AtmosphereHandler h,String broadcasterId);\\ninitServletProcessor(AtmosphereHandler h);\\naddAtmosphereHandler(String mapping,AtmosphereHandler h,Broadcaster broadcaster);\\nremoveAtmosphereHandler(String mapping);\\nremoveAllAtmosphereHandler();\\nremoveAllInitParams();\\naddInitParameter(String name,String value);\\nreadSystemProperties();\\npatchContainer();\\ninit();\\ninit(ServletConfig sc);\\npreventOOM();\\ninit(ServletConfig sc,boolean wrap);\\nservletConfig(ServletConfig sc,boolean wrap);\\ngetServletName();\\ngetServletContext();\\ngetInitParameter(String name);\\ngetInitParameterNames();\\nreconfigureInitParams(boolean reconfigureInitParams);\\ninfo();\\nuniverse();\\nconfigureAnnotationPackages();\\nanalytics();\\nconfigureAtmosphereInterceptor(ServletConfig sc);\\nnewAInterceptor(Class a);\\ncompare(AtmosphereInterceptor i1,AtmosphereInterceptor i2);\\nconfigureWebDotXmlAtmosphereHandler(ServletConfig sc);\\nconfigureScanningPackage(ServletConfig sc,String value);\\ndefaultPackagesToScan();\\nconfigureBroadcasterFactory();\\nconfigureBroadcaster();\\ninstallAnnotationProcessor(ServletConfig sc);\\ndoInitParamsForWebSocket(ServletConfig sc);\\ndoInitParams(ServletConfig sc);\\ndoInitParams(ServletConfig sc,boolean reconfigure);\\nloadConfiguration(ServletConfig sc);\\ndetectSupportedFramework(ServletConfig sc);\\nconfigureDetectedFramework(ReflectorServletProcessor rsp,boolean isJersey);\\nlookupDefaultBroadcasterType(String defaultB);\\nautodetectBroadcaster();\\nlookupDefaultObjectFactoryType();\\nsessionSupport(boolean sessionSupport);\\ninitAtmosphereHandler(ServletConfig sc);\\ninitAtmosphereHandler();\\ncheckWebSocketSupportState();\\nonRequest(AtmosphereResource r);\\ninitWebSocket();\\ninitEndpointMapper();\\ncloseAtmosphereResource();\\ndestroyInterceptors();\\nresetStates();\\nloadMetaService();\\nloadAtmosphereDotXml(InputStream stream,ClassLoader c);\\nsetAsyncSupport(AsyncSupport asyncSupport);\\nsetCometSupport(AsyncSupport asyncSupport);\\ngetAsyncSupport();\\ngetCometSupport();\\ncreateAsyncSupportResolver();\\nautoDetectContainer();\\nautoDetectAtmosphereHandlers(ServletContext servletContext,ClassLoader classloader);\\nloadAtmosphereHandlersFromPath(ClassLoader classloader,String realPath);\\nautoDetectWebSocketHandler(ServletContext servletContext,ClassLoader classloader);\\nloadWebSocketFromPath(ClassLoader classloader,String realPath);\\ngetFiles(File f);\\nconfigureRequestResponse(AtmosphereRequest req,AtmosphereResponse res);\\ndoCometSupport(AtmosphereRequest req,AtmosphereResponse res);\\ngetDefaultBroadcasterClassName();\\nsetDefaultBroadcasterClassName(String bccn);\\nisUseStreamForFlushingComments();\\nisUseServlet30();\\nsetUseStreamForFlushingComments(boolean useStreamForFlushingComments);\\ngetBroadcasterFactory();\\nsetBroadcasterFactory(BroadcasterFactory broadcasterFactory);\\ngetBroadcasterCacheClassName();\\nsetBroadcasterCacheClassName(String broadcasterCacheClassName);\\naddBroadcasterType(String broadcasterTypeString);\\nbroadcasterTypes();\\ngetWebSocketProtocolClassName();\\nsetWebSocketProtocolClassName(String webSocketProtocolClassName);\\ngetAtmosphereHandlers();\\nconfigureQueryStringAsRequest(AtmosphereRequest request);\\ngetWebSocketProtocol();\\nisUseNativeImplementation();\\nsetUseNativeImplementation(boolean useNativeImplementation);\\nisUseBlockingImplementation();\\nsetUseBlockingImplementation(boolean useBlockingImplementation);\\ngetAtmosphereDotXmlPath();\\nsetAtmosphereDotXmlPath(String atmosphereDotXmlPath);\\ngetHandlersPath();\\nsetHandlersPath(String handlersPath);\\ngetLibPath();\\nsetLibPath(String libPath);\\ngetWebSocketProcessorClassName();\\nsetWebsocketProcessorClassName(String webSocketProcessorClassName);\\ninterceptor(AtmosphereInterceptor c);\\naddDefaultOrAppInterceptors();\\naddInterceptorToAllWrappers(AtmosphereInterceptor c);\\naddInterceptorToWrapper(AtmosphereHandlerWrapper wrapper,AtmosphereInterceptor c);\\naddInterceptorToWrapper(AtmosphereHandlerWrapper wrapper,List interceptors);\\ncheckDuplicate(AtmosphereInterceptor c);\\ncheckDuplicate(List interceptorList,Class c);\\ninterceptors();\\nannotationProcessorClassName(String annotationProcessorClassName);\\nasyncSupportListener(AsyncSupportListener asyncSupportListener);\\nasyncSupportListeners();\\naddBroadcasterListener(BroadcasterListener b);\\naddBroadcasterCacheListener(BroadcasterCacheListener b);\\nbroadcasterCacheListeners();\\naddBroadcasterCacheInjector(BroadcasterCacheInspector b);\\ninspectors();\\ngetAtmosphereConfig();\\ngetServletConfig();\\nbroadcasterFilters();\\nbroadcasterFilters(BroadcastFilter f);\\nisShareExecutorServices();\\nshareExecutorServices(boolean sharedThreadPools);\\nautoConfigureService(ServletContext sc);\\nendPointMapper();\\nendPointMapper(EndpointMapper endpointMapper);\\naddAnnotationPackage(Class clazz);\\nnotify(TYPE type,AtmosphereRequest request,AtmosphereResponse response);\\nnotifyDestroyed(String uuid);\\nnotifySuspended(String uuid);\\naddWebSocketHandler(WebSocketHandler handler);\\naddWebSocketHandler(String path,WebSocketHandler handler);\\naddWebSocketHandler(String path,WebSocketHandler handler,AtmosphereHandler h);\\naddWebSocketHandler(String path,WebSocketHandler handler,AtmosphereHandler h,List l);\\nannotationScanned(boolean b);\\ninitialized();\\npackages();\\ncustomAnnotationPackages();\\naddCustomAnnotationPackage(Class p);\\nobjectFactory(AtmosphereObjectFactory objectFactory);\\nexternalizeDestroy(boolean externalizeDestroy);\\nannotationProcessor();\\nisBroadcasterSpecified();\\nconfigureObjectFactory();\\nexcludeInterceptor(String interceptor);\\nfilterManipulator(FilterManipulator m);\\nfilterManipulators();\\nisAServletFilter();\\nobjectFactoryType();\\nmappingRegex();\\nmappingRegex(String mappingRegex);\\nsetUseServlet30(boolean useServlet30);\\nwebSocketEnabled();\\nwebSocketEnabled(boolean webSocketEnabled);\\nbroadcasterLifeCyclePolicy();\\nbroadcasterLifeCyclePolicy(String broadcasterLifeCyclePolicy);\\nbroadcasterListeners();\\nsharedThreadPools();\\nsharedThreadPools(boolean sharedThreadPools);\\nallowAllClassesScan();\\nallowAllClassesScan(boolean allowAllClassesScan);\\nobjectFactory();\\nexternalizeDestroy();\\nexcludedInterceptors();\\ndefaultInterceptors();\\natmosphereFactory();\\nconfigureAtmosphereResourceFactory();\\nconfigureWebSocketFactory();\\nmetaBroadcaster();\\nconfigureMetaBroadcaster();\\ngetDefaultSerializerClassName();\\ngetDefaultSerializerClass();\\nsetDefaultSerializerClassName(String defaultSerializerClassName);\\ninitDefaultSerializer();\\nsessionFactory();\\nisDestroyed();\\nframeworkListener(AtmosphereFrameworkListener l);\\nframeworkListeners();\\nonPreInit();\\nonPostInit();\\nonPreDestroy();\\nonPostDestroy();\\natmosphereResourceListeners();\\natmosphereResourceListener(AtmosphereResourceListener atmosphereResourceListener);\\nuuidProvider(UUIDProvider uuidProvider);\\nuuidProvider();\\nwebSocketFactory();\\nwebSocketFactory(WebSocketFactory webSocketFactory);\\ninitializationError(IllegalStateException initializationError);\\nMetaServiceAction(MetaServiceProcedure p);\\n\", \"repo_level\" : \"public interface Processor { void handle(AtmosphereFramework framework,Class annotatedClass);\\n }\\npublic interface BroadcasterCacheInspector { boolean inspect(BroadcastMessage message);\\n }\\npublic interface DefaultBroadcasterCache {public void start();\\npublic void stop();\\npublic void cleanup();\\npublic CacheMessage addToCache(String broadcasterId,String uuid,BroadcastMessage message);\\npublic List retrieveFromCache(String id,String uuid);\\npublic BroadcasterCache clearCache(String broadcasterId,String uuid,CacheMessage cache);\\npublic BroadcasterCache excludeFromCache(String broadcasterId,AtmosphereResource r);\\npublic BroadcasterCache cacheCandidate(String broadcasterId,String uuid);\\npublic BroadcasterCache inspector(BroadcasterCacheInspector interceptor);\\npublic BroadcasterCache addBroadcasterCacheListener(BroadcasterCacheListener l);\\npublic BroadcasterCache removeBroadcasterCacheListener(BroadcasterCacheListener l);\\npublic void configure(AtmosphereConfig config);\\n }\\npublic interface UUIDBroadcasterCache {public void configure(AtmosphereConfig config);\\npublic void start();\\npublic void stop();\\npublic void cleanup();\\npublic CacheMessage addToCache(String broadcasterId,String uuid,BroadcastMessage message);\\npublic List retrieveFromCache(String broadcasterId,String uuid);\\npublic BroadcasterCache clearCache(String broadcasterId,String uuid,CacheMessage message);\\npublic BroadcasterCache inspector(BroadcasterCacheInspector b);\\npublic BroadcasterCache addBroadcasterCacheListener(BroadcasterCacheListener l);\\npublic BroadcasterCache removeBroadcasterCacheListener(BroadcasterCacheListener l);\\nprotected String uuid(AtmosphereResource r);\\npublic Map> messages();\\npublic Map activeClients();\\nprotected boolean inspect(BroadcastMessage m);\\npublic void setInvalidateCacheInterval(long invalidateCacheInterval);\\npublic void setClientIdleTime(long clientIdleTime);\\nprotected void invalidateExpiredEntries();\\npublic BroadcasterCache excludeFromCache(String broadcasterId,AtmosphereResource r);\\npublic BroadcasterCache cacheCandidate(String broadcasterId,String uuid);\\npublic String toString();\\npublic List listeners();\\npublic List inspectors();\\n }\\npublic interface ApplicationConfiguration {public String getParamName();\\npublic void setParamName(String paramName);\\npublic String getParamValue();\\npublic void setParamValue(String paramValue);\\n }\\npublic interface AtmosphereHandlerConfig {public String getSupportSession();\\npublic void setSupportSession(String supportSession);\\npublic String getContextRoot();\\npublic void setContextRoot(String contextRoot);\\npublic String getClassName();\\npublic void setClassName(String className);\\npublic String getBroadcaster();\\npublic void setBroadcaster(String broadcaster);\\npublic List getProperties();\\npublic void setProperties(List properties);\\npublic List getApplicationConfig();\\npublic void setApplicationConfig(List applicationConfig);\\npublic List getFrameworkConfig();\\npublic void setFrameworkConfig(List frameworkConfig);\\npublic String getBroadcasterCache();\\npublic void setBroadcasterCache(String broadcasterCache);\\npublic List getBroadcastFilterClasses();\\npublic void setAtmosphereInterceptorClasses(List interceptors);\\npublic List getAtmosphereInterceptorClasses();\\npublic void setBroadcastFilterClasses(List broadcastFilterClasses);\\npublic String getCometSupport();\\npublic void setCometSupport(String cometSupport);\\n }\\npublic interface AtmosphereHandlerProperty {public String getName();\\npublic void setName(String name);\\npublic String getValue();\\npublic void setValue(String value);\\n }\\npublic interface FrameworkConfiguration {public String getParamName();\\npublic void setParamName(String paramName);\\npublic String getParamValue();\\npublic void setParamValue(String paramValue);\\n }\\npublic interface BlockingIOCometSupport {public Action service(AtmosphereRequest req,AtmosphereResponse res);\\nprotected void suspend(Action action,AtmosphereRequest req,AtmosphereResponse res);\\npublic void onResume(AtmosphereResourceEvent event);\\npublic Action cancelled(AtmosphereRequest req,AtmosphereResponse res);\\npublic void action(AtmosphereResourceImpl r);\\npublic AsyncSupport complete(AtmosphereResourceImpl r);\\n }\\npublic interface Tomcat7BIOSupportWithWebSocket {public Action service(AtmosphereRequest req,AtmosphereResponse res);\\npublic Action doService(AtmosphereRequest req,AtmosphereResponse res);\\npublic boolean supportWebSocket();\\n }\\npublic interface WebLogicServlet30WithWebSocket {public boolean supportWebSocket();\\npublic String getContainerName();\\n }\\npublic interface AbstractReflectorAtmosphereHandler {public void onStateChange(AtmosphereResourceEvent event);\\nprotected void write(AtmosphereResourceEvent event,ServletOutputStream o,byte[] data);\\nprotected boolean useTwoStepWrite(AtmosphereResourceEvent event);\\nfinal void postStateChange(AtmosphereResourceEvent event);\\npublic void destroy();\\npublic void init(AtmosphereConfig config);\\npublic void onRequest(AtmosphereResource resource);\\n }\\npublic interface ReflectorServletProcessor { void loadWebApplication(ServletConfig sc);\\npublic void onRequest(AtmosphereResource r);\\npublic void init(AtmosphereConfig config);\\npublic void addFilter(Filter filter);\\npublic void destroy();\\npublic String getServletClass();\\npublic void setServletClass(String servletClass);\\npublic String getServletClassName();\\npublic void setServletClassName(String servletClass);\\npublic void setFilterClassName(String filterClass);\\npublic void addFilterClassName(String filterClass,String filterName);\\npublic Servlet getServlet();\\npublic void setServlet(Servlet servlet);\\npublic void destroy();\\npublic String getInitParameter(String name);\\npublic Enumeration getInitParameterNames();\\npublic ServletConfig getServletConfig();\\npublic ServletContext getServletContext();\\npublic String getServletInfo();\\npublic void init(ServletConfig sc);\\npublic void init();\\npublic void log(String msg);\\npublic void log(String message,Throwable t);\\npublic void service(ServletRequest req,ServletResponse res);\\npublic String getServletName();\\npublic String toString();\\n }\\npublic interface InjectableObjectFactory {public void configure(AtmosphereConfig config);\\npublic void started(AtmosphereFramework framework);\\nprotected void retryInjection(AtmosphereFramework framework);\\npublic U newClassInstance(Class classType,Class defaultType);\\npublic T inject(T instance);\\npublic void applyMethods(U instance,Class defaultType);\\npublic void injectInjectable(U instance,Class defaultType,AtmosphereFramework framework);\\npublic void injectFields(Set fields,U instance,AtmosphereFramework framework,LinkedList injectable);\\npublic AtmosphereObjectFactory allowInjectionOf(Injectable injectable);\\npublic AtmosphereObjectFactory allowInjectionOf(Injectable injectable,boolean first);\\npublic String toString();\\npublic U getInjectable(Class u);\\npublic void requestScoped(Object instance,Class defaultType,AtmosphereResource r);\\npublic void requestScoped(Object instance,Class defaultType);\\npublic boolean needRequestScoped(Class defaultType);\\npublic InjectableObjectFactory listener(InjectionListener i);\\nprotected void injectionFailed();\\nprotected void nullFieldInjectionFor(Field field,U instance,Class clazz);\\nprotected void fieldInjectionException(Field field,U instance,Class clazz,Exception ex);\\nprotected void methodInjectionException(Method m,U instance,Class clazz,Exception ex);\\nprotected void preFieldInjection(Field field,U instance,Class clazz);\\nprotected void postFieldInjection(Field field,U instance,Class clazz);\\nprotected void preMethodInjection(Method method,U instance,Class clazz);\\nprotected void postMethodInjection(Method method,U instance,Class clazz);\\n }\\npublic interface AndroidAtmosphereInterceptor {public Action inspect(AtmosphereResource r);\\npublic void prePayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic void postPayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic String toString();\\n }\\npublic interface CacheHeadersInterceptor {public void configure(AtmosphereConfig config);\\npublic Action inspect(AtmosphereResource r);\\npublic boolean injectCacheHeaders();\\npublic boolean writeHeaders();\\npublic CacheHeadersInterceptor injectCacheHeaders(boolean injectCacheHeaders);\\npublic CacheHeadersInterceptor writeHeaders(boolean writeHeaders);\\npublic String toString();\\n }\\npublic interface CorsInterceptor {public void configure(AtmosphereConfig config);\\npublic Action inspect(AtmosphereResource r);\\npublic boolean enableAccessControl();\\npublic CorsInterceptor enableAccessControl(boolean enableAccessControl);\\npublic PRIORITY priority();\\npublic String toString();\\n }\\npublic interface HeartbeatInterceptor {public HeartbeatInterceptor paddingText(byte[] paddingBytes);\\npublic byte[] getPaddingBytes();\\npublic HeartbeatInterceptor heartbeatFrequencyInSeconds(int heartbeatFrequencyInSeconds);\\npublic int heartbeatFrequencyInSeconds();\\npublic int clientHeartbeatFrequencyInSeconds();\\npublic HeartbeatInterceptor clientHeartbeatFrequencyInSeconds(int clientHeartbeatFrequencyInSeconds);\\npublic boolean resumeOnHeartbeat();\\npublic HeartbeatInterceptor resumeOnHeartbeat(boolean resumeOnHeartbeat);\\npublic void configure(AtmosphereConfig config);\\npublic Action inspect(AtmosphereResource r);\\npublic void onHeartbeat(AtmosphereResourceEvent event);\\npublic void onSuspend(AtmosphereResourceEvent event);\\npublic void onResume(AtmosphereResourceEvent event);\\npublic void onDisconnect(AtmosphereResourceEvent event);\\npublic void onClose(AtmosphereResourceEvent event);\\npublic byte[] transformPayload(AtmosphereResponse response,byte[] responseDraft,byte[] data);\\npublic void postPayload(AtmosphereResponse response,byte[] data,int offset,int length);\\nprotected int extractHeartbeatInterval(AtmosphereResourceImpl resource);\\n void cancelF(AtmosphereRequest request);\\npublic HeartbeatInterceptor clock(int interval,AtmosphereResource r,AtmosphereRequest request,AtmosphereResponse response);\\npublic String toString();\\npublic void destroy();\\n }\\npublic interface IdleResourceInterceptor {public void configure(AtmosphereConfig config);\\nprotected void idleResources();\\npublic long maxInactiveTime();\\npublic IdleResourceInterceptor maxInactiveTime(long maxInactiveTime);\\npublic Action inspect(AtmosphereResource r);\\npublic PRIORITY priority();\\npublic void destroy();\\n }\\npublic interface InvokationOrder { PRIORITY priority();\\n }\\npublic interface JSONPAtmosphereInterceptor {public void configure(AtmosphereConfig config);\\npublic Action inspect(AtmosphereResource r);\\n String callbackName();\\npublic void prePayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic byte[] transformPayload(AtmosphereResponse response,byte[] responseDraft,byte[] data);\\npublic void postPayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic String toString();\\n }\\npublic interface JavaScriptProtocol {public void configure(AtmosphereConfig config);\\npublic Action inspect(AtmosphereResource ar);\\npublic void onSuspend(AtmosphereResourceEvent event);\\npublic String wsDelimiter();\\npublic JavaScriptProtocol wsDelimiter(String wsDelimiter);\\npublic boolean enforceAtmosphereVersion();\\npublic JavaScriptProtocol enforceAtmosphereVersion(boolean enforceAtmosphereVersion);\\npublic String toString();\\n }\\npublic interface OnDisconnectInterceptor {public void configure(AtmosphereConfig config);\\npublic Action inspect(AtmosphereResource r);\\npublic String toString();\\n }\\npublic interface PaddingAtmosphereInterceptor {static String confPadding(int size);\\npublic Action inspect(AtmosphereResource r);\\npublic void prePayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic void postPayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic String toString();\\npublic void onPreSuspend(AtmosphereResourceEvent event);\\n }\\npublic interface SSEAtmosphereInterceptor {public void configure(AtmosphereConfig config);\\npublic void onPreSuspend(AtmosphereResourceEvent event);\\npublic Action inspect(AtmosphereResource r);\\npublic void prePayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic byte[] transformPayload(AtmosphereResponse response,byte[] responseDraft,byte[] data);\\npublic void postPayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic String toString();\\n }\\npublic interface WebSocketMessageSuspendInterceptor {public Action inspect(AtmosphereResource r);\\n }\\npublic interface AtmosphereConfigReader {public AtmosphereConfig parse(AtmosphereConfig config,String filename);\\npublic AtmosphereConfig parse(AtmosphereConfig config,InputStream stream);\\nstatic AtmosphereConfigReader getInstance();\\n }\\npublic interface DefaultEndpointMapper {protected U match(String path,Map handlers);\\npublic String computePath(AtmosphereRequest req);\\npublic void configure(AtmosphereConfig config);\\npublic U map(AtmosphereRequest req,Map handlers);\\npublic U map(String path,Map handlers);\\n }\\npublic interface DefaultUUIDProvider {public String generateUuid();\\n }\\npublic interface EndpointMapper { U map(AtmosphereRequest req,Map handlers);\\n U map(String path,Map handlers);\\n }\\npublic interface ExecutorsFactory {public Thread newThread(Runnable runnable);\\nstatic ExecutorService getMessageDispatcher(AtmosphereConfig config,String name);\\nstatic ExecutorService getAsyncOperationExecutor(AtmosphereConfig config,String name);\\nstatic ScheduledExecutorService getScheduler(AtmosphereConfig config);\\npublic Thread newThread(Runnable runnable);\\nstatic void reset(AtmosphereConfig config);\\n }\\npublic interface IOUtils {static void deliver(Object o,DeliverTo deliverConfig,DELIVER_TO defaultDeliver,AtmosphereResource r);\\nstatic Object readEntirely(AtmosphereResource r);\\nstatic boolean isBodyBinary(AtmosphereRequest request);\\nstatic boolean isBodyEmpty(Object o);\\nstatic StringBuilder readEntirelyAsString(AtmosphereResource r);\\nstatic byte[] readEntirelyAsByte(AtmosphereResource r);\\nstatic byte[] forceReadEntirelyAsByte(AtmosphereResource r);\\nstatic String guestServletPath(AtmosphereConfig config);\\nstatic String guestRawServletPath(AtmosphereConfig config);\\nstatic String getCleanedServletPath(String fullServletPath);\\nstatic Class loadClass(Class thisClass,String className);\\nstatic boolean isAtmosphere(String className);\\nstatic Map readServiceFile(String path);\\nstatic void close(Closeable closeableArray);\\nstatic String realPath(ServletContext servletContext,String targetPath);\\n }\\npublic interface IntrospectionUtils {static void execute(Object proxy,String method);\\nstatic void setAttribute(Object proxy,String name,Object value);\\nstatic Object getAttribute(Object proxy,String name);\\nstatic boolean setProperty(Object o,String name,String value);\\nstatic boolean addProperty(Object o,String name,String value);\\npublic boolean invokeProperty(Object object,String setter,String name,String value);\\nstatic Object getProperty(Object object,String name);\\nstatic void setProperty(Object object,String name);\\nstatic String replaceProperties(String value,Hashtable staticProp,PropertySource dynamicProp);\\nstatic String capitalize(String name);\\nstatic String unCapitalize(String name);\\nstatic void addToClassPath(Vector cpV,String dir);\\nstatic void addToolsJar(Vector v);\\nstatic String[] getFilesByExt(String ld,String ext);\\npublic boolean accept(File d,String name);\\nstatic URL getURL(String base,String file);\\nstatic void addJarsFromClassPath(Vector jars,String cp);\\nstatic URL[] getClassPath(Vector v);\\nstatic URL[] getClassPath(String dir,String cpath,String cpathProp,boolean addTools);\\nstatic boolean processArgs(Object proxy,String args);\\nstatic boolean processArgs(Object proxy,String args,String args0,String args1,Hashtable aliases);\\nstatic void clear();\\nstatic String[] findVoidSetters(Class c);\\nstatic String[] findBooleanSetters(Class c);\\nstatic Method[] findMethods(Class c);\\nstatic Method findMethod(Class c,String name,Class params);\\nstatic boolean hasHook(Object obj,String methodN);\\nstatic void callMain(Class c,String args);\\nstatic Object callMethod1(Object target,String methodN,Object param1,String typeParam1,ClassLoader cl);\\nstatic Object callMethod0(Object target,String methodN);\\nstatic Object callMethodN(Object target,String methodN,Object params,Class typeParams);\\nstatic Object convert(String object,Class paramType);\\npublic String getProperty(String key);\\npublic void setAttribute(String key,Object o);\\nstatic void debug(String s);\\n }\\npublic interface ServletContextFactory {public void init(ServletContext servletContext);\\npublic ServletContext getServletContext();\\nstatic ServletContextFactory getDefault();\\n }\\npublic interface UUIDProvider { String generateUuid();\\n }\\npublic interface Utils {static boolean webSocketEnabled(HttpServletRequest request);\\nstatic boolean rawWebSocket(HttpServletRequest request);\\nstatic boolean firefoxWebSocketEnabled(HttpServletRequest request);\\nstatic boolean twoConnectionsTransport(TRANSPORT t);\\nstatic boolean webSocketQueryStringPresentOrNull(HttpServletRequest request);\\nstatic boolean resumableTransport(TRANSPORT t);\\nstatic boolean pollableTransport(TRANSPORT t);\\nstatic boolean pushMessage(TRANSPORT t);\\nstatic boolean atmosphereProtocol(AtmosphereRequest r);\\nstatic boolean webSocketMessage(AtmosphereResource r);\\nstatic boolean properProtocol(HttpServletRequest request);\\nstatic AtmosphereResource websocketResource(AtmosphereResource r);\\nstatic boolean closeMessage(HttpServletRequest request);\\nstatic Object invoke(Object proxiedInstance,Method m,Object o);\\nstatic void inject(AtmosphereResource r);\\nstatic void inject(Object object,Class clazz,AtmosphereResource r);\\nstatic void inject(Object object,Class clazz,AtmosphereConfig config);\\nstatic Set getInheritedPrivateFields(Class type);\\nstatic Set getInheritedPrivateMethod(Class type);\\nstatic boolean requestScopedInjection(AtmosphereConfig config,AtmosphereHandler h);\\nstatic boolean requestScopedInjection(AtmosphereConfig config,Object o);\\nstatic void destroyMeteor(AtmosphereRequest req);\\nstatic String pathInfo(AtmosphereRequest request);\\nstatic boolean isRunningTest();\\nstatic boolean isUnderJDK11AndUp();\\n }\\npublic interface Version {static void main(String[] args);\\nstatic String getRawVersion();\\nstatic String getDotedVersion();\\nstatic int getMajorVersion();\\nstatic int getMinorVersion();\\nstatic int getMicroVersion();\\nstatic boolean equalVersion(int major,int minor);\\n }\\npublic interface VoidServletConfig {public String getServletName();\\npublic ServletContext getServletContext();\\npublic String getInitParameter(String name);\\npublic Enumeration getInitParameterNames();\\n }\\npublic interface FocusPoint {public String getName();\\npublic void setParentTrackPoint(FocusPoint parentFocusPoint);\\npublic FocusPoint getParentFocusPoint();\\npublic String getContentURI();\\npublic String getContentTitle();\\n }\\npublic interface JGoogleAnalyticsTracker {public void setUrlBuildingStrategy(URLBuildingStrategy urlBuildingStrategy);\\npublic void trackSynchronously(FocusPoint focusPoint);\\n }\\npublic interface ModuleDetection {static String detect();\\nstatic boolean check(String clazz);\\n }\\npublic interface DefaultWebSocketFactory {public WebSocket find(String uuid);\\n }\\npublic interface DefaultWebSocketProcessor {public WebSocketProcessor configure(AtmosphereConfig config);\\npublic Action service(AtmosphereRequest req,AtmosphereResponse res);\\npublic boolean handshake(HttpServletRequest request);\\npublic WebSocketProcessor registerWebSocketHandler(String path,WebSocketHandlerProxy webSockethandler);\\nfinal void open(WebSocket webSocket,AtmosphereRequest request,AtmosphereResponse response);\\nprotected WebSocketHandler postProcessMapping(WebSocket webSocket,AtmosphereRequest request,WebSocketHandlerProxy w);\\npublic void invokeWebSocketProtocol(WebSocket webSocket,String webSocketMessage);\\npublic void invokeWebSocketProtocol(WebSocket webSocket,byte[] data,int offset,int length);\\npublic void invokeWebSocketProtocol(WebSocket webSocket,InputStream stream);\\npublic void invokeWebSocketProtocol(WebSocket webSocket,Reader reader);\\nfinal void dispatch(WebSocket webSocket,AtmosphereRequest request,AtmosphereResponse r);\\npublic void close(WebSocket webSocket,int closeCode);\\npublic void executeClose(WebSocket webSocket,int closeCode);\\npublic void destroy();\\npublic void notifyListener(WebSocket webSocket,WebSocketEventListener.WebSocketEvent event);\\nstatic Map configureHeader(AtmosphereRequest request);\\nprotected void dispatchStream(WebSocket webSocket,InputStream is);\\nprotected void dispatchReader(WebSocket webSocket,Reader r);\\nprotected void optimizeMapping();\\npublic boolean wildcardMapping();\\npublic DefaultWebSocketProcessor wildcardMapping(boolean wildcardMapping);\\npublic Map handlers();\\npublic boolean executeAsync();\\npublic boolean destroyable();\\npublic int byteBufferMaxSize();\\npublic DefaultWebSocketProcessor byteBufferMaxSize(int byteBufferMaxSize);\\npublic int charBufferMaxSize();\\npublic DefaultWebSocketProcessor charBufferMaxSize(int charBufferMaxSize);\\npublic long closingTime();\\npublic EndpointMapper mapper();\\npublic boolean invokeInterceptors();\\npublic void onPong(WebSocket webSocket,byte[] payload,int offset,int length);\\npublic void onPing(WebSocket webSocket,byte[] payload,int offset,int length);\\n }\\npublic interface WebSocket {public AtmosphereConfig config();\\nprotected WebSocket webSocketHandler(WebSocketHandler webSocketHandler);\\npublic WebSocket binaryWrite(boolean binaryWrite);\\npublic WebSocketHandler webSocketHandler();\\npublic WebSocket resource(AtmosphereResource r);\\nsynchronized void shiftAttributes();\\npublic Map attributes();\\npublic AtmosphereResource resource();\\npublic long lastWriteTimeStampInMilliseconds();\\nprotected byte[] transform(byte[] b,int offset,int length);\\nprotected byte[] transform(AtmosphereResponse response,byte[] b,int offset,int length);\\npublic WebSocket write(AtmosphereResponse r,String data);\\npublic WebSocket write(AtmosphereResponse r,byte[] data);\\npublic WebSocket write(AtmosphereResponse r,byte[] b,int offset,int length);\\npublic WebSocket broadcast(Object o);\\npublic WebSocket writeError(AtmosphereResponse r,int errorCode,String message);\\npublic WebSocket redirect(AtmosphereResponse r,String location);\\npublic void close(AtmosphereResponse r);\\npublic WebSocket flush(AtmosphereResponse r);\\npublic boolean isOpen();\\npublic WebSocket write(String s);\\npublic WebSocket write(byte[] b,int offset,int length);\\npublic WebSocket write(byte[] b);\\npublic void close();\\npublic void close(int statusCode,String reasonText);\\npublic String uuid();\\nstatic void notSupported(AtmosphereRequest request,AtmosphereResponse response);\\npublic WebSocket sendPing(byte[] payload);\\npublic WebSocket sendPong(byte[] payload);\\npublic WebSocket attachment(Object attachment);\\npublic Object attachment();\\n }\\npublic interface WebSocketFactory { WebSocket find(String uuid);\\n }\\npublic interface WebSocketHandler { void onByteMessage(WebSocket webSocket,byte[] data,int offset,int length);\\n void onTextMessage(WebSocket webSocket,String data);\\n void onOpen(WebSocket webSocket);\\n void onClose(WebSocket webSocket);\\n void onError(WebSocket webSocket,WebSocketException t);\\n }\\npublic interface WebSocketProcessor { WebSocketProcessor configure(AtmosphereConfig config);\\n boolean handshake(HttpServletRequest request);\\n WebSocketProcessor registerWebSocketHandler(String path,WebSocketHandlerProxy webSockethandler);\\n void open(WebSocket webSocket,AtmosphereRequest request,AtmosphereResponse response);\\n void invokeWebSocketProtocol(WebSocket webSocket,String webSocketMessage);\\n void invokeWebSocketProtocol(WebSocket webSocket,byte[] data,int offset,int length);\\n void invokeWebSocketProtocol(WebSocket webSocket,InputStream stream);\\n void invokeWebSocketProtocol(WebSocket webSocket,Reader reader);\\n void close(WebSocket webSocket,int closeCode);\\n void notifyListener(WebSocket webSocket,WebSocketEvent webSocketEvent);\\n void destroy();\\npublic AtmosphereResponse response();\\npublic String path();\\npublic WebSocketHandlerProxy path(String path);\\npublic WebSocketHandler proxied();\\npublic void onByteMessage(WebSocket webSocket,byte[] data,int offset,int length);\\npublic void onTextMessage(WebSocket webSocket,String data);\\npublic void onOpen(WebSocket webSocket);\\npublic void onClose(WebSocket webSocket);\\npublic void onError(WebSocket webSocket,WebSocketException t);\\n }\\npublic interface WebSocketProtocol { List onMessage(WebSocket webSocket,String data);\\n List onMessage(WebSocket webSocket,byte[] data,int offset,int length);\\n void onOpen(WebSocket webSocket);\\n void onClose(WebSocket webSocket);\\n void onError(WebSocket webSocket,WebSocketException t);\\n }\\npublic interface SimpleHttpProtocol {public void configure(AtmosphereConfig config);\\npublic List onMessage(WebSocket webSocket,String message);\\npublic List onMessage(WebSocket webSocket,byte[] d,int offset,int length);\\npublic void onOpen(WebSocket webSocket);\\npublic void onClose(WebSocket webSocket);\\npublic void onError(WebSocket webSocket,WebSocketException t);\\n }\\n\" }", "class_name": "AtmosphereFramework", "code": "public AtmosphereFramework removeAtmosphereHandler(String mapping){\n if (mapping.endsWith(\"/\")) {\n mapping+=mappingRegex;\n }\n atmosphereHandlers.remove(mapping);\n return this;\n}\n", "docstring": "/** \n * Remove an {@link AtmosphereHandler}.\n * @param mapping the mapping used when invoking {@link #addAtmosphereHandler(String,AtmosphereHandler)};\n * @return true if removed\n */\n", "end_lineno": "760", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\npackage org.atmosphere.cpr;\n\nimport org.atmosphere.annotation.Processor;\nimport org.atmosphere.cache.BroadcasterCacheInspector;\nimport org.atmosphere.cache.DefaultBroadcasterCache;\nimport org.atmosphere.cache.UUIDBroadcasterCache;\nimport org.atmosphere.config.ApplicationConfiguration;\nimport org.atmosphere.config.AtmosphereHandlerConfig;\nimport org.atmosphere.config.AtmosphereHandlerProperty;\nimport org.atmosphere.config.FrameworkConfiguration;\nimport org.atmosphere.container.BlockingIOCometSupport;\nimport org.atmosphere.container.Tomcat7BIOSupportWithWebSocket;\nimport org.atmosphere.container.WebLogicServlet30WithWebSocket;\nimport org.atmosphere.handler.AbstractReflectorAtmosphereHandler;\nimport org.atmosphere.handler.ReflectorServletProcessor;\nimport org.atmosphere.inject.InjectableObjectFactory;\nimport org.atmosphere.interceptor.AndroidAtmosphereInterceptor;\nimport org.atmosphere.interceptor.CacheHeadersInterceptor;\nimport org.atmosphere.interceptor.CorsInterceptor;\nimport org.atmosphere.interceptor.HeartbeatInterceptor;\nimport org.atmosphere.interceptor.IdleResourceInterceptor;\nimport org.atmosphere.interceptor.InvokationOrder;\nimport org.atmosphere.interceptor.JSONPAtmosphereInterceptor;\nimport org.atmosphere.interceptor.JavaScriptProtocol;\nimport org.atmosphere.interceptor.OnDisconnectInterceptor;\nimport org.atmosphere.interceptor.PaddingAtmosphereInterceptor;\nimport org.atmosphere.interceptor.SSEAtmosphereInterceptor;\nimport org.atmosphere.interceptor.WebSocketMessageSuspendInterceptor;\nimport org.atmosphere.util.AtmosphereConfigReader;\nimport org.atmosphere.util.DefaultEndpointMapper;\nimport org.atmosphere.util.DefaultUUIDProvider;\nimport org.atmosphere.util.EndpointMapper;\nimport org.atmosphere.util.ExecutorsFactory;\nimport org.atmosphere.util.IOUtils;\nimport org.atmosphere.util.IntrospectionUtils;\nimport org.atmosphere.util.ServletContextFactory;\nimport org.atmosphere.util.UUIDProvider;\nimport org.atmosphere.util.Utils;\nimport org.atmosphere.util.Version;\nimport org.atmosphere.util.VoidServletConfig;\nimport org.atmosphere.util.analytics.FocusPoint;\nimport org.atmosphere.util.analytics.JGoogleAnalyticsTracker;\nimport org.atmosphere.util.analytics.ModuleDetection;\nimport org.atmosphere.websocket.DefaultWebSocketFactory;\nimport org.atmosphere.websocket.DefaultWebSocketProcessor;\nimport org.atmosphere.websocket.WebSocket;\nimport org.atmosphere.websocket.WebSocketFactory;\nimport org.atmosphere.websocket.WebSocketHandler;\nimport org.atmosphere.websocket.WebSocketProcessor;\nimport org.atmosphere.websocket.WebSocketProtocol;\nimport org.atmosphere.websocket.protocol.SimpleHttpProtocol;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.servlet.Servlet;\nimport javax.servlet.ServletConfig;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.UnsupportedEncodingException;\nimport java.net.HttpURLConnection;\nimport java.net.MalformedURLException;\nimport java.net.URI;\nimport java.net.URL;\nimport java.net.URLClassLoader;\nimport java.net.URLDecoder;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Objects;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\nimport static org.atmosphere.cpr.ApplicationConfig.ALLOW_QUERYSTRING_AS_REQUEST;\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER;\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER_MAPPING;\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER_PATH;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CACHE;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CLASS;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_FACTORY;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_LIFECYCLE_POLICY;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_SHAREABLE_LISTENERS;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_WAIT_TIME;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCAST_FILTER_CLASSES;\nimport static org.atmosphere.cpr.ApplicationConfig.CONTENT_TYPE_FIRST_RESPONSE;\nimport static org.atmosphere.cpr.ApplicationConfig.DISABLE_ONSTATE_EVENT;\nimport static org.atmosphere.cpr.ApplicationConfig.META_SERVICE_PATH;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_ALLOW_SESSION_TIMEOUT_REMOVAL;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_ATMOSPHERE_XML;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_BLOCKING_COMETSUPPORT;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_COMET_SUPPORT;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_NATIVE_COMETSUPPORT;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SERVLET_MAPPING;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SESSION_SUPPORT;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_THROW_EXCEPTION_ON_CLONED_REQUEST;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_USE_STREAM;\nimport static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID;\nimport static org.atmosphere.cpr.ApplicationConfig.USE_SERVLET_CONTEXT_PARAMETERS;\nimport static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROCESSOR;\nimport static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROTOCOL;\nimport static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_SUPPORT;\nimport static org.atmosphere.cpr.Broadcaster.ROOT_MASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.ATMOSPHERE_CONFIG;\nimport static org.atmosphere.cpr.FrameworkConfig.CDI_INJECTOR;\nimport static org.atmosphere.cpr.FrameworkConfig.GUICE_INJECTOR;\nimport static org.atmosphere.cpr.FrameworkConfig.HAZELCAST_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.INJECT_LIBARY;\nimport static org.atmosphere.cpr.FrameworkConfig.JERSEY_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.JERSEY_CONTAINER;\nimport static org.atmosphere.cpr.FrameworkConfig.JGROUPS_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.JMS_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.KAFKA_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.RABBITMQ_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.REDIS_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.RMI_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.SPRING_INJECTOR;\nimport static org.atmosphere.cpr.FrameworkConfig.THROW_EXCEPTION_ON_CLONED_REQUEST;\nimport static org.atmosphere.cpr.FrameworkConfig.XMPP_BROADCASTER;\nimport static org.atmosphere.cpr.HeaderConfig.ATMOSPHERE_POST_BODY;\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_TRACKING_ID;\nimport static org.atmosphere.util.IOUtils.realPath;\nimport static org.atmosphere.websocket.WebSocket.WEBSOCKET_SUSPEND;\n\n/**\n * The {@link AtmosphereFramework} is the entry point for the framework. This class can be used to from Servlet/filter\n * to dispatch {@link AtmosphereRequest} and {@link AtmosphereResponse}. The framework can also be configured using\n * the setXXX method. The life cycle of this class is\n *
\n * AtmosphereFramework f = new AtmosphereFramework();\n * f.init();\n * f.doCometSupport(AtmosphereRequest, AtmosphereResource);\n * f.destroy();\n * 
\n *\n * @author Jeanfrancois Arcand\n */\npublic class AtmosphereFramework {\n\n public static final String DEFAULT_ATMOSPHERE_CONFIG_PATH = \"/META-INF/atmosphere.xml\";\n public static final String DEFAULT_LIB_PATH = \"/WEB-INF/lib/\";\n public static final String DEFAULT_HANDLER_PATH = \"/WEB-INF/classes/\";\n public static final String META_SERVICE = \"META-INF/services/\";\n public static final String MAPPING_REGEX = \"[a-zA-Z0-9-&.*_~=@;\\\\?]+\";\n public static final String ASYNC_IO = \"io.async\";\n\n protected static final Logger logger = LoggerFactory.getLogger(AtmosphereFramework.class);\n\n protected final List broadcasterFilters = new ArrayList<>();\n protected final List asyncSupportListeners = new ArrayList<>();\n protected final List atmosphereResourceListeners = new ArrayList<>();\n protected final ArrayList possibleComponentsCandidate = new ArrayList<>();\n protected final HashMap initParams = new HashMap<>();\n protected final AtmosphereConfig config;\n protected final AtomicBoolean isCometSupportConfigured = new AtomicBoolean(false);\n protected final boolean isFilter;\n protected final Map atmosphereHandlers = new ConcurrentHashMap<>();\n protected final ConcurrentLinkedQueue broadcasterTypes = new ConcurrentLinkedQueue<>();\n protected final ConcurrentLinkedQueue objectFactoryType = new ConcurrentLinkedQueue<>();\n protected final ConcurrentLinkedQueue inspectors = new ConcurrentLinkedQueue<>();\n\n protected String mappingRegex = MAPPING_REGEX;\n protected boolean useNativeImplementation;\n protected boolean useBlockingImplementation;\n protected boolean useStreamForFlushingComments = true;\n protected boolean useServlet30 = true;\n protected AsyncSupport asyncSupport;\n protected String broadcasterClassName = DefaultBroadcaster.class.getName();\n protected boolean isCometSupportSpecified;\n protected boolean isBroadcasterSpecified;\n protected boolean isSessionSupportSpecified;\n protected boolean isThrowExceptionOnClonedRequestSpecified;\n protected BroadcasterFactory broadcasterFactory;\n protected String broadcasterFactoryClassName;\n protected String broadcasterCacheClassName;\n protected boolean webSocketEnabled = true;\n protected String broadcasterLifeCyclePolicy = \"NEVER\";\n protected String webSocketProtocolClassName = SimpleHttpProtocol.class.getName();\n protected WebSocketProtocol webSocketProtocol;\n protected String handlersPath = DEFAULT_HANDLER_PATH;\n protected ServletConfig servletConfig;\n protected boolean autoDetectHandlers = true;\n private boolean hasNewWebSocketProtocol;\n protected String atmosphereDotXmlPath = DEFAULT_ATMOSPHERE_CONFIG_PATH;\n protected String metaServicePath = META_SERVICE;\n protected final LinkedList interceptors = new LinkedList<>();\n protected boolean scanDone;\n protected String annotationProcessorClassName = \"org.atmosphere.cpr.DefaultAnnotationProcessor\";\n protected final List broadcasterListeners = Collections.synchronizedList(new ArrayList<>());\n protected String webSocketProcessorClassName = DefaultWebSocketProcessor.class.getName();\n protected boolean webSocketProtocolInitialized;\n protected EndpointMapper endpointMapper = new DefaultEndpointMapper<>();\n protected String libPath = DEFAULT_LIB_PATH;\n protected boolean isInit;\n protected boolean sharedThreadPools = true;\n protected final List packages = new ArrayList<>();\n protected final LinkedList annotationPackages = new LinkedList<>();\n protected boolean allowAllClassesScan = true;\n protected boolean annotationFound;\n protected boolean executeFirstSet;\n protected AtmosphereObjectFactory objectFactory = new DefaultAtmosphereObjectFactory();\n protected final AtomicBoolean isDestroyed = new AtomicBoolean();\n protected boolean externalizeDestroy;\n protected AnnotationProcessor annotationProcessor;\n protected final List excludedInterceptors = new ArrayList<>();\n protected final LinkedList broadcasterCacheListeners = new LinkedList<>();\n protected final List filterManipulators = new ArrayList<>();\n protected AtmosphereResourceFactory arFactory;\n protected MetaBroadcaster metaBroadcaster;\n protected AtmosphereResourceSessionFactory sessionFactory;\n protected String defaultSerializerClassName;\n protected Class defaultSerializerClass;\n protected final List frameworkListeners = new LinkedList<>();\n private UUIDProvider uuidProvider = new DefaultUUIDProvider();\n protected Thread shutdownHook;\n public static final List> DEFAULT_ATMOSPHERE_INTERCEPTORS = new LinkedList>() {\n {\n // Add CORS support\n add(CorsInterceptor.class);\n // Default Interceptor\n add(CacheHeadersInterceptor.class);\n // WebKit & IE Padding\n add(PaddingAtmosphereInterceptor.class);\n // Android 2.3.x streaming support\n add(AndroidAtmosphereInterceptor.class);\n // Heartbeat\n add(HeartbeatInterceptor.class);\n // Add SSE support\n add(SSEAtmosphereInterceptor.class);\n // ADD JSONP support\n add(JSONPAtmosphereInterceptor.class);\n // ADD Tracking ID Handshake\n add(JavaScriptProtocol.class);\n // WebSocket and suspend\n add(WebSocketMessageSuspendInterceptor.class);\n // OnDisconnect\n add(OnDisconnectInterceptor.class);\n // Idle connection\n add(IdleResourceInterceptor.class);\n }\n };\n private WebSocketFactory webSocketFactory;\n private IllegalStateException initializationError;\n\n /**\n * An implementation of {@link AbstractReflectorAtmosphereHandler}.\n */\n public final static AtmosphereHandler REFLECTOR_ATMOSPHEREHANDLER = new AbstractReflectorAtmosphereHandler() {\n @Override\n public void onRequest(AtmosphereResource resource) {\n logger.trace(\"VoidHandler {}\", resource.uuid());\n }\n\n @Override\n public void destroy() {\n logger.trace(\"VoidHandler\");\n }\n };\n\n public void setAndConfigureAtmosphereResourceFactory(AtmosphereResourceFactory arFactory) {\n this.arFactory = arFactory;\n this.arFactory.configure(config);\n }\n\n public static final class AtmosphereHandlerWrapper {\n\n public final AtmosphereHandler atmosphereHandler;\n public Broadcaster broadcaster;\n public String mapping;\n public final LinkedList interceptors = new LinkedList<>();\n public boolean create;\n private boolean needRequestScopedInjection;\n private final boolean wilcardMapping;\n\n public AtmosphereHandlerWrapper(BroadcasterFactory broadcasterFactory, final AtmosphereHandler atmosphereHandler, String mapping,\n final AtmosphereConfig config) {\n this.atmosphereHandler = atmosphereHandler;\n\n try {\n if (broadcasterFactory != null) {\n this.broadcaster = broadcasterFactory.lookup(mapping, true);\n } else {\n this.mapping = mapping;\n }\n } catch (Exception t) {\n throw new RuntimeException(t);\n }\n wilcardMapping = mapping.contains(\"{\") && mapping.contains(\"}\");\n hookInjection(config);\n }\n\n void hookInjection(final AtmosphereConfig config) {\n config.startupHook(framework -> needRequestScopedInjection = Utils.requestScopedInjection(config, atmosphereHandler));\n }\n\n public AtmosphereHandlerWrapper(final AtmosphereHandler atmosphereHandler, Broadcaster broadcaster,\n final AtmosphereConfig config) {\n this.atmosphereHandler = atmosphereHandler;\n this.broadcaster = broadcaster;\n hookInjection(config);\n wilcardMapping = false;\n }\n\n @Override\n public String toString() {\n\n StringBuilder b = new StringBuilder();\n for (int i = 0; i < interceptors.size(); i++) {\n b.append(\"\\n\\t\").append(i).append(\": \").append(interceptors.get(i).getClass().getName());\n }\n\n return \"\\n atmosphereHandler\"\n + \"\\n\\t\" + atmosphereHandler\n + \"\\n interceptors\" +\n b.toString()\n + \"\\n broadcaster\"\n + \"\\t\" + broadcaster;\n }\n\n public boolean needRequestScopedInjection() {\n return needRequestScopedInjection;\n }\n\n public boolean wildcardMapping() {\n return wilcardMapping;\n }\n }\n\n /**\n *

\n * This enumeration represents all possible actions to specify in a meta service file.\n *

\n *\n * @author Guillaume DROUET\n * @version 1.0\n * @since 2.2.0\n */\n public enum MetaServiceAction {\n\n /**\n * Install service.\n */\n INSTALL(new InstallMetaServiceProcedure()),\n\n /**\n * Exclude service.\n */\n EXCLUDE(new ExcludeMetaServiceProcedure());\n\n /**\n * The procedure to apply.\n */\n private MetaServiceProcedure procedure;\n\n /**\n *

\n * Builds a new instance.\n *

\n *\n * @param p the enum procedure\n */\n MetaServiceAction(final MetaServiceProcedure p) {\n procedure = p;\n }\n\n /**\n *

\n * Applies this action to given class.\n *

\n *\n * @param fwk the framework\n * @param clazz the class\n * @throws Exception if procedure fails\n */\n public void apply(final AtmosphereFramework fwk, final Class clazz) throws Exception {\n procedure.apply(fwk, clazz);\n\n }\n\n /**\n *

\n * This interface defined a method with a signature like a procedure to process an action.\n *

\n *\n * @author Guillaume DROUET\n * @version 1.0\n * @since 2.2.0\n */\n private interface MetaServiceProcedure {\n\n /**\n *

\n * Processes an action.\n *

\n *\n * @param fwk the framework\n * @param clazz the class to use during processing\n * @throws Exception if procedure fails\n */\n void apply(final AtmosphereFramework fwk, final Class clazz) throws Exception;\n }\n\n /**\n *

\n * Install the classes.\n *

\n *\n * @author Guillaume DROUET\n * @version 1.0\n * @since 2.2.0\n */\n private static class InstallMetaServiceProcedure implements MetaServiceProcedure {\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void apply(final AtmosphereFramework fwk, final Class c) throws Exception {\n if (AtmosphereInterceptor.class.isAssignableFrom(c)) {\n fwk.interceptor(fwk.newClassInstance(AtmosphereInterceptor.class, c));\n } else if (Broadcaster.class.isAssignableFrom(c)) {\n fwk.setDefaultBroadcasterClassName(c.getName());\n } else if (BroadcasterListener.class.isAssignableFrom(c)) {\n fwk.addBroadcasterListener(fwk.newClassInstance(BroadcasterListener.class, c));\n } else if (BroadcasterCache.class.isAssignableFrom(c)) {\n fwk.setBroadcasterCacheClassName(c.getName());\n } else if (BroadcastFilter.class.isAssignableFrom(c)) {\n fwk.broadcasterFilters.add(c.getName());\n } else if (BroadcasterCacheInspector.class.isAssignableFrom(c)) {\n fwk.inspectors.add(fwk.newClassInstance(BroadcasterCacheInspector.class, c));\n } else if (AsyncSupportListener.class.isAssignableFrom(c)) {\n fwk.asyncSupportListeners.add(fwk.newClassInstance(AsyncSupportListener.class, c));\n } else if (AsyncSupport.class.isAssignableFrom(c)) {\n fwk.setAsyncSupport(fwk.newClassInstance(AsyncSupport.class, c));\n } else if (BroadcasterCacheListener.class.isAssignableFrom(c)) {\n fwk.broadcasterCacheListeners.add(fwk.newClassInstance(BroadcasterCacheListener.class, c));\n } else if (BroadcasterConfig.FilterManipulator.class.isAssignableFrom(c)) {\n fwk.filterManipulators.add(fwk.newClassInstance(BroadcasterConfig.FilterManipulator.class, c));\n } else if (WebSocketProtocol.class.isAssignableFrom(c)) {\n fwk.webSocketProtocolClassName = c.getName();\n } else if (WebSocketProcessor.class.isAssignableFrom(c)) {\n fwk.webSocketProcessorClassName = c.getName();\n } else if (AtmosphereResourceFactory.class.isAssignableFrom(c)) {\n fwk.setAndConfigureAtmosphereResourceFactory(fwk.newClassInstance(AtmosphereResourceFactory.class, c));\n } else if (AtmosphereFrameworkListener.class.isAssignableFrom(c)) {\n fwk.frameworkListener(fwk.newClassInstance(AtmosphereFrameworkListener.class, c));\n } else if (WebSocketFactory.class.isAssignableFrom(c)) {\n fwk.webSocketFactory(fwk.newClassInstance(WebSocketFactory.class, c));\n } else if (AtmosphereFramework.class.isAssignableFrom(c)) {\n // No OPS\n } else if (EndpointMapper.class.isAssignableFrom(c)) {\n fwk.endPointMapper(fwk.newClassInstance(EndpointMapper.class, c));\n } else {\n logger.warn(\"{} is not a framework service that could be installed\", c.getName());\n }\n }\n }\n\n /**\n *

\n * Exclude the services.\n *

\n *\n * @author Guillaume DROUET\n * @version 1.0\n * @since 2.2.0\n */\n private static class ExcludeMetaServiceProcedure implements MetaServiceProcedure {\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void apply(final AtmosphereFramework fwk, final Class c) {\n if (AtmosphereInterceptor.class.isAssignableFrom(c)) {\n fwk.excludeInterceptor(c.getName());\n } else {\n logger.warn(\"{} is not a framework service that could be excluded, pull request is welcome ;-)\", c.getName());\n }\n }\n }\n }\n\n public static class DefaultAtmosphereObjectFactory implements AtmosphereObjectFactory {\n public String toString() {\n return \"DefaultAtmosphereObjectFactory\";\n }\n\n @Override\n public void configure(AtmosphereConfig config) {\n }\n\n @Override\n public U newClassInstance(Class classType,\n Class defaultType) throws InstantiationException, IllegalAccessException {\n return defaultType.newInstance();\n }\n\n @Override\n public AtmosphereObjectFactory allowInjectionOf(java.lang.Object o) {\n return this;\n }\n }\n\n /**\n * Create an AtmosphereFramework.\n */\n public AtmosphereFramework() {\n this(false, true);\n }\n\n /**\n * Create an AtmosphereFramework and initialize it via {@link AtmosphereFramework#init(javax.servlet.ServletConfig)}.\n */\n public AtmosphereFramework(ServletConfig sc) throws ServletException {\n this(false, true);\n // TODO: What?\n init(sc);\n }\n\n /**\n * Create an AtmosphereFramework.\n *\n * @param isFilter true if this instance is used as an {@link AtmosphereFilter}\n */\n public AtmosphereFramework(boolean isFilter, boolean autoDetectHandlers) {\n this.isFilter = isFilter;\n this.autoDetectHandlers = autoDetectHandlers;\n config = newAtmosphereConfig();\n }\n\n /**\n * Create an instance of {@link org.atmosphere.cpr.AtmosphereConfig}\n */\n protected AtmosphereConfig newAtmosphereConfig() {\n return new AtmosphereConfig(this);\n }\n\n /**\n * The order of addition is quite important here.\n */\n private void populateBroadcasterType() {\n broadcasterTypes.add(KAFKA_BROADCASTER);\n broadcasterTypes.add(HAZELCAST_BROADCASTER);\n broadcasterTypes.add(XMPP_BROADCASTER);\n broadcasterTypes.add(REDIS_BROADCASTER);\n broadcasterTypes.add(JGROUPS_BROADCASTER);\n broadcasterTypes.add(JMS_BROADCASTER);\n broadcasterTypes.add(RMI_BROADCASTER);\n broadcasterTypes.add(RABBITMQ_BROADCASTER);\n }\n\n /**\n * The order of addition is quite important here.\n */\n private void populateObjectFactoryType() {\n objectFactoryType.add(CDI_INJECTOR);\n objectFactoryType.add(SPRING_INJECTOR);\n objectFactoryType.add(GUICE_INJECTOR);\n }\n\n /**\n * Add an {@link AtmosphereHandler} serviced by the {@link Servlet}\n * This API is exposed to allow embedding an Atmosphere application.\n *\n * @param mapping The servlet mapping (servlet path)\n * @param h implementation of an {@link AtmosphereHandler}\n * @param l An array of {@link AtmosphereInterceptor}.\n */\n public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, List l) {\n if (!mapping.startsWith(\"/\")) {\n mapping = \"/\" + mapping;\n }\n createWrapperAndConfigureHandler(h, mapping, l);\n\n if (!isInit) {\n logger.info(\"Installed AtmosphereHandler {} mapped to context-path: {}\", h.getClass().getName(), mapping);\n logger.info(\"Installed the following AtmosphereInterceptor mapped to AtmosphereHandler {}\", h.getClass().getName());\n if (!l.isEmpty()) {\n for (AtmosphereInterceptor s : l) {\n logger.info(\"\\t{} : {}\", s.getClass().getName(), s);\n }\n }\n }\n return this;\n }\n\n /**\n * Add an {@link AtmosphereHandler} serviced by the {@link Servlet}.\n * This API is exposed to allow embedding an Atmosphere application.\n *\n * @param mapping The servlet mapping (servlet path)\n * @param h implementation of an {@link AtmosphereHandler}\n * @param broadcaster The {@link Broadcaster} associated with AtmosphereHandler\n * @param l A list of {@link AtmosphereInterceptor}s\n */\n public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, Broadcaster broadcaster, List l) {\n if (!mapping.startsWith(\"/\")) {\n mapping = \"/\" + mapping;\n }\n\n createWrapperAndConfigureHandler(h, mapping, l).broadcaster = broadcaster;\n\n if (!isInit) {\n logger.info(\"Installed AtmosphereHandler {} mapped to context-path {} and Broadcaster Class {}\", h.getClass().getName(), mapping, broadcaster.getClass().getName());\n } else {\n logger.debug(\"Installed AtmosphereHandler {} mapped to context-path {} and Broadcaster Class {}\",\n h.getClass().getName(), mapping, broadcaster.getClass().getName());\n }\n\n if (!l.isEmpty()) {\n logger.info(\"Installed AtmosphereInterceptor {} mapped to AtmosphereHandler {}\", l, h.getClass().getName());\n }\n return this;\n }\n\n\n /**\n * Add an {@link AtmosphereHandler} serviced by the {@link Servlet}.\n * This API is exposed to allow embedding an Atmosphere application.\n *\n * @param mapping The servlet mapping (servlet path)\n * @param h implementation of an {@link AtmosphereHandler}\n * @param broadcasterId The {@link Broadcaster#getID} value.\n * @param l A list of {@link AtmosphereInterceptor}\n */\n public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, String broadcasterId, List l) {\n if (!mapping.startsWith(\"/\")) {\n mapping = \"/\" + mapping;\n }\n\n createWrapperAndConfigureHandler(h, mapping, l).broadcaster.setID(broadcasterId);\n\n logger.info(\"Installed AtmosphereHandler {} mapped to context-path: {}\", h.getClass().getName(), mapping);\n if (!l.isEmpty()) {\n logger.info(\"Installed AtmosphereInterceptor {} mapped to AtmosphereHandler {}\", l, h.getClass().getName());\n }\n return this;\n }\n\n protected AtmosphereHandlerWrapper createWrapperAndConfigureHandler(AtmosphereHandler h, String mapping, List l) {\n AtmosphereHandlerWrapper w = new AtmosphereHandlerWrapper(broadcasterFactory, h, mapping, config);\n addMapping(mapping, w);\n addInterceptorToWrapper(w, l);\n initServletProcessor(h);\n return w;\n }\n\n /**\n * Add an {@link AtmosphereHandler} serviced by the {@link Servlet}\n * This API is exposed to allow embedding an Atmosphere application.\n *\n * @param mapping The servlet mapping (servlet path)\n * @param h implementation of an {@link AtmosphereHandler}\n */\n public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h) {\n addAtmosphereHandler(mapping, h, Collections.emptyList());\n return this;\n }\n\n private AtmosphereFramework addMapping(String path, AtmosphereHandlerWrapper w) {\n atmosphereHandlers.put(normalizePath(path), w);\n return this;\n }\n\n public String normalizePath(String path) {\n // We are using JAXRS mapping algorithm.\n if (path.contains(\"*\")) {\n path = path.replace(\"*\", mappingRegex);\n }\n\n if (path.endsWith(\"/\")) {\n path = path + mappingRegex;\n }\n return path;\n }\n\n\n /**\n * Add an {@link AtmosphereHandler} serviced by the {@link Servlet}.\n * This API is exposed to allow embedding an Atmosphere application.\n *\n * @param mapping The servlet mapping (servlet path)\n * @param h implementation of an {@link AtmosphereHandler}\n * @param broadcasterId The {@link Broadcaster#getID} value\n */\n public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, String broadcasterId) {\n addAtmosphereHandler(mapping, h, broadcasterId, Collections.emptyList());\n return this;\n }\n\n private void initServletProcessor(AtmosphereHandler h) {\n if (!isInit) return;\n\n try {\n if (h instanceof AtmosphereServletProcessor) {\n ((AtmosphereServletProcessor) h).init(config);\n }\n } catch (ServletException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Add an {@link AtmosphereHandler} serviced by the {@link Servlet}.\n * This API is exposed to allow embedding an Atmosphere application.\n *\n * @param mapping The servlet mapping (servlet path)\n * @param h implementation of an {@link AtmosphereHandler}\n * @param broadcaster The {@link Broadcaster} associated with AtmosphereHandler.\n */\n public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, Broadcaster broadcaster) {\n addAtmosphereHandler(mapping, h, broadcaster, Collections.emptyList());\n return this;\n }\n\n /**\n * Remove an {@link AtmosphereHandler}.\n *\n * @param mapping the mapping used when invoking {@link #addAtmosphereHandler(String, AtmosphereHandler)};\n * @return true if removed\n */\n public AtmosphereFramework removeAtmosphereHandler(String mapping) {\n\n if (mapping.endsWith(\"/\")) {\n mapping += mappingRegex;\n }\n\n atmosphereHandlers.remove(mapping);\n return this;\n }\n\n /**\n * Remove all {@link AtmosphereHandler}s.\n */\n public AtmosphereFramework removeAllAtmosphereHandler() {\n atmosphereHandlers.clear();\n return this;\n }\n\n /**\n * Remove all init parameters.\n */\n public AtmosphereFramework removeAllInitParams() {\n initParams.clear();\n return this;\n }\n\n /**\n * Add init-param like if they were defined in web.xml\n *\n * @param name The name\n * @param value The value\n */\n public AtmosphereFramework addInitParameter(String name, String value) {\n initParams.put(name, value);\n return this;\n }\n\n protected void readSystemProperties() {\n if (System.getProperty(PROPERTY_NATIVE_COMETSUPPORT) != null) {\n useNativeImplementation = Boolean\n .parseBoolean(System.getProperty(PROPERTY_NATIVE_COMETSUPPORT));\n isCometSupportSpecified = true;\n }\n\n if (System.getProperty(PROPERTY_BLOCKING_COMETSUPPORT) != null) {\n useBlockingImplementation = Boolean\n .parseBoolean(System.getProperty(PROPERTY_BLOCKING_COMETSUPPORT));\n isCometSupportSpecified = true;\n }\n atmosphereDotXmlPath = System.getProperty(PROPERTY_ATMOSPHERE_XML, atmosphereDotXmlPath);\n\n if (System.getProperty(DISABLE_ONSTATE_EVENT) != null) {\n initParams.put(DISABLE_ONSTATE_EVENT, System.getProperty(DISABLE_ONSTATE_EVENT));\n }\n }\n\n /**\n * Path specific container using their own property.\n */\n public void patchContainer() {\n System.setProperty(\"org.apache.catalina.STRICT_SERVLET_COMPLIANCE\", \"false\");\n }\n\n /**\n * Initialize the AtmosphereFramework. Invoke this method after having properly configured this class using the setters.\n */\n public AtmosphereFramework init() {\n try {\n init(servletConfig == null ? new VoidServletConfig(initParams) : servletConfig, false);\n } catch (ServletException e) {\n logger.error(\"\", e);\n }\n return this;\n }\n\n /**\n * Initialize the AtmosphereFramework using the {@link ServletContext}.\n *\n * @param sc the {@link ServletContext}\n */\n public AtmosphereFramework init(final ServletConfig sc) throws ServletException {\n return init(sc, true);\n }\n\n /**\n * Prevent Atmosphere from scanning the entire class path.\n */\n protected void preventOOM() {\n\n String s = config.getInitParameter(ApplicationConfig.SCAN_CLASSPATH);\n if (s != null) {\n allowAllClassesScan = Boolean.parseBoolean(s);\n }\n\n try {\n Class.forName(\"org.testng.Assert\");\n allowAllClassesScan = false;\n } catch (ClassNotFoundException e) {\n }\n }\n\n /**\n * Initialize the AtmosphereFramework using the {@link ServletContext}.\n *\n * @param sc the {@link ServletContext}\n */\n public AtmosphereFramework init(final ServletConfig sc, boolean wrap) throws ServletException {\n if (isInit) return this;\n\n servletConfig(sc, wrap);\n readSystemProperties();\n populateBroadcasterType();\n populateObjectFactoryType();\n loadMetaService();\n onPreInit();\n\n try {\n\n ServletContextFactory.getDefault().init(sc.getServletContext());\n\n preventOOM();\n doInitParams(servletConfig);\n doInitParamsForWebSocket(servletConfig);\n lookupDefaultObjectFactoryType();\n\n if (logger.isTraceEnabled()) {\n asyncSupportListener(newClassInstance(AsyncSupportListener.class, AsyncSupportListenerAdapter.class));\n }\n\n configureObjectFactory();\n configureAnnotationPackages();\n\n configureBroadcasterFactory();\n configureMetaBroadcaster();\n configureAtmosphereResourceFactory();\n if (isSessionSupportSpecified) {\n sessionFactory();\n }\n configureScanningPackage(servletConfig, ApplicationConfig.ANNOTATION_PACKAGE);\n configureScanningPackage(servletConfig, FrameworkConfig.JERSEY2_SCANNING_PACKAGE);\n configureScanningPackage(servletConfig, FrameworkConfig.JERSEY_SCANNING_PACKAGE);\n // Force scanning of the packages defined.\n defaultPackagesToScan();\n\n installAnnotationProcessor(servletConfig);\n\n autoConfigureService(servletConfig.getServletContext());\n\n // Reconfigure in case an annotation changed the default.\n configureBroadcasterFactory();\n patchContainer();\n configureBroadcaster();\n loadConfiguration(servletConfig);\n initWebSocket();\n initEndpointMapper();\n initDefaultSerializer();\n\n autoDetectContainer();\n configureWebDotXmlAtmosphereHandler(servletConfig);\n asyncSupport.init(servletConfig);\n initAtmosphereHandler(servletConfig);\n configureAtmosphereInterceptor(servletConfig);\n analytics();\n\n // http://java.net/jira/browse/ATMOSPHERE-157\n if (sc.getServletContext() != null) {\n sc.getServletContext().setAttribute(BroadcasterFactory.class.getName(), broadcasterFactory);\n }\n\n String s = config.getInitParameter(ApplicationConfig.BROADCASTER_SHARABLE_THREAD_POOLS);\n if (s != null) {\n sharedThreadPools = Boolean.parseBoolean(s);\n }\n\n this.shutdownHook = new Thread(AtmosphereFramework.this::destroy);\n\n Runtime.getRuntime().addShutdownHook(this.shutdownHook);\n\n if (logger.isInfoEnabled()) {\n info();\n }\n\n if (initializationError != null) {\n logger.trace(\"ContainerInitalizer exception. May not be an issue if Atmosphere started properly \", initializationError);\n }\n\n universe();\n } catch (Throwable t) {\n logger.error(\"Failed to initialize Atmosphere Framework\", t);\n\n if (t instanceof ServletException) {\n throw (ServletException) t;\n }\n\n throw new ServletException(t);\n }\n isInit = true;\n config.initComplete();\n\n // wlc 12.x\n if (WebLogicServlet30WithWebSocket.class.isAssignableFrom(asyncSupport.getClass())) {\n servletConfig.getServletContext().setAttribute(AtmosphereConfig.class.getName(), config);\n }\n\n onPostInit();\n\n return this;\n }\n\n protected void servletConfig(final ServletConfig sc, boolean wrap) {\n if (wrap) {\n\n String value = sc.getServletContext().getInitParameter(USE_SERVLET_CONTEXT_PARAMETERS);\n final boolean useServletContextParameters = Boolean.parseBoolean(value);\n\n servletConfig = new ServletConfig() {\n\n final AtomicBoolean done = new AtomicBoolean();\n\n public String getServletName() {\n return sc.getServletName();\n }\n\n public ServletContext getServletContext() {\n return sc.getServletContext();\n }\n\n public String getInitParameter(String name) {\n String param = initParams.get(name);\n if (param == null) {\n param = sc.getInitParameter(name);\n\n if (param == null && useServletContextParameters) {\n param = sc.getServletContext().getInitParameter(name);\n }\n }\n return param;\n }\n\n public Enumeration getInitParameterNames() {\n if (!done.getAndSet(true)) {\n Enumeration en = sc.getInitParameterNames();\n if (en != null) {\n while (en.hasMoreElements()) {\n String name = en.nextElement();\n if (!initParams.containsKey(name)) {\n initParams.put(name, sc.getInitParameter(name));\n }\n }\n }\n }\n return Collections.enumeration(initParams.keySet());\n }\n };\n } else {\n servletConfig = sc;\n }\n }\n\n public void reconfigureInitParams(boolean reconfigureInitParams) {\n if (reconfigureInitParams) {\n doInitParams(servletConfig, reconfigureInitParams);\n doInitParamsForWebSocket(servletConfig);\n }\n }\n\n private void info() {\n\n if (logger.isTraceEnabled()) {\n Enumeration e = servletConfig.getInitParameterNames();\n logger.trace(\"Configured init-params\");\n String n;\n while (e.hasMoreElements()) {\n n = e.nextElement();\n logger.trace(\"\\t{} = {}\", n, servletConfig.getInitParameter(n));\n }\n }\n\n logger.info(\"Using EndpointMapper {}\", endpointMapper.getClass());\n for (String i : broadcasterFilters) {\n logger.info(\"Using BroadcastFilter: {}\", i);\n }\n\n if (broadcasterCacheClassName == null || DefaultBroadcasterCache.class.getName().equals(broadcasterCacheClassName)) {\n logger.warn(\"No BroadcasterCache configured. Broadcasted message between client reconnection will be LOST. \" +\n \"It is recommended to configure the {}\", UUIDBroadcasterCache.class.getName());\n } else {\n logger.info(\"Using BroadcasterCache: {}\", broadcasterCacheClassName);\n }\n\n String s = config.getInitParameter(BROADCASTER_WAIT_TIME);\n\n logger.info(\"Default Broadcaster Class: {}\", broadcasterClassName);\n logger.info(\"Broadcaster Shared List Resources: {}\", config.getInitParameter(BROADCASTER_SHAREABLE_LISTENERS, false));\n logger.info(\"Broadcaster Polling Wait Time {}\", s == null ? DefaultBroadcaster.POLLING_DEFAULT : s);\n logger.info(\"Shared ExecutorService supported: {}\", sharedThreadPools);\n\n ExecutorService executorService = ExecutorsFactory.getMessageDispatcher(config, Broadcaster.ROOT_MASTER);\n if (executorService != null) {\n if (ThreadPoolExecutor.class.isAssignableFrom(executorService.getClass())) {\n long max = ((ThreadPoolExecutor) executorService).getMaximumPoolSize();\n logger.info(\"Messaging Thread Pool Size: {}\",\n ((ThreadPoolExecutor) executorService).getMaximumPoolSize() == 2147483647 ? \"Unlimited\" : max);\n } else {\n logger.info(\"Messaging ExecutorService Pool Size unavailable - Not instance of ThreadPoolExecutor\");\n }\n }\n\n executorService = ExecutorsFactory.getAsyncOperationExecutor(config, Broadcaster.ROOT_MASTER);\n if (executorService != null) {\n if (ThreadPoolExecutor.class.isAssignableFrom(executorService.getClass())) {\n logger.info(\"Async I/O Thread Pool Size: {}\",\n ((ThreadPoolExecutor) executorService).getMaximumPoolSize());\n } else {\n logger.info(\"Async I/O ExecutorService Pool Size unavailable - Not instance of ThreadPoolExecutor\");\n }\n }\n logger.info(\"Using BroadcasterFactory: {}\", broadcasterFactory.getClass().getName());\n logger.info(\"Using AtmosphereResurceFactory: {}\", arFactory.getClass().getName());\n logger.info(\"Using WebSocketProcessor: {}\", webSocketProcessorClassName);\n if (defaultSerializerClassName != null && !defaultSerializerClassName.isEmpty()) {\n logger.info(\"Using Serializer: {}\", defaultSerializerClassName);\n }\n\n WebSocketProcessor wp = WebSocketProcessorFactory.getDefault().getWebSocketProcessor(this);\n boolean b = false;\n if (DefaultWebSocketProcessor.class.isAssignableFrom(wp.getClass())) {\n b = ((DefaultWebSocketProcessor) wp).invokeInterceptors();\n }\n logger.info(\"Invoke AtmosphereInterceptor on WebSocket message {}\", b);\n logger.info(\"HttpSession supported: {}\", config.isSupportSession());\n\n logger.info(\"Atmosphere is using {} for dependency injection and object creation\", objectFactory);\n logger.info(\"Atmosphere is using async support: {} running under container: {}\",\n getAsyncSupport().getClass().getName(), asyncSupport.getContainerName());\n logger.info(\"Atmosphere Framework {} started.\", Version.getRawVersion());\n\n logger.info(\"\\n\\n\\tFor Atmosphere Framework Commercial Support, visit \\n\\t{} \" +\n \"or send an email to {}\\n\", \"http://www.async-io.org/\", \"support@async-io.org\");\n\n if (logger.isTraceEnabled()) {\n for (Entry e : atmosphereHandlers.entrySet()) {\n logger.trace(\"\\nConfigured AtmosphereHandler {}\\n\", e.getKey());\n logger.trace(\"{}\", e.getValue());\n }\n }\n }\n\n protected void universe() {\n Universe.broadcasterFactory(broadcasterFactory);\n Universe.resourceFactory(arFactory);\n Universe.sessionResourceFactory(sessionFactory);\n Universe.framework(this);\n }\n\n private void configureAnnotationPackages() {\n // We must scan the default annotation set.\n annotationPackages.add(Processor.class.getPackage().getName());\n\n String s = config.getInitParameter(ApplicationConfig.CUSTOM_ANNOTATION_PACKAGE);\n if (s != null) {\n String[] l = s.split(\",\");\n for (String p : l) {\n annotationPackages.addLast(p);\n }\n }\n }\n\n protected void analytics() {\n if (!config.getInitParameter(ApplicationConfig.ANALYTICS, true)) return;\n\n final String container = getServletContext().getServerInfo();\n Thread t = new Thread(() -> {\n try {\n logger.debug(\"Retrieving Atmosphere's latest version from http://async-io.org/version.html\");\n HttpURLConnection urlConnection = (HttpURLConnection)\n URI.create(\"http://async-io.org/version.html\").toURL().openConnection();\n urlConnection.setRequestProperty(\"User-Agent\", \"Mozilla/5.0\");\n urlConnection.setRequestProperty(\"Connection\", \"keep-alive\");\n urlConnection.setRequestProperty(\"Cache-Control\", \"max-age=0\");\n urlConnection.setRequestProperty(\"Accept\", \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\");\n urlConnection.setRequestProperty(\"Accept-Language\", \"en-US,en;q=0.8\");\n urlConnection.setRequestProperty(\"Accept-Charset\", \"ISO-8859-1,utf-8;q=0.7,*;q=0.3\");\n urlConnection.setRequestProperty(\"If-Modified-Since\", \"ISO-8859-1,utf-8;q=0.7,*;q=0.3\");\n urlConnection.setInstanceFollowRedirects(true);\n\n BufferedReader in = new BufferedReader(new InputStreamReader(\n urlConnection.getInputStream()));\n\n String inputLine;\n String newVersion = Version.getRawVersion();\n String clientVersion = null;\n String nextMajorRelease = null;\n boolean nextAvailable = false;\n if (!newVersion.contains(\"SNAPSHOT\")) {\n try {\n while ((inputLine = in.readLine().trim()) != null) {\n if (inputLine.startsWith(\"ATMO23_VERSION=\")) {\n newVersion = inputLine.substring(\"ATMO23_VERSION=\".length());\n } else if (inputLine.startsWith(\"CLIENT3_VERSION=\")) {\n clientVersion = inputLine.substring(\"CLIENT3_VERSION=\".length());\n break;\n } else if (inputLine.startsWith(\"ATMO_RELEASE_VERSION=\")) {\n nextMajorRelease = inputLine.substring(\"ATMO_RELEASE_VERSION=\".length());\n if (nextMajorRelease.compareTo(Version.getRawVersion()) > 0\n && !nextMajorRelease.toLowerCase().contains(\"rc\")\n && !nextMajorRelease.toLowerCase().contains(\"beta\")) {\n nextAvailable = true;\n }\n }\n }\n } finally {\n if (clientVersion != null) {\n logger.info(\"Latest version of Atmosphere's JavaScript Client {}\", clientVersion);\n }\n if (newVersion.compareTo(Version.getRawVersion()) > 0) {\n if (nextAvailable) {\n logger.info(\"\\n\\n\\tAtmosphere Framework Updates\\n\\tMinor available (bugs fixes): {}\\n\\tMajor available (new features): {}\", newVersion, nextMajorRelease);\n } else {\n logger.info(\"\\n\\n\\tAtmosphere Framework Updates:\\n\\tMinor Update available (bugs fixes): {}\", newVersion);\n }\n } else if (nextAvailable) {\n logger.info(\"\\n\\n\\tAtmosphere Framework Updates:\\n\\tMajor Update available (new features): {}\", nextMajorRelease);\n }\n try {\n in.close();\n } catch (IOException ex) {\n }\n urlConnection.disconnect();\n }\n }\n\n JGoogleAnalyticsTracker tracker = new JGoogleAnalyticsTracker(ModuleDetection.detect(), Version.getRawVersion(), \"UA-31990725-1\");\n tracker.trackSynchronously(new FocusPoint(container, new FocusPoint(\"Atmosphere\")));\n\n } catch (Throwable e) {\n }\n });\n t.setDaemon(true);\n t.start();\n }\n\n /**\n * Configure the list of {@link AtmosphereInterceptor}.\n *\n * @param sc a ServletConfig\n */\n protected void configureAtmosphereInterceptor(ServletConfig sc) {\n String s = sc.getInitParameter(ApplicationConfig.ATMOSPHERE_INTERCEPTORS);\n if (s != null) {\n String[] list = s.split(\",\");\n for (String a : list) {\n try {\n AtmosphereInterceptor ai = newClassInstance(AtmosphereInterceptor.class,\n (Class) IOUtils.loadClass(getClass(), a.trim()));\n interceptor(ai);\n } catch (Exception e) {\n logger.warn(\"\", e);\n }\n }\n }\n\n s = sc.getInitParameter(ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTOR);\n if (!Boolean.parseBoolean(s)) {\n logger.info(\"Installing Default AtmosphereInterceptors\");\n\n for (Class a : DEFAULT_ATMOSPHERE_INTERCEPTORS) {\n if (!excludedInterceptors.contains(a.getName())) {\n interceptors.add(newAInterceptor(a));\n } else {\n logger.info(\"Dropping Interceptor {}\", a.getName());\n }\n }\n logger.info(\"Set {} to disable them.\", ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTOR);\n }\n addDefaultOrAppInterceptors();\n }\n\n protected AtmosphereInterceptor newAInterceptor(Class a) {\n AtmosphereInterceptor ai = null;\n try {\n ai = newClassInstance(AtmosphereInterceptor.class,\n (Class) IOUtils.loadClass(getClass(), a.getName()));\n logger.info(\"\\t{} : {}\", a.getName(), ai);\n } catch (Exception ex) {\n logger.warn(\"\", ex);\n }\n return ai;\n }\n\n private static class InterceptorComparator implements Comparator {\n @Override\n public int compare(AtmosphereInterceptor i1, AtmosphereInterceptor i2) {\n InvokationOrder.PRIORITY p1, p2;\n\n if (i1 instanceof InvokationOrder) {\n p1 = ((InvokationOrder) i1).priority();\n } else {\n p1 = InvokationOrder.PRIORITY.AFTER_DEFAULT;\n }\n\n if (i2 instanceof InvokationOrder) {\n p2 = ((InvokationOrder) i2).priority();\n } else {\n p2 = InvokationOrder.PRIORITY.AFTER_DEFAULT;\n }\n\n int orderResult = 0;\n\n switch (p1) {\n case AFTER_DEFAULT:\n switch (p2) {\n case BEFORE_DEFAULT:\n case FIRST_BEFORE_DEFAULT:\n orderResult = 1;\n break;\n }\n break;\n\n case BEFORE_DEFAULT:\n switch (p2) {\n case AFTER_DEFAULT:\n orderResult = -1;\n break;\n case FIRST_BEFORE_DEFAULT:\n orderResult = 1;\n break;\n }\n break;\n\n case FIRST_BEFORE_DEFAULT:\n switch (p2) {\n case AFTER_DEFAULT:\n case BEFORE_DEFAULT:\n orderResult = -1;\n break;\n }\n break;\n }\n\n return orderResult;\n }\n }\n\n protected void configureWebDotXmlAtmosphereHandler(ServletConfig sc) {\n String s = sc.getInitParameter(ATMOSPHERE_HANDLER);\n if (s != null) {\n try {\n\n String mapping = sc.getInitParameter(ATMOSPHERE_HANDLER_MAPPING);\n if (mapping == null) {\n mapping = Broadcaster.ROOT_MASTER;\n }\n addAtmosphereHandler(mapping, newClassInstance(AtmosphereHandler.class,\n (Class) IOUtils.loadClass(getClass(), s)));\n } catch (Exception ex) {\n logger.warn(\"Unable to load WebSocketHandle instance\", ex);\n }\n }\n }\n\n protected void configureScanningPackage(ServletConfig sc, String value) {\n String packageName = sc.getInitParameter(value);\n if (packageName != null) {\n String[] list = packageName.split(\",\");\n Collections.addAll(packages, list);\n }\n }\n\n protected void defaultPackagesToScan() {\n // Atmosphere HA/Pro\n packages.add(\"io.async.control\");\n packages.add(\"io.async.satellite\");\n packages.add(\"io.async.postman\");\n }\n\n public void configureBroadcasterFactory() {\n try {\n // Check auto supported one\n if (!isBroadcasterSpecified) {\n broadcasterClassName = lookupDefaultBroadcasterType(broadcasterClassName);\n }\n\n if (broadcasterFactoryClassName != null && broadcasterFactory == null) {\n broadcasterFactory = newClassInstance(BroadcasterFactory.class,\n (Class) IOUtils.loadClass(getClass(), broadcasterFactoryClassName));\n Class bc =\n (Class) IOUtils.loadClass(getClass(), broadcasterClassName);\n broadcasterFactory.configure(bc, broadcasterLifeCyclePolicy, config);\n }\n\n if (broadcasterFactory == null) {\n Class bc =\n (Class) IOUtils.loadClass(getClass(), broadcasterClassName);\n broadcasterFactory = newClassInstance(BroadcasterFactory.class, DefaultBroadcasterFactory.class);\n broadcasterFactory.configure(bc, broadcasterLifeCyclePolicy, config);\n }\n\n for (BroadcasterListener b : broadcasterListeners) {\n broadcasterFactory.addBroadcasterListener(b);\n }\n } catch (Exception ex) {\n logger.error(\"Unable to configure Broadcaster/Factory/Cache\", ex);\n }\n }\n\n protected void configureBroadcaster() {\n\n try {\n Iterator> i = atmosphereHandlers.entrySet().iterator();\n AtmosphereHandlerWrapper w;\n Entry e;\n while (i.hasNext()) {\n e = i.next();\n w = e.getValue();\n\n if (w.broadcaster == null) {\n w.broadcaster = broadcasterFactory.get(w.mapping);\n } else {\n if (broadcasterCacheClassName != null\n && w.broadcaster.getBroadcasterConfig().getBroadcasterCache().getClass().getName().equals(\n DefaultBroadcasterCache.class.getName())) {\n BroadcasterCache cache = newClassInstance(BroadcasterCache.class,\n (Class) IOUtils.loadClass(getClass(), broadcasterCacheClassName));\n cache.configure(config);\n w.broadcaster.getBroadcasterConfig().setBroadcasterCache(cache);\n }\n }\n }\n } catch (Exception ex) {\n logger.error(\"Unable to configure Broadcaster/Factory/Cache\", ex);\n }\n }\n\n protected void installAnnotationProcessor(ServletConfig sc) {\n String s = sc.getInitParameter(ApplicationConfig.ANNOTATION_PROCESSOR);\n if (s != null) {\n annotationProcessorClassName = s;\n }\n }\n\n protected void doInitParamsForWebSocket(ServletConfig sc) {\n String s = sc.getInitParameter(WEBSOCKET_SUPPORT);\n if (s != null) {\n webSocketEnabled = Boolean.parseBoolean(s);\n sessionSupport(false);\n }\n s = sc.getInitParameter(WEBSOCKET_PROTOCOL);\n if (s != null) {\n webSocketProtocolClassName = s;\n }\n\n s = sc.getInitParameter(WEBSOCKET_PROCESSOR);\n if (s != null) {\n webSocketProcessorClassName = s;\n }\n\n s = config.getInitParameter(ApplicationConfig.WEBSOCKET_SUPPORT_SERVLET3);\n if (s != null) {\n useServlet30 = Boolean.parseBoolean(s);\n }\n }\n\n /**\n * Read init params from web.xml and apply them.\n *\n * @param sc {@link ServletConfig}\n */\n protected void doInitParams(ServletConfig sc) {\n doInitParams(sc, false);\n }\n\n /**\n * Read init params from web.xml and apply them.\n *\n * @param sc {@link ServletConfig}\n */\n protected void doInitParams(ServletConfig sc, boolean reconfigure) {\n String s = sc.getInitParameter(PROPERTY_NATIVE_COMETSUPPORT);\n if (s != null) {\n useNativeImplementation = Boolean.parseBoolean(s);\n if (useNativeImplementation) isCometSupportSpecified = true;\n }\n s = sc.getInitParameter(PROPERTY_BLOCKING_COMETSUPPORT);\n if (s != null) {\n useBlockingImplementation = Boolean.parseBoolean(s);\n if (useBlockingImplementation) isCometSupportSpecified = true;\n }\n s = sc.getInitParameter(PROPERTY_USE_STREAM);\n if (s != null) {\n useStreamForFlushingComments = Boolean.parseBoolean(s);\n }\n s = sc.getInitParameter(PROPERTY_COMET_SUPPORT);\n if (asyncSupport == null && s != null && !reconfigure) {\n asyncSupport = new DefaultAsyncSupportResolver(config).newCometSupport(s);\n isCometSupportSpecified = true;\n }\n s = sc.getInitParameter(BROADCASTER_CLASS);\n if (s != null) {\n broadcasterClassName = s;\n isBroadcasterSpecified = true;\n }\n s = sc.getInitParameter(BROADCASTER_CACHE);\n if (s != null) {\n broadcasterCacheClassName = s;\n }\n\n s = sc.getInitParameter(PROPERTY_SESSION_SUPPORT);\n if (s == null) {\n s = sc.getServletContext().getInitParameter(PROPERTY_SESSION_SUPPORT);\n }\n\n if (s != null || SessionSupport.initializationHint) {\n boolean sessionSupport = Boolean.parseBoolean(s) || SessionSupport.initializationHint;\n config.setSupportSession(sessionSupport);\n if (sessionSupport && (sc.getServletContext().getMajorVersion() < 3 || !SessionSupport.initializationHint)) {\n logger.warn(\"SessionSupport error. Make sure you also define {} as a listener in web.xml, see https://github.com/Atmosphere/atmosphere/wiki/Enabling-HttpSession-Support\", SessionSupport.class.getName());\n }\n isSessionSupportSpecified = true;\n }\n s = sc.getInitParameter(PROPERTY_ALLOW_SESSION_TIMEOUT_REMOVAL);\n if (s != null) {\n config.setSessionTimeoutRemovalAllowed(Boolean.parseBoolean(s));\n }\n s = sc.getInitParameter(PROPERTY_THROW_EXCEPTION_ON_CLONED_REQUEST);\n if (s != null) {\n config.setThrowExceptionOnCloned(Boolean.parseBoolean(s));\n isThrowExceptionOnClonedRequestSpecified = true;\n }\n s = sc.getInitParameter(DISABLE_ONSTATE_EVENT);\n if (s != null) {\n initParams.put(DISABLE_ONSTATE_EVENT, s);\n } else {\n initParams.put(DISABLE_ONSTATE_EVENT, \"false\");\n }\n s = sc.getInitParameter(BROADCAST_FILTER_CLASSES);\n if (s != null) {\n broadcasterFilters.addAll(Arrays.asList(s.split(\",\")));\n logger.info(\"Installing BroadcastFilter class(es) {}\", s);\n }\n s = sc.getInitParameter(BROADCASTER_LIFECYCLE_POLICY);\n if (s != null) {\n broadcasterLifeCyclePolicy = s;\n }\n s = sc.getInitParameter(BROADCASTER_FACTORY);\n if (s != null) {\n broadcasterFactoryClassName = s;\n }\n s = sc.getInitParameter(ATMOSPHERE_HANDLER_PATH);\n if (s != null) {\n handlersPath = s;\n }\n s = sc.getInitParameter(PROPERTY_ATMOSPHERE_XML);\n if (s != null) {\n atmosphereDotXmlPath = s;\n }\n s = sc.getInitParameter(META_SERVICE_PATH);\n if (s != null) {\n metaServicePath = s;\n }\n s = sc.getInitParameter(ApplicationConfig.HANDLER_MAPPING_REGEX);\n if (s != null) {\n mappingRegex = s;\n }\n\n s = sc.getInitParameter(FrameworkConfig.JERSEY_SCANNING_PACKAGE);\n if (s != null) {\n packages.add(s);\n }\n\n s = sc.getInitParameter(ApplicationConfig.DEFAULT_SERIALIZER);\n if (s != null) {\n defaultSerializerClassName = s;\n }\n\n s = sc.getInitParameter(ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTORS);\n if (s != null) {\n excludedInterceptors.addAll(Arrays.asList(s.trim().replace(\" \", \"\").split(\",\")));\n }\n }\n\n public void loadConfiguration(ServletConfig sc) throws ServletException {\n\n if (!autoDetectHandlers) return;\n\n try {\n URL url = sc.getServletContext().getResource(handlersPath);\n ClassLoader urlC = url == null ? getClass().getClassLoader() : new URLClassLoader(new URL[]{url},\n Thread.currentThread().getContextClassLoader());\n loadAtmosphereDotXml(sc.getServletContext().\n getResourceAsStream(atmosphereDotXmlPath), urlC);\n\n if (atmosphereHandlers.isEmpty()) {\n autoDetectAtmosphereHandlers(sc.getServletContext(), urlC);\n\n if (atmosphereHandlers.isEmpty()) {\n detectSupportedFramework(sc);\n }\n }\n\n autoDetectWebSocketHandler(sc.getServletContext(), urlC);\n } catch (Throwable t) {\n throw new ServletException(t);\n }\n }\n\n /**\n * Auto-detect Jersey when no atmosphere.xml file is specified.\n *\n * @param sc {@link ServletConfig}\n * @return true if Jersey classes are detected\n * @throws ClassNotFoundException\n */\n protected boolean detectSupportedFramework(ServletConfig sc) throws Exception {\n\n String broadcasterClassNameTmp = null;\n\n boolean isJersey;\n try {\n IOUtils.loadClass(getClass(), JERSEY_CONTAINER);\n isJersey = true;\n\n if (!isBroadcasterSpecified) {\n broadcasterClassNameTmp = lookupDefaultBroadcasterType(JERSEY_BROADCASTER);\n\n IOUtils.loadClass(getClass(), broadcasterClassNameTmp);\n }\n useStreamForFlushingComments = true;\n\n StringBuilder packagesInit = new StringBuilder();\n for (String s : packages) {\n packagesInit.append(s).append(\",\");\n }\n\n initParams.put(FrameworkConfig.JERSEY_SCANNING_PACKAGE, packagesInit.toString());\n } catch (Throwable t) {\n logger.trace(\"\", t);\n return false;\n }\n\n logger.debug(\"Missing META-INF/atmosphere.xml but found the Jersey runtime. Starting Jersey\");\n\n // Atmosphere 1.1 : could add regressions\n // Jersey will itself handle the headers.\n //initParams.put(WRITE_HEADERS, \"false\");\n\n ReflectorServletProcessor rsp = newClassInstance(ReflectorServletProcessor.class, ReflectorServletProcessor.class);\n if (broadcasterClassNameTmp != null) broadcasterClassName = broadcasterClassNameTmp;\n configureDetectedFramework(rsp, isJersey);\n sessionSupport(false);\n initParams.put(DISABLE_ONSTATE_EVENT, \"true\");\n\n String mapping = sc.getInitParameter(PROPERTY_SERVLET_MAPPING);\n if (mapping == null) {\n mapping = sc.getInitParameter(ATMOSPHERE_HANDLER_MAPPING);\n if (mapping == null) {\n mapping = Broadcaster.ROOT_MASTER;\n }\n }\n Class bc = (Class) IOUtils.loadClass(getClass(), broadcasterClassName);\n\n broadcasterFactory.destroy();\n\n broadcasterFactory = newClassInstance(BroadcasterFactory.class, DefaultBroadcasterFactory.class);\n broadcasterFactory.configure(bc, broadcasterLifeCyclePolicy, config);\n for (BroadcasterListener b : broadcasterListeners) {\n broadcasterFactory.addBroadcasterListener(b);\n }\n\n Broadcaster b;\n\n try {\n b = broadcasterFactory.get(bc, mapping);\n } catch (IllegalStateException ex) {\n logger.warn(\"Two Broadcaster's named {}. Renaming the second one to {}\", mapping, sc.getServletName() + mapping);\n b = broadcasterFactory.get(bc, sc.getServletName() + mapping);\n }\n\n addAtmosphereHandler(mapping, rsp, b);\n return true;\n }\n\n protected void configureDetectedFramework(ReflectorServletProcessor rsp, boolean isJersey) {\n rsp.setServletClassName(JERSEY_CONTAINER);\n }\n\n protected String lookupDefaultBroadcasterType(String defaultB) {\n if (autodetectBroadcaster()) {\n for (String b : broadcasterTypes) {\n try {\n Class.forName(b);\n logger.info(\"Detected a Broadcaster {} on the classpath. \" +\n \"This broadcaster will be used by default and will override any annotated resources. \" +\n \"Set {} to false to change the behavior\", b, ApplicationConfig.AUTODETECT_BROADCASTER);\n isBroadcasterSpecified = true;\n return b;\n } catch (ClassNotFoundException e) {\n }\n }\n }\n\n return defaultB;\n }\n\n boolean autodetectBroadcaster() {\n if (servletConfig == null) {\n return true;\n }\n\n String autodetect = servletConfig.getInitParameter(ApplicationConfig.AUTODETECT_BROADCASTER);\n return autodetect == null || Boolean.parseBoolean(autodetect);\n }\n\n protected AtmosphereObjectFactory lookupDefaultObjectFactoryType() {\n\n if (objectFactory != null && !DefaultAtmosphereObjectFactory.class.getName().equals(objectFactory.getClass()\n .getName())) return objectFactory;\n\n for (String b : objectFactoryType) {\n try {\n Class c = Class.forName(b);\n objectFactory = (AtmosphereObjectFactory) c.newInstance();\n break;\n } catch (ClassNotFoundException e) {\n logger.trace(e.getMessage() + \" not found\");\n } catch (Exception e) {\n logger.trace(\"\", e);\n }\n }\n\n if (objectFactory == null || DefaultAtmosphereObjectFactory.class.getName().equals(objectFactory.getClass()\n .getName())) {\n try {\n IOUtils.loadClass(getClass(), INJECT_LIBARY);\n objectFactory = new InjectableObjectFactory();\n } catch (Exception e) {\n logger.trace(\"javax.inject.Inject nor installed. Using DefaultAtmosphereObjectFactory\");\n objectFactory = new DefaultAtmosphereObjectFactory();\n }\n }\n\n objectFactory.configure(config);\n return objectFactory;\n }\n\n public void sessionSupport(boolean sessionSupport) {\n if (!isSessionSupportSpecified) {\n config.setSupportSession(sessionSupport);\n } else if (!config.isSupportSession()) {\n // Don't turn off session support. Once it's on, leave it on.\n config.setSupportSession(sessionSupport);\n }\n }\n\n /**\n * Initialize {@link AtmosphereServletProcessor}.\n *\n * @param sc the {@link ServletConfig}\n * @throws javax.servlet.ServletException\n * @Deprecated\n */\n public void initAtmosphereHandler(ServletConfig sc) throws ServletException {\n initAtmosphereHandler();\n }\n\n public void initAtmosphereHandler() throws ServletException {\n\n AtmosphereHandler a;\n AtmosphereHandlerWrapper w;\n for (Entry h : atmosphereHandlers.entrySet()) {\n w = h.getValue();\n a = w.atmosphereHandler;\n if (a instanceof AtmosphereServletProcessor) {\n ((AtmosphereServletProcessor) a).init(config);\n }\n }\n checkWebSocketSupportState();\n }\n\n public void checkWebSocketSupportState() {\n if (atmosphereHandlers.isEmpty() && !SimpleHttpProtocol.class.isAssignableFrom(webSocketProtocol.getClass())) {\n logger.debug(\"Adding a void AtmosphereHandler mapped to /* to allow WebSocket application only\");\n addAtmosphereHandler(Broadcaster.ROOT_MASTER, new AbstractReflectorAtmosphereHandler() {\n @Override\n public void onRequest(AtmosphereResource r) throws IOException {\n logger.debug(\"No AtmosphereHandler defined.\");\n if (!r.transport().equals(AtmosphereResource.TRANSPORT.WEBSOCKET)) {\n WebSocket.notSupported(r.getRequest(), r.getResponse());\n }\n }\n\n @Override\n public void destroy() {\n }\n });\n }\n }\n\n public void initWebSocket() {\n if (webSocketProtocolInitialized) return;\n\n if (webSocketProtocol == null) {\n try {\n webSocketProtocol = newClassInstance(WebSocketProtocol.class,\n (Class) IOUtils.loadClass(this.getClass(), webSocketProtocolClassName));\n logger.info(\"Installed WebSocketProtocol {} \", webSocketProtocolClassName);\n } catch (Exception ex) {\n logger.error(\"Cannot load the WebSocketProtocol {}\", getWebSocketProtocolClassName(), ex);\n try {\n webSocketProtocol = newClassInstance(WebSocketProtocol.class, SimpleHttpProtocol.class);\n } catch (Exception e) {\n }\n }\n }\n webSocketProtocolInitialized = true;\n webSocketProtocol.configure(config);\n }\n\n public void initEndpointMapper() {\n String s = servletConfig.getInitParameter(ApplicationConfig.ENDPOINT_MAPPER);\n if (s != null) {\n try {\n endpointMapper = newClassInstance(EndpointMapper.class, (Class) IOUtils.loadClass(this.getClass(), s));\n logger.info(\"Installed EndpointMapper {} \", s);\n } catch (Exception ex) {\n logger.error(\"Cannot load the EndpointMapper {}\", s, ex);\n }\n }\n endpointMapper.configure(config);\n }\n\n protected void closeAtmosphereResource() {\n for (AtmosphereResource r : config.resourcesFactory().findAll()) {\n try {\n r.resume().close();\n } catch (Exception e) {\n logger.trace(\"\", e);\n }\n }\n }\n\n public AtmosphereFramework destroy() {\n\n if (isDestroyed.getAndSet(true)) return this;\n\n onPreDestroy();\n\n closeAtmosphereResource();\n destroyInterceptors();\n\n // Invoke ShutdownHook.\n config.destroy();\n\n BroadcasterFactory factory = broadcasterFactory;\n if (factory != null) {\n factory.destroy();\n }\n\n if (asyncSupport != null && AsynchronousProcessor.class.isAssignableFrom(asyncSupport.getClass())) {\n ((AsynchronousProcessor) asyncSupport).shutdown();\n }\n\n // We just need one bc to shutdown the shared thread pool\n for (Entry entry : atmosphereHandlers.entrySet()) {\n AtmosphereHandlerWrapper handlerWrapper = entry.getValue();\n try {\n handlerWrapper.atmosphereHandler.destroy();\n } catch (Throwable t) {\n logger.warn(\"\", t);\n }\n }\n\n if (metaBroadcaster != null) metaBroadcaster.destroy();\n if (arFactory != null) arFactory.destroy();\n if (sessionFactory != null) sessionFactory.destroy();\n\n WebSocketProcessorFactory.getDefault().destroy();\n\n ExecutorsFactory.reset(config);\n\n resetStates();\n\n onPostDestroy();\n\n try {\n if (this.shutdownHook != null) {\n Runtime.getRuntime().removeShutdownHook(this.shutdownHook);\n shutdownHook = null;\n }\n } catch (IllegalStateException ex) {\n logger.trace(\"\", ex);\n }\n\n config.properties().clear();\n return this;\n }\n\n protected void destroyInterceptors() {\n for (AtmosphereHandlerWrapper w : atmosphereHandlers.values()) {\n for (AtmosphereInterceptor i : w.interceptors) {\n try {\n i.destroy();\n } catch (Throwable ex) {\n logger.warn(\"\", ex);\n }\n }\n }\n }\n\n public AtmosphereFramework resetStates() {\n isInit = false;\n executeFirstSet = false;\n\n broadcasterFilters.clear();\n asyncSupportListeners.clear();\n possibleComponentsCandidate.clear();\n initParams.clear();\n atmosphereHandlers.clear();\n broadcasterTypes.clear();\n objectFactoryType.clear();\n inspectors.clear();\n broadcasterListeners.clear();\n packages.clear();\n annotationPackages.clear();\n excludedInterceptors.clear();\n broadcasterCacheListeners.clear();\n filterManipulators.clear();\n interceptors.clear();\n\n broadcasterFactory = null;\n arFactory = null;\n metaBroadcaster = null;\n sessionFactory = null;\n annotationFound = false;\n return this;\n }\n\n protected void loadMetaService() {\n try {\n Map config = (Map) servletConfig.getServletContext().getAttribute(AtmosphereFramework.MetaServiceAction.class.getName());\n if (config == null) {\n config = IOUtils.readServiceFile(metaServicePath + AtmosphereFramework.class.getName());\n }\n\n for (final Map.Entry action : config.entrySet()) {\n try {\n final Class c = IOUtils.loadClass(AtmosphereFramework.class, action.getKey());\n action.getValue().apply(this, c);\n } catch (ClassNotFoundException ex) {\n if (action.getKey().startsWith(ASYNC_IO)) {\n logger.trace(\"Unable to load class {}\", ex.getMessage());\n } else {\n logger.warn(\"\", ex);\n }\n }\n }\n } catch (Exception ex) {\n logger.warn(\"\", ex);\n }\n }\n\n /**\n * Load AtmosphereHandler defined under META-INF/atmosphere.xml.\n *\n * @param stream The input stream we read from.\n * @param c The classloader\n */\n protected void loadAtmosphereDotXml(InputStream stream, ClassLoader c)\n throws IOException, ServletException {\n\n if (stream == null) {\n return;\n }\n\n logger.info(\"Found Atmosphere Configuration under {}\", atmosphereDotXmlPath);\n AtmosphereConfigReader.getInstance().parse(config, stream);\n AtmosphereHandler handler = null;\n for (AtmosphereHandlerConfig atmoHandler : config.getAtmosphereHandlerConfig()) {\n try {\n if (!atmoHandler.getClassName().startsWith(\"@\")) {\n if (!ReflectorServletProcessor.class.getName().equals(atmoHandler.getClassName())) {\n handler = newClassInstance(AtmosphereHandler.class,\n (Class) IOUtils.loadClass(this.getClass(), atmoHandler.getClassName()));\n } else {\n handler = newClassInstance(AtmosphereHandler.class, ReflectorServletProcessor.class);\n }\n logger.info(\"Installed AtmosphereHandler {} mapped to context-path: {}\", handler, atmoHandler.getContextRoot());\n }\n\n for (ApplicationConfiguration a : atmoHandler.getApplicationConfig()) {\n initParams.put(a.getParamName(), a.getParamValue());\n }\n\n for (FrameworkConfiguration a : atmoHandler.getFrameworkConfig()) {\n initParams.put(a.getParamName(), a.getParamValue());\n }\n\n for (AtmosphereHandlerProperty handlerProperty : atmoHandler.getProperties()) {\n\n if (handlerProperty.getValue() != null && handlerProperty.getValue().contains(\"jersey\")) {\n initParams.put(DISABLE_ONSTATE_EVENT, \"true\");\n useStreamForFlushingComments = true;\n broadcasterClassName = lookupDefaultBroadcasterType(JERSEY_BROADCASTER);\n broadcasterFactory.destroy();\n broadcasterFactory = null;\n configureBroadcasterFactory();\n configureBroadcaster();\n }\n\n if (handler != null) {\n IntrospectionUtils.setProperty(handler, handlerProperty.getName(), handlerProperty.getValue());\n IntrospectionUtils.addProperty(handler, handlerProperty.getName(), handlerProperty.getValue());\n }\n }\n\n sessionSupport(Boolean.parseBoolean(atmoHandler.getSupportSession()));\n\n if (handler != null) {\n String broadcasterClass = atmoHandler.getBroadcaster();\n Broadcaster b;\n /*\n * If there is more than one AtmosphereHandler defined, their Broadcaster\n * may clash each other with the BroadcasterFactory. In that case we will use the\n * last one defined.\n */\n if (broadcasterClass != null) {\n broadcasterClassName = broadcasterClass;\n ClassLoader cl = Thread.currentThread().getContextClassLoader();\n Class bc = (Class) cl.loadClass(broadcasterClassName);\n broadcasterFactory = newClassInstance(BroadcasterFactory.class, DefaultBroadcasterFactory.class);\n broadcasterFactory.configure(bc, broadcasterLifeCyclePolicy, config);\n }\n\n b = broadcasterFactory.lookup(atmoHandler.getContextRoot(), true);\n\n AtmosphereHandlerWrapper wrapper = new AtmosphereHandlerWrapper(handler, b, config);\n addMapping(atmoHandler.getContextRoot(), wrapper);\n\n String bc = atmoHandler.getBroadcasterCache();\n if (bc != null) {\n broadcasterCacheClassName = bc;\n }\n\n if (atmoHandler.getCometSupport() != null) {\n asyncSupport = (AsyncSupport) c.loadClass(atmoHandler.getCometSupport())\n .getDeclaredConstructor(new Class[]{AtmosphereConfig.class})\n .newInstance(new Object[]{config});\n }\n\n if (atmoHandler.getBroadcastFilterClasses() != null) {\n broadcasterFilters.addAll(atmoHandler.getBroadcastFilterClasses());\n }\n\n LinkedList l = new LinkedList();\n if (atmoHandler.getAtmosphereInterceptorClasses() != null) {\n for (String a : atmoHandler.getAtmosphereInterceptorClasses()) {\n try {\n AtmosphereInterceptor ai = newClassInstance(AtmosphereInterceptor.class,\n (Class) IOUtils.loadClass(getClass(), a));\n l.add(ai);\n } catch (Throwable e) {\n logger.warn(\"\", e);\n }\n }\n }\n addInterceptorToWrapper(wrapper, l);\n\n if (!l.isEmpty()) {\n logger.info(\"Installed AtmosphereInterceptor {} mapped to AtmosphereHandler {}\", l, atmoHandler.getClassName());\n }\n }\n } catch (Throwable t) {\n logger.warn(\"Unable to load AtmosphereHandler class: \" + atmoHandler.getClassName(), t);\n throw new ServletException(t);\n }\n\n }\n }\n\n /**\n * Set the {@link AsyncSupport} implementation. Make sure you don't set an implementation that only works on\n * some container. See {@link BlockingIOCometSupport} for an example.\n *\n * @param asyncSupport\n */\n public AtmosphereFramework setAsyncSupport(AsyncSupport asyncSupport) {\n this.asyncSupport = asyncSupport;\n return this;\n }\n\n /**\n * @param asyncSupport\n * @return\n * @Deprecated - Use {@link #setAsyncSupport(AsyncSupport)}\n */\n public AtmosphereFramework setCometSupport(AsyncSupport asyncSupport) {\n return setAsyncSupport(asyncSupport);\n }\n\n /**\n * Return the current {@link AsyncSupport}.\n *\n * @return the current {@link AsyncSupport}\n */\n public AsyncSupport getAsyncSupport() {\n return asyncSupport;\n }\n\n /**\n * Return the current {@link AsyncSupport}.\n *\n * @return the current {@link AsyncSupport}\n * @deprecated Use getAsyncSupport\n */\n public AsyncSupport getCometSupport() {\n return asyncSupport;\n }\n\n /**\n * Returns an instance of AsyncSupportResolver {@link AsyncSupportResolver}.\n *\n * @return CometSupportResolver\n */\n protected AsyncSupportResolver createAsyncSupportResolver() {\n return new DefaultAsyncSupportResolver(config);\n }\n\n\n /**\n * Auto detect the underlying Servlet Container we are running on.\n */\n protected void autoDetectContainer() {\n // Was defined in atmosphere.xml\n if (getAsyncSupport() == null) {\n setAsyncSupport(createAsyncSupportResolver()\n .resolve(useNativeImplementation, useBlockingImplementation, useServlet30));\n }\n }\n\n /**\n * Auto detect instance of {@link AtmosphereHandler} in case META-INF/atmosphere.xml\n * is missing.\n *\n * @param servletContext {@link ServletContext}\n * @param classloader {@link ClassLoader} to load the class.\n * @throws java.net.MalformedURLException\n */\n public void autoDetectAtmosphereHandlers(ServletContext servletContext, ClassLoader classloader)\n throws MalformedURLException {\n\n // If Handler has been added\n if (!atmosphereHandlers.isEmpty()) return;\n\n logger.info(\"Auto detecting atmosphere handlers {}\", handlersPath);\n\n String realPath = servletContext.getRealPath(handlersPath);\n\n // Weblogic bug\n if (realPath == null) {\n URL u = servletContext.getResource(handlersPath);\n if (u == null) return;\n realPath = u.getPath();\n }\n\n loadAtmosphereHandlersFromPath(classloader, realPath);\n }\n\n public void loadAtmosphereHandlersFromPath(ClassLoader classloader, String realPath) {\n File file = new File(realPath);\n\n if (file.exists() && file.isDirectory()) {\n getFiles(file);\n scanDone = true;\n\n for (String className : possibleComponentsCandidate) {\n try {\n className = className.replace('\\\\', '/');\n className = className.replaceFirst(\"^.*/(WEB-INF|target)(?:/scala-[^/]+)?/(test-)?classes/(.*)\\\\.class\", \"$3\").replace(\"/\", \".\");\n Class clazz = classloader.loadClass(className);\n\n if (AtmosphereHandler.class.isAssignableFrom(clazz)) {\n AtmosphereHandler handler = newClassInstance(AtmosphereHandler.class, (Class) clazz);\n addMapping(\"/\" + handler.getClass().getSimpleName(),\n new AtmosphereHandlerWrapper(broadcasterFactory, handler, \"/\" + handler.getClass().getSimpleName(), config));\n logger.info(\"Installed AtmosphereHandler {} mapped to context-path: {}\", handler, handler.getClass().getName());\n }\n } catch (Throwable t) {\n logger.trace(\"failed to load class as an AtmosphereHandler: \" + className, t);\n }\n }\n }\n }\n\n /**\n * Auto detect instance of {@link org.atmosphere.websocket.WebSocketHandler} in case META-INF/atmosphere.xml\n * is missing.\n *\n * @param servletContext {@link ServletContext}\n * @param classloader {@link ClassLoader} to load the class.\n * @throws java.net.MalformedURLException\n */\n protected void autoDetectWebSocketHandler(ServletContext servletContext, ClassLoader classloader)\n throws MalformedURLException {\n\n if (hasNewWebSocketProtocol) return;\n\n logger.info(\"Auto detecting WebSocketHandler in {}\", handlersPath);\n loadWebSocketFromPath(classloader, realPath(servletContext, handlersPath));\n }\n\n protected void loadWebSocketFromPath(ClassLoader classloader, String realPath) {\n File file = new File(realPath);\n\n if (file.exists() && file.isDirectory()) {\n getFiles(file);\n scanDone = true;\n\n for (String className : possibleComponentsCandidate) {\n try {\n className = className.replace('\\\\', '/');\n className = className.replaceFirst(\"^.*/(WEB-INF|target)(?:/scala-[^/]+)?/(test-)?classes/(.*)\\\\.class\", \"$3\").replace(\"/\", \".\");\n Class clazz = classloader.loadClass(className);\n\n if (WebSocketProtocol.class.isAssignableFrom(clazz)) {\n webSocketProtocol = newClassInstance(WebSocketProtocol.class, (Class) clazz);\n logger.info(\"Installed WebSocketProtocol {}\", webSocketProtocol);\n }\n } catch (Throwable t) {\n logger.trace(\"failed to load class as an WebSocketProtocol: \" + className, t);\n }\n }\n }\n }\n\n /**\n * Get a list of possible candidates to load as {@link AtmosphereHandler}.\n *\n * @param f the real path {@link File}\n */\n private void getFiles(File f) {\n if (scanDone) return;\n\n File[] files = f.listFiles();\n for (File test : Objects.requireNonNull(files)) {\n if (test.isDirectory()) {\n getFiles(test);\n } else {\n String clazz = test.getAbsolutePath();\n if (clazz.endsWith(\".class\")) {\n possibleComponentsCandidate.add(clazz);\n }\n }\n }\n }\n\n /**\n * Configure some attributes on the {@link AtmosphereRequest}.\n *\n * @param req {@link AtmosphereRequest}\n */\n public AtmosphereFramework configureRequestResponse(AtmosphereRequest req, AtmosphereResponse res) throws UnsupportedEncodingException {\n req.setAttribute(PROPERTY_USE_STREAM, useStreamForFlushingComments);\n req.setAttribute(BROADCASTER_CLASS, broadcasterClassName);\n req.setAttribute(ATMOSPHERE_CONFIG, config);\n req.setAttribute(THROW_EXCEPTION_ON_CLONED_REQUEST, \"\" + config.isThrowExceptionOnCloned());\n\n boolean skip = true;\n String s = config.getInitParameter(ALLOW_QUERYSTRING_AS_REQUEST);\n if (s != null) {\n skip = Boolean.parseBoolean(s);\n }\n\n if (!skip || req.getAttribute(WEBSOCKET_SUSPEND) == null) {\n Map headers = configureQueryStringAsRequest(req);\n String body = headers.remove(ATMOSPHERE_POST_BODY);\n if (body != null && body.isEmpty()) {\n body = null;\n }\n\n // Reconfigure the request. Clear the Atmosphere queryString\n req.headers(headers)\n .method(body != null && req.getMethod().equalsIgnoreCase(\"GET\") ? \"POST\" : req.getMethod());\n\n if (body != null) {\n req.body(URLDecoder.decode(body, req.getCharacterEncoding() == null ? \"UTF-8\" : req.getCharacterEncoding()));\n }\n }\n\n s = req.getHeader(X_ATMOSPHERE_TRACKING_ID);\n\n // Lookup for websocket\n if (s == null || s.equals(\"0\")) {\n String unique = config.getInitParameter(ApplicationConfig.UNIQUE_UUID_WEBSOCKET);\n if (Boolean.parseBoolean(unique)) {\n s = (String) req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID);\n }\n }\n\n if (s == null || s.equals(\"0\")) {\n s = config.uuidProvider().generateUuid();\n res.setHeader(HeaderConfig.X_FIRST_REQUEST, \"true\");\n res.setHeader(X_ATMOSPHERE_TRACKING_ID, s);\n String contentType = config.getInitParameter(CONTENT_TYPE_FIRST_RESPONSE);\n if (contentType != null) {\n res.setHeader(\"Content-Type\", contentType);\n }\n } else {\n // This may breaks 1.0.0 application because the WebSocket's associated AtmosphereResource will\n // all have the same UUID, and retrieving the original one for WebSocket, so we don't set it at all.\n // Null means it is not an HTTP request.\n if (req.resource() == null) {\n res.setHeader(X_ATMOSPHERE_TRACKING_ID, s);\n } else if (req.getAttribute(WebSocket.WEBSOCKET_INITIATED) == null) {\n // WebSocket reconnect, in case an application manually set the header\n // (impossible to retrieve the headers normally with WebSocket or SSE)\n res.setHeader(X_ATMOSPHERE_TRACKING_ID, s);\n }\n }\n\n if (req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID) == null) {\n req.setAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID, s);\n }\n return this;\n }\n\n /**\n * Invoke the proprietary {@link AsyncSupport}.\n *\n * @param req\n * @param res\n * @return an {@link Action}\n * @throws IOException\n * @throws ServletException\n */\n public Action doCometSupport(AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException {\n\n if (isDestroyed.get()) return Action.CANCELLED;\n\n Action a = null;\n try {\n configureRequestResponse(req, res);\n a = asyncSupport.service(req, res);\n } catch (IllegalStateException ex) {\n boolean isJBoss = ex.getMessage() != null && ex.getMessage().startsWith(\"JBoss failed\");\n if (ex.getMessage() != null && (ex.getMessage().startsWith(\"Tomcat failed\") || isJBoss)) {\n if (!isFilter) {\n logger.warn(\"Failed using comet support: {}, error: {} Is the NIO or APR Connector enabled?\", asyncSupport.getClass().getName(),\n ex.getMessage());\n }\n logger.error(\"If you have more than one Connector enabled, make sure they both use the same protocol, \" +\n \"e.g NIO/APR or HTTP for all. If not, {} will be used and cannot be changed.\", BlockingIOCometSupport.class.getName(), ex);\n\n AsyncSupport current = asyncSupport;\n asyncSupport = asyncSupport.supportWebSocket() && !isJBoss ? new Tomcat7BIOSupportWithWebSocket(config) : new BlockingIOCometSupport(config);\n if (current instanceof AsynchronousProcessor) {\n ((AsynchronousProcessor) current).shutdown();\n }\n\n asyncSupport.init(config.getServletConfig());\n logger.warn(\"Using \" + asyncSupport.getClass().getName());\n\n a = asyncSupport.service(req, res);\n } else {\n logger.error(\"AtmosphereFramework exception\", ex);\n throw ex;\n }\n } finally {\n if (a != null) {\n notify(a.type(), req, res);\n }\n\n if (!externalizeDestroy) {\n if (req != null && a != null && a.type() != Action.TYPE.SUSPEND) {\n req.destroy();\n res.destroy();\n notify(Action.TYPE.DESTROYED, req, res);\n }\n }\n }\n return a;\n }\n\n /**\n * Return the default {@link Broadcaster} class name.\n *\n * @return the broadcasterClassName\n */\n public String getDefaultBroadcasterClassName() {\n return broadcasterClassName;\n }\n\n /**\n * Set the default {@link Broadcaster} class name.\n *\n * @param bccn the broadcasterClassName to set\n */\n public AtmosphereFramework setDefaultBroadcasterClassName(String bccn) {\n if (isBroadcasterSpecified) {\n logger.trace(\"Broadcaster {} already set in web.xml\", broadcasterClassName);\n return this;\n }\n isBroadcasterSpecified = true;\n\n broadcasterClassName = bccn;\n\n // Must reconfigure.\n broadcasterFactory = null;\n configureBroadcasterFactory();\n\n // We must recreate all previously created Broadcaster.\n for (AtmosphereHandlerWrapper w : atmosphereHandlers.values()) {\n // If case one listener is initializing the framework.\n if (w.broadcaster != null) {\n w.broadcaster = broadcasterFactory.lookup(w.broadcaster.getID(), true);\n }\n }\n return this;\n }\n\n /**\n * true if Atmosphere uses {@link AtmosphereResponseImpl#getOutputStream()}\n * by default for write operation.\n *\n * @return the useStreamForFlushingComments\n */\n public boolean isUseStreamForFlushingComments() {\n return useStreamForFlushingComments;\n }\n\n public boolean isUseServlet30() {\n return useServlet30;\n }\n\n /**\n * Set to true so Atmosphere uses {@link AtmosphereResponseImpl#getOutputStream()}\n * by default for write operation. Default is false.\n *\n * @param useStreamForFlushingComments the useStreamForFlushingComments to set\n */\n public AtmosphereFramework setUseStreamForFlushingComments(boolean useStreamForFlushingComments) {\n this.useStreamForFlushingComments = useStreamForFlushingComments;\n return this;\n }\n\n /**\n * Get the {@link BroadcasterFactory} which is used by Atmosphere to construct\n * {@link Broadcaster}.\n *\n * @return {@link BroadcasterFactory}\n */\n public BroadcasterFactory getBroadcasterFactory() {\n if (broadcasterFactory == null) {\n configureBroadcasterFactory();\n }\n return broadcasterFactory;\n }\n\n /**\n * Set the {@link BroadcasterFactory} which is used by Atmosphere to construct\n * {@link Broadcaster}.\n *\n * @return {@link BroadcasterFactory}\n */\n public AtmosphereFramework setBroadcasterFactory(final BroadcasterFactory broadcasterFactory) {\n this.broadcasterFactory = broadcasterFactory;\n configureBroadcaster();\n return this;\n }\n\n /**\n * Return the {@link org.atmosphere.cpr.BroadcasterCache} class name.\n *\n * @return the {@link org.atmosphere.cpr.BroadcasterCache} class name\n */\n public String getBroadcasterCacheClassName() {\n return broadcasterCacheClassName;\n }\n\n /**\n * Set the {@link org.atmosphere.cpr.BroadcasterCache} class name.\n *\n * @param broadcasterCacheClassName\n */\n public AtmosphereFramework setBroadcasterCacheClassName(String broadcasterCacheClassName) {\n this.broadcasterCacheClassName = broadcasterCacheClassName;\n return this;\n }\n\n /**\n * Add a new Broadcaster class name that AtmosphereServlet can use when initializing requests, and when the\n * atmosphere.xml broadcaster element is unspecified.\n *\n * @param broadcasterTypeString\n */\n public AtmosphereFramework addBroadcasterType(String broadcasterTypeString) {\n broadcasterTypes.add(broadcasterTypeString);\n return this;\n }\n\n public ConcurrentLinkedQueue broadcasterTypes() {\n return broadcasterTypes;\n }\n\n public String getWebSocketProtocolClassName() {\n return webSocketProtocolClassName;\n }\n\n public AtmosphereFramework setWebSocketProtocolClassName(String webSocketProtocolClassName) {\n hasNewWebSocketProtocol = true;\n this.webSocketProtocolClassName = webSocketProtocolClassName;\n return this;\n }\n\n public Map getAtmosphereHandlers() {\n return atmosphereHandlers;\n }\n\n protected Map configureQueryStringAsRequest(AtmosphereRequest request) {\n Map headers = new HashMap();\n\n StringBuilder q = new StringBuilder();\n try {\n String qs = request.getQueryString();\n if (qs != null && !qs.isEmpty()) {\n String[] params = qs.split(\"&\");\n String[] s;\n for (String p : params) {\n s = p.split(\"=\", 2);\n final String header = s[0];\n final String value = s.length > 1 ? s[1] : \"\";\n\n if (header.equalsIgnoreCase(\"Content-Type\")) {\n // Use the one set by the user first.\n if (request.getContentType() == null ||\n !request.getContentType().equalsIgnoreCase(s.length > 1 ? value : \"\")) {\n request.contentType(s.length > 1 ? URLDecoder.decode(value, \"UTF-8\") : \"\");\n }\n }\n if (!header.isEmpty()\n && !header.toLowerCase().startsWith(\"x-atmo\")\n && !header.equalsIgnoreCase(HeaderConfig.X_HEARTBEAT_SERVER)\n && !header.equalsIgnoreCase(\"Content-Type\")\n && !header.equalsIgnoreCase(\"_\")) {\n q.append(header).append(\"=\").append(s.length > 1 ? value : \"\").append(\"&\");\n }\n headers.put(header, s.length > 1 ? value : \"\");\n }\n }\n } catch (Exception ex) {\n logger.error(\"Unable to parse query string\", ex);\n }\n String disallowModifyQueryString = config.getInitParameter(ApplicationConfig.DISALLOW_MODIFY_QUERYSTRING);\n if (disallowModifyQueryString == null ||\n disallowModifyQueryString.length() == 0 || \"false\".equalsIgnoreCase(disallowModifyQueryString)) {\n if (q.length() > 0) {\n q.deleteCharAt(q.length() - 1);\n }\n request.queryString(q.toString());\n }\n\n logger.trace(\"Query String translated to headers {}\", headers);\n return headers;\n }\n\n public WebSocketProtocol getWebSocketProtocol() {\n // TODO: Spagetthi code, needs to rework.\n // Make sure we initialized the WebSocketProtocol\n initWebSocket();\n return webSocketProtocol;\n }\n\n public boolean isUseNativeImplementation() {\n return useNativeImplementation;\n }\n\n public AtmosphereFramework setUseNativeImplementation(boolean useNativeImplementation) {\n this.useNativeImplementation = useNativeImplementation;\n return this;\n }\n\n public boolean isUseBlockingImplementation() {\n return useBlockingImplementation;\n }\n\n public AtmosphereFramework setUseBlockingImplementation(boolean useBlockingImplementation) {\n this.useBlockingImplementation = useBlockingImplementation;\n return this;\n }\n\n public String getAtmosphereDotXmlPath() {\n return atmosphereDotXmlPath;\n }\n\n public AtmosphereFramework setAtmosphereDotXmlPath(String atmosphereDotXmlPath) {\n this.atmosphereDotXmlPath = atmosphereDotXmlPath;\n return this;\n }\n\n public String getHandlersPath() {\n return handlersPath;\n }\n\n public AtmosphereFramework setHandlersPath(String handlersPath) {\n this.handlersPath = handlersPath;\n return this;\n }\n\n /**\n * Return the location of the JARs containing the application classes. Default is WEB-INF/lib.\n *\n * @return the location of the JARs containing the application classes. Default is WEB-INF/lib\n */\n public String getLibPath() {\n return libPath;\n }\n\n /**\n * Set the location of the JARs containing the application.\n *\n * @param libPath the location of the JARs containing the application.\n * @return this\n */\n public AtmosphereFramework setLibPath(String libPath) {\n this.libPath = libPath;\n return this;\n }\n\n /**\n * The current {@link org.atmosphere.websocket.WebSocketProcessor} used to handle websocket requests.\n *\n * @return {@link org.atmosphere.websocket.WebSocketProcessor}\n */\n public String getWebSocketProcessorClassName() {\n return webSocketProcessorClassName;\n }\n\n /**\n * Set the {@link org.atmosphere.websocket.WebSocketProcessor} class name used to process WebSocket requests. Default is\n * {@link DefaultWebSocketProcessor}\n *\n * @param webSocketProcessorClassName {@link org.atmosphere.websocket.WebSocketProcessor}\n * @return this\n */\n public AtmosphereFramework setWebsocketProcessorClassName(String webSocketProcessorClassName) {\n this.webSocketProcessorClassName = webSocketProcessorClassName;\n return this;\n }\n\n /**\n * Add an {@link AtmosphereInterceptor} implementation. The adding order of {@link AtmosphereInterceptor} will be used, e.g\n * the first added {@link AtmosphereInterceptor} will always be called first.\n *\n * @param c {@link AtmosphereInterceptor}\n * @return this\n */\n public AtmosphereFramework interceptor(AtmosphereInterceptor c) {\n if (!checkDuplicate(c)) {\n interceptors.add(c);\n if (isInit) {\n addInterceptorToAllWrappers(c);\n }\n }\n return this;\n }\n\n protected void addDefaultOrAppInterceptors() {\n for (AtmosphereInterceptor c : interceptors) {\n addInterceptorToAllWrappers(c);\n }\n }\n\n protected void addInterceptorToAllWrappers(AtmosphereInterceptor c) {\n c.configure(config);\n InvokationOrder.PRIORITY p = InvokationOrder.class.isAssignableFrom(c.getClass()) ? ((InvokationOrder) c).priority() : InvokationOrder.AFTER_DEFAULT;\n\n logger.info(\"Installed AtmosphereInterceptor {} with priority {} \", c, p.name());\n //need insert this new interceptor into all the existing handlers\n for (AtmosphereHandlerWrapper wrapper : atmosphereHandlers.values()) {\n addInterceptorToWrapper(wrapper, c);\n }\n }\n\n protected void addInterceptorToWrapper(AtmosphereHandlerWrapper wrapper, AtmosphereInterceptor c) {\n if (!checkDuplicate(wrapper.interceptors, c.getClass())) {\n wrapper.interceptors.add(c);\n wrapper.interceptors.sort(new InterceptorComparator());\n }\n }\n\n protected void addInterceptorToWrapper(AtmosphereHandlerWrapper wrapper, List interceptors) {\n\n for (AtmosphereInterceptor c : this.interceptors) {\n addInterceptorToWrapper(wrapper, c);\n }\n\n for (AtmosphereInterceptor c : interceptors) {\n addInterceptorToWrapper(wrapper, c);\n c.configure(config);\n }\n }\n\n /**\n *

\n * Checks if an instance of the specified {@link AtmosphereInterceptor} implementation exists in the\n * {@link #interceptors}.\n *

\n *\n * @param c the implementation\n * @return {@code false} if an instance of the same interceptor's class already exists in {@link #interceptors}, {@code true} otherwise\n */\n private boolean checkDuplicate(final AtmosphereInterceptor c) {\n return checkDuplicate(interceptors, c.getClass());\n }\n\n /**\n *

\n * Checks in the specified list if there is at least one instance of the given\n * {@link AtmosphereInterceptor interceptor} implementation class.\n *

\n *\n * @param interceptorList the interceptors\n * @param c the interceptor class\n * @return {@code false} if an instance of the class already exists in the list, {@code true} otherwise\n */\n private boolean checkDuplicate(final List interceptorList, Class c) {\n for (final AtmosphereInterceptor i : interceptorList) {\n if (i.getClass().equals(c)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Return the list of {@link AtmosphereInterceptor}.\n *\n * @return the list of {@link AtmosphereInterceptor}\n */\n public LinkedList interceptors() {\n return interceptors;\n }\n\n /**\n * Set the {@link AnnotationProcessor} class name.\n *\n * @param annotationProcessorClassName the {@link AnnotationProcessor} class name.\n * @return this\n */\n public AtmosphereFramework annotationProcessorClassName(String annotationProcessorClassName) {\n this.annotationProcessorClassName = annotationProcessorClassName;\n return this;\n }\n\n /**\n * Add an {@link AsyncSupportListener}.\n *\n * @param asyncSupportListener an {@link AsyncSupportListener}\n * @return this;\n */\n public AtmosphereFramework asyncSupportListener(AsyncSupportListener asyncSupportListener) {\n asyncSupportListeners.add(asyncSupportListener);\n return this;\n }\n\n /**\n * Return the list of {@link AsyncSupportListener}s.\n *\n * @return\n */\n public List asyncSupportListeners() {\n return asyncSupportListeners;\n }\n\n /**\n * Add {@link BroadcasterListener} to all created {@link Broadcaster}s.\n */\n public AtmosphereFramework addBroadcasterListener(BroadcasterListener b) {\n broadcasterFactory.addBroadcasterListener(b);\n broadcasterListeners.add(b);\n return this;\n }\n\n /**\n * Add {@link BroadcasterCacheListener} to the {@link BroadcasterCache}.\n */\n public AtmosphereFramework addBroadcasterCacheListener(BroadcasterCacheListener b) {\n broadcasterCacheListeners.add(b);\n return this;\n }\n\n public List broadcasterCacheListeners() {\n return broadcasterCacheListeners;\n }\n\n /**\n * Add a {@link BroadcasterCacheInspector} which will be associated with the defined {@link BroadcasterCache}.\n *\n * @param b {@link BroadcasterCacheInspector}\n * @return this;\n */\n public AtmosphereFramework addBroadcasterCacheInjector(BroadcasterCacheInspector b) {\n inspectors.add(b);\n return this;\n }\n\n /**\n * Return the list of {@link BroadcasterCacheInspector}s.\n *\n * @return the list of {@link BroadcasterCacheInspector}s\n */\n public ConcurrentLinkedQueue inspectors() {\n return inspectors;\n }\n\n /**\n * Return a configured instance of {@link AtmosphereConfig}.\n *\n * @return a configured instance of {@link AtmosphereConfig}\n */\n public AtmosphereConfig getAtmosphereConfig() {\n return config;\n }\n\n /**\n * Return the {@link ServletContext}\n *\n * @return the {@link ServletContext}\n */\n public ServletContext getServletContext() {\n return servletConfig.getServletContext();\n }\n\n public ServletConfig getServletConfig() {\n return servletConfig;\n }\n\n /**\n * Return the list of {@link BroadcastFilter}s.\n *\n * @return the list of {@link BroadcastFilter}s\n */\n public List broadcasterFilters() {\n return broadcasterFilters;\n }\n\n /**\n * Add a {@link BroadcastFilter}.\n *\n * @return\n */\n public AtmosphereFramework broadcasterFilters(BroadcastFilter f) {\n broadcasterFilters.add(f.getClass().getName());\n\n for (Broadcaster b : config.getBroadcasterFactory().lookupAll()) {\n b.getBroadcasterConfig().addFilter(f);\n }\n return this;\n }\n\n /**\n * Returns true if {@link java.util.concurrent.ExecutorService} is shared among all components.\n *\n * @return true if {@link java.util.concurrent.ExecutorService} is shared amongst all components\n */\n public boolean isShareExecutorServices() {\n return sharedThreadPools;\n }\n\n /**\n * Set to true to have a {@link java.util.concurrent.ExecutorService} shared among all components.\n *\n * @param sharedThreadPools\n * @return this\n */\n public AtmosphereFramework shareExecutorServices(boolean sharedThreadPools) {\n this.sharedThreadPools = sharedThreadPools;\n return this;\n }\n\n protected void autoConfigureService(ServletContext sc) throws IOException {\n String path = handlersPath != DEFAULT_HANDLER_PATH ? handlersPath : realPath(sc, handlersPath);\n try {\n annotationProcessor = newClassInstance(AnnotationProcessor.class,\n (Class) IOUtils.loadClass(getClass(), annotationProcessorClassName));\n logger.info(\"Atmosphere is using {} for processing annotation\", annotationProcessorClassName);\n\n annotationProcessor.configure(config);\n\n if (!packages.isEmpty()) {\n for (String s : packages) {\n annotationProcessor.scan(s);\n }\n }\n\n // Second try.\n if (!annotationFound) {\n if (path != null) {\n annotationProcessor.scan(new File(path));\n }\n\n // Always scan library\n String pathLibs = !libPath.equals(DEFAULT_LIB_PATH) ? libPath : realPath(sc, DEFAULT_LIB_PATH);\n if (pathLibs != null) {\n File libFolder = new File(pathLibs);\n File[] jars = libFolder.listFiles((arg0, arg1) -> arg1.endsWith(\".jar\"));\n\n if (jars != null) {\n for (File file : jars) {\n annotationProcessor.scan(file);\n }\n }\n }\n }\n\n if (!annotationFound && allowAllClassesScan) {\n logger.debug(\"Scanning all classes on the classpath\");\n annotationProcessor.scanAll();\n }\n } catch (Throwable e) {\n logger.error(\"\", e);\n } finally {\n if (annotationProcessor != null) {\n annotationProcessor.destroy();\n }\n }\n }\n\n /**\n * The current {@link EndpointMapper} used to map requests to {@link AtmosphereHandler}.\n *\n * @return {@link EndpointMapper}\n */\n public EndpointMapper endPointMapper() {\n return endpointMapper;\n }\n\n /**\n * Set the {@link EndpointMapper}.\n *\n * @param endpointMapper {@link EndpointMapper}\n * @return this\n */\n public AtmosphereFramework endPointMapper(EndpointMapper endpointMapper) {\n this.endpointMapper = endpointMapper;\n return this;\n }\n\n /**\n * Add support for package detection of Atmosphere's Component.\n *\n * @param clazz a Class\n * @return this.\n */\n public AtmosphereFramework addAnnotationPackage(Class clazz) {\n if (clazz.getPackage() == null) {\n logger.error(\"Class {} must have a package defined\", clazz);\n } else {\n packages.add(clazz.getPackage().getName());\n }\n return this;\n }\n\n public AtmosphereFramework notify(Action.TYPE type, AtmosphereRequest request, AtmosphereResponse response) {\n for (AsyncSupportListener l : asyncSupportListeners()) {\n try {\n switch (type) {\n case TIMEOUT:\n l.onTimeout(request, response);\n break;\n case CANCELLED:\n l.onClose(request, response);\n break;\n case SUSPEND:\n l.onSuspend(request, response);\n break;\n case RESUME:\n l.onResume(request, response);\n break;\n case DESTROYED:\n l.onDestroyed(request, response);\n break;\n }\n } catch (Throwable t) {\n logger.warn(\"\", t);\n }\n }\n return this;\n }\n\n public AtmosphereFramework notifyDestroyed(String uuid) {\n for (AtmosphereResourceListener l : atmosphereResourceListeners()) {\n l.onDisconnect(uuid);\n }\n return this;\n }\n\n public AtmosphereFramework notifySuspended(String uuid) {\n for (AtmosphereResourceListener l : atmosphereResourceListeners()) {\n l.onSuspended(uuid);\n }\n return this;\n }\n\n /**\n * Add an {@link WebSocketHandler} mapped to \"/*\".\n * return this\n */\n public AtmosphereFramework addWebSocketHandler(WebSocketHandler handler) {\n addWebSocketHandler(ROOT_MASTER, handler);\n return this;\n }\n\n /**\n * Add an {@link WebSocketHandler} mapped to the path.\n * return this\n */\n public AtmosphereFramework addWebSocketHandler(String path, WebSocketHandler handler) {\n addWebSocketHandler(path, handler, REFLECTOR_ATMOSPHEREHANDLER, Collections.emptyList());\n return this;\n }\n\n /**\n * Add an {@link WebSocketHandler} mapped to the path and the {@link AtmosphereHandler} in case {@link Broadcaster} are\n * used.\n *\n * @param path a path\n * @param handler a {@link WebSocketHandler}\n * @param h an {@link AtmosphereHandler}\n * @return this\n */\n public AtmosphereFramework addWebSocketHandler(String path, WebSocketHandler handler, AtmosphereHandler h) {\n addWebSocketHandler(path, handler, REFLECTOR_ATMOSPHEREHANDLER, Collections.emptyList());\n return this;\n }\n\n /**\n * Add an {@link WebSocketHandler} mapped to the path and the {@link AtmosphereHandler} in case {@link Broadcaster} are\n * used.\n *\n * @param path a path\n * @param handler a {@link WebSocketHandler}\n * @param h an {@link AtmosphereHandler}\n * @param l {@link AtmosphereInterceptor}\n * @return this\n */\n public AtmosphereFramework addWebSocketHandler(String path, WebSocketHandler handler, AtmosphereHandler h, List l) {\n WebSocketProcessorFactory.getDefault().getWebSocketProcessor(this)\n .registerWebSocketHandler(path,\n new WebSocketProcessor.WebSocketHandlerProxy(broadcasterFactory.lookup(path, true).getClass(), handler));\n addAtmosphereHandler(path, h, l);\n return this;\n }\n\n /**\n * Invoked when a {@link AnnotationProcessor} found an annotation.\n *\n * @param b true when found\n * @return this\n */\n public AtmosphereFramework annotationScanned(boolean b) {\n annotationFound = b;\n return this;\n }\n\n /**\n * Return true if the {@link #init()} has been sucessfully executed.\n *\n * @return true if the {@link #init()} has been sucessfully executed.\n */\n public boolean initialized() {\n return isInit;\n }\n\n public List packages() {\n return packages;\n }\n\n /**\n * Return the list of packages the framework should look for {@link org.atmosphere.config.AtmosphereAnnotation}.\n *\n * @return the list of packages the framework should look for {@link org.atmosphere.config.AtmosphereAnnotation}\n */\n public List customAnnotationPackages() {\n return annotationPackages;\n }\n\n /**\n * Add a package containing classes annotated with {@link org.atmosphere.config.AtmosphereAnnotation}.\n *\n * @param p a package\n * @return this;\n */\n public AtmosphereFramework addCustomAnnotationPackage(Class p) {\n annotationPackages.addLast(p.getPackage().getName());\n return this;\n }\n\n /**\n * Instantiate a class\n *\n * @param classType The Required Class's Type\n * @param defaultType The default implementation of the Class's Type.\n * @return the an instance of defaultType\n * @throws InstantiationException\n * @throws IllegalAccessException\n */\n public T newClassInstance(Class classType, Class defaultType) throws InstantiationException, IllegalAccessException {\n return objectFactory.newClassInstance(classType, defaultType);\n }\n\n /**\n * Set an object used for class instantiation.\n * Allows for integration with dependency injection frameworks.\n *\n * @param objectFactory\n */\n public void objectFactory(AtmosphereObjectFactory objectFactory) {\n this.objectFactory = objectFactory;\n this.objectFactory.configure(config);\n }\n\n /**\n * If set to true, the task of finishing the request/response lifecycle will not be handled by this class.\n *\n * @param externalizeDestroy\n * @return this\n */\n public AtmosphereFramework externalizeDestroy(boolean externalizeDestroy) {\n this.externalizeDestroy = externalizeDestroy;\n return this;\n }\n\n /**\n * Return the {@link AnnotationProcessor}\n *\n * @return the {@link AnnotationProcessor}\n */\n public AnnotationProcessor annotationProcessor() {\n return annotationProcessor;\n }\n\n /**\n * Was a {@link Broadcaster} defined in web.xml or programmatically added.\n *\n * @return true is defined.\n */\n public boolean isBroadcasterSpecified() {\n return isBroadcasterSpecified;\n }\n\n protected void configureObjectFactory() {\n String s = config.getInitParameter(ApplicationConfig.OBJECT_FACTORY);\n if (s != null) {\n try {\n AtmosphereObjectFactory aci = (AtmosphereObjectFactory) IOUtils.loadClass(getClass(), s).newInstance();\n logger.debug(\"Found ObjectFactory {}\", aci.getClass().getName());\n objectFactory(aci);\n } catch (Exception ex) {\n logger.warn(\"Unable to load AtmosphereClassInstantiator instance\", ex);\n }\n }\n\n if (!DefaultAtmosphereObjectFactory.class.isAssignableFrom(objectFactory.getClass())) {\n logger.trace(\"ObjectFactory already set to {}\", objectFactory);\n }\n }\n\n /**\n * Exclude an {@link AtmosphereInterceptor} from being added, at startup, by Atmosphere. The default's {@link #DEFAULT_ATMOSPHERE_INTERCEPTORS}\n * are candidates for being excluded.\n *\n * @param interceptor an {@link AtmosphereInterceptor} class name\n * @return this\n */\n public AtmosphereFramework excludeInterceptor(String interceptor) {\n excludedInterceptors.add(interceptor);\n return this;\n }\n\n public AtmosphereFramework filterManipulator(BroadcasterConfig.FilterManipulator m) {\n filterManipulators.add(m);\n return this;\n }\n\n public List filterManipulators() {\n return filterManipulators;\n }\n\n public boolean isAServletFilter() {\n return isFilter;\n }\n\n public ConcurrentLinkedQueue objectFactoryType() {\n return objectFactoryType;\n }\n\n public String mappingRegex() {\n return mappingRegex;\n }\n\n public AtmosphereFramework mappingRegex(String mappingRegex) {\n this.mappingRegex = mappingRegex;\n return this;\n }\n\n public void setUseServlet30(boolean useServlet30) {\n this.useServlet30 = useServlet30;\n }\n\n public boolean webSocketEnabled() {\n return webSocketEnabled;\n }\n\n public AtmosphereFramework webSocketEnabled(boolean webSocketEnabled) {\n this.webSocketEnabled = webSocketEnabled;\n return this;\n }\n\n public String broadcasterLifeCyclePolicy() {\n return broadcasterLifeCyclePolicy;\n }\n\n public AtmosphereFramework broadcasterLifeCyclePolicy(String broadcasterLifeCyclePolicy) {\n this.broadcasterLifeCyclePolicy = broadcasterLifeCyclePolicy;\n return this;\n }\n\n public List broadcasterListeners() {\n return broadcasterListeners;\n }\n\n public boolean sharedThreadPools() {\n return sharedThreadPools;\n }\n\n public AtmosphereFramework sharedThreadPools(boolean sharedThreadPools) {\n this.sharedThreadPools = sharedThreadPools;\n return this;\n }\n\n public boolean allowAllClassesScan() {\n return allowAllClassesScan;\n }\n\n public AtmosphereFramework allowAllClassesScan(boolean allowAllClassesScan) {\n this.allowAllClassesScan = allowAllClassesScan;\n return this;\n }\n\n public AtmosphereObjectFactory objectFactory() {\n return objectFactory;\n }\n\n public boolean externalizeDestroy() {\n return externalizeDestroy;\n }\n\n public List excludedInterceptors() {\n return excludedInterceptors;\n }\n\n public Class[] defaultInterceptors() {\n return DEFAULT_ATMOSPHERE_INTERCEPTORS.toArray(new Class[DEFAULT_ATMOSPHERE_INTERCEPTORS.size()]);\n }\n\n public AtmosphereResourceFactory atmosphereFactory() {\n if (arFactory == null) {\n configureAtmosphereResourceFactory();\n }\n return arFactory;\n }\n\n private AtmosphereFramework configureAtmosphereResourceFactory() {\n if (arFactory != null) return this;\n\n synchronized (this) {\n try {\n arFactory = newClassInstance(AtmosphereResourceFactory.class, DefaultAtmosphereResourceFactory.class);\n } catch (InstantiationException | IllegalAccessException e) {\n logger.error(\"\", e);\n }\n arFactory.configure(config);\n }\n return this;\n }\n\n private AtmosphereFramework configureWebSocketFactory() {\n if (webSocketFactory != null) return this;\n\n synchronized (this) {\n try {\n webSocketFactory = newClassInstance(WebSocketFactory.class, DefaultWebSocketFactory.class);\n } catch (InstantiationException | IllegalAccessException e) {\n logger.error(\"\", e);\n }\n }\n return this;\n }\n\n public MetaBroadcaster metaBroadcaster() {\n return metaBroadcaster;\n }\n\n private AtmosphereFramework configureMetaBroadcaster() {\n try {\n metaBroadcaster = newClassInstance(MetaBroadcaster.class, DefaultMetaBroadcaster.class);\n metaBroadcaster.configure(config);\n } catch (InstantiationException | IllegalAccessException e) {\n logger.error(\"\", e);\n }\n return this;\n }\n\n /**\n * Get the default {@link org.atmosphere.cpr.Serializer} class name to use for {@link org.atmosphere.cpr.AtmosphereResource}s.\n *\n * @return the class name as a string, might be null if not configured\n */\n public String getDefaultSerializerClassName() {\n return defaultSerializerClassName;\n }\n\n /**\n * Get the default {@link org.atmosphere.cpr.Serializer} class to use for {@link org.atmosphere.cpr.AtmosphereResource}s.\n *\n * @return the class, might be null if not configured\n */\n public Class getDefaultSerializerClass() {\n return defaultSerializerClass;\n }\n\n /**\n * Set the default {@link org.atmosphere.cpr.Serializer} class name to use for {@link org.atmosphere.cpr.AtmosphereResource}s.\n *\n * @param defaultSerializerClassName the class name to use\n * @return this\n */\n public AtmosphereFramework setDefaultSerializerClassName(String defaultSerializerClassName) {\n this.defaultSerializerClassName = defaultSerializerClassName;\n initDefaultSerializer();\n return this;\n }\n\n private void initDefaultSerializer() {\n if (defaultSerializerClassName != null && !defaultSerializerClassName.isEmpty()) {\n try {\n @SuppressWarnings(\"unchecked\")\n Class clazz = (Class) IOUtils.loadClass(Serializer.class, defaultSerializerClassName);\n if (Serializer.class.isAssignableFrom(clazz)) {\n defaultSerializerClass = clazz;\n } else {\n logger.error(\"Default Serializer class name does not implement Serializer interface\");\n defaultSerializerClassName = null;\n defaultSerializerClass = null;\n }\n } catch (Exception e) {\n logger.error(\"Unable to set default Serializer\", e);\n defaultSerializerClassName = null;\n defaultSerializerClass = null;\n }\n } else {\n defaultSerializerClassName = null;\n defaultSerializerClass = null;\n }\n }\n\n /**\n * Return the {@link AtmosphereResourceSessionFactory}\n *\n * @return the AtmosphereResourceSessionFactory\n */\n public synchronized AtmosphereResourceSessionFactory sessionFactory() {\n if (sessionFactory == null) {\n try {\n sessionFactory = newClassInstance(AtmosphereResourceSessionFactory.class, DefaultAtmosphereResourceSessionFactory.class);\n } catch (InstantiationException | IllegalAccessException e) {\n logger.error(\"\", e);\n }\n }\n return sessionFactory;\n }\n\n /**\n * Return true is the {@link #destroy()} method has been invoked.\n *\n * @return true is the {@link #destroy()} method has been invoked.\n */\n public boolean isDestroyed() {\n return isDestroyed.get();\n }\n\n /**\n * Add a {@link org.atmosphere.cpr.AtmosphereFrameworkListener}\n *\n * @param l {@link org.atmosphere.cpr.AtmosphereFrameworkListener}\n * @return this;\n */\n public AtmosphereFramework frameworkListener(AtmosphereFrameworkListener l) {\n frameworkListeners.add(l);\n return this;\n }\n\n /**\n * Return the list of {@link org.atmosphere.cpr.AtmosphereFrameworkListener}\n *\n * @return {@link org.atmosphere.cpr.AtmosphereFrameworkListener}\n */\n public List frameworkListeners() {\n return frameworkListeners;\n }\n\n protected void onPreInit() {\n for (AtmosphereFrameworkListener l : frameworkListeners) {\n try {\n l.onPreInit(this);\n } catch (Exception e) {\n logger.error(\"\", e);\n }\n }\n }\n\n protected void onPostInit() {\n for (AtmosphereFrameworkListener l : frameworkListeners) {\n try {\n l.onPostInit(this);\n } catch (Exception e) {\n logger.error(\"\", e);\n }\n }\n }\n\n protected void onPreDestroy() {\n for (AtmosphereFrameworkListener l : frameworkListeners) {\n try {\n l.onPreDestroy(this);\n } catch (Exception e) {\n logger.error(\"\", e);\n }\n }\n }\n\n protected void onPostDestroy() {\n for (AtmosphereFrameworkListener l : frameworkListeners) {\n try {\n l.onPostDestroy(this);\n } catch (Exception e) {\n logger.error(\"\", e);\n }\n }\n }\n\n /**\n * Return the list of {@link org.atmosphere.cpr.AtmosphereResourceListener}\n *\n * @return the list of {@link org.atmosphere.cpr.AtmosphereResourceListener}\n */\n public List atmosphereResourceListeners() {\n return atmosphereResourceListeners;\n }\n\n /**\n * Add a {@link org.atmosphere.cpr.AtmosphereResourceListener}\n *\n * @param atmosphereResourceListener a {@link org.atmosphere.cpr.AtmosphereResourceListener}\n * @return this\n */\n public AtmosphereFramework atmosphereResourceListener(AtmosphereResourceListener atmosphereResourceListener) {\n atmosphereResourceListeners.add(atmosphereResourceListener);\n return this;\n }\n\n /**\n * Set a {@link java.util.UUID} like implementation for generating random UUID String\n *\n * @param uuidProvider\n * @return this\n */\n public AtmosphereFramework uuidProvider(UUIDProvider uuidProvider) {\n this.uuidProvider = uuidProvider;\n return this;\n }\n\n /**\n * Return the {@link org.atmosphere.util.UUIDProvider}\n *\n * @return {@link org.atmosphere.util.UUIDProvider}\n */\n public UUIDProvider uuidProvider() {\n return uuidProvider;\n }\n\n /**\n * Return the {@link WebSocketFactory}\n *\n * @return the {@link WebSocketFactory}\n */\n public WebSocketFactory webSocketFactory() {\n if (webSocketFactory == null) {\n configureWebSocketFactory();\n }\n return webSocketFactory;\n }\n\n /**\n * Configure the {@link WebSocketFactory}\n *\n * @param webSocketFactory the {@link WebSocketFactory}\n * @return this\n */\n public AtmosphereFramework webSocketFactory(WebSocketFactory webSocketFactory) {\n this.webSocketFactory = webSocketFactory;\n return this;\n }\n\n /**\n * If a {@link ContainerInitializer} fail, log the excetion here.\n *\n * @param initializationError\n */\n public void initializationError(IllegalStateException initializationError) {\n this.initializationError = initializationError;\n }\n}\n", "file_name": "AtmosphereFramework.java", "human_label": "Remove the mapping from atmosphereHandlers.", "level": "class_runnable", "lineno": "746", "name": "removeAtmosphereHandler", "oracle_context": "{ \"apis\" : \"[endsWith, remove, AtmosphereFramework, mappingRegex]\", \"classes\" : \"[]\", \"vars\" : \"[mappingRegex, atmosphereHandlers]\" }", "package": "org.atmosphere.cpr", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767a21a6d9265ec018517", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.io.OutputStream;\\nLinkedBuffer head;\\nLinkedBuffer tail;\\nint size;\\nint nextBufferSize;\\nOutputStream out;\\nFlushHandler flushHandler;\\nWriteSink sink;\\nflush(WriteSession session,byte[] buf,int offset,int len);\\nflush(WriteSession session,byte[] buf,int offset,int len,byte[] next,int nextoffset,int nextlen);\\nflush(WriteSession session,LinkedBuffer lb,byte[] buf,int offset,int len);\\nWriteSession(LinkedBuffer head);\\nWriteSession(LinkedBuffer head,int nextBufferSize);\\nWriteSession(LinkedBuffer head,OutputStream out,FlushHandler flushHandler,int nextBufferSize);\\nWriteSession(LinkedBuffer head,OutputStream out);\\nclear();\\ngetSize();\\ntoByteArray();\\nflush(byte[] buf,int offset,int len);\\nflush(byte[] buf,int offset,int len,byte[] next,int nextoffset,int nextlen);\\nflush(LinkedBuffer lb,byte[] buf,int offset,int len);\\nreset();\\n\", \"repo_level\" : \"\" }", "class_name": "WriteSession", "code": "public final byte[] toByteArray(){\n LinkedBuffer node=head;\n int offset=0, len;\n final byte[] buf=new byte[size];\n do {\n if ((len=node.offset - node.start) > 0) {\n System.arraycopy(node.buffer,node.start,buf,offset,len);\n offset+=len;\n }\n }\n while ((node=node.next) != null);\n return buf;\n}\n", "docstring": "/** \n * Returns a single byte array containg all the contents written to the buffer(s).\n */\n", "end_lineno": "155", "file_content": "//========================================================================\r\n//Copyright 2007-2010 David Yu dyuproject@gmail.com\r\n//------------------------------------------------------------------------\r\n//Licensed under the Apache License, Version 2.0 (the \"License\");\r\n//you may not use this file except in compliance with the License.\r\n//You may obtain a copy of the License at \r\n//http://www.apache.org/licenses/LICENSE-2.0\r\n//Unless required by applicable law or agreed to in writing, software\r\n//distributed under the License is distributed on an \"AS IS\" BASIS,\r\n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n//See the License for the specific language governing permissions and\r\n//limitations under the License.\r\n//========================================================================\r\n\r\npackage io.protostuff;\r\n\r\nimport java.io.IOException;\r\nimport java.io.OutputStream;\r\n\r\n/**\r\n * Designed to be subclassed by implementations of {@link Output} for easier serialization code for streaming or full\r\n * buffering. This is used when objects need to be serialzied/written into a {@code LinkedBuffer}.\r\n * \r\n * @author David Yu\r\n * @created Sep 20, 2010\r\n */\r\npublic class WriteSession\r\n{\r\n\r\n public interface FlushHandler\r\n {\r\n int flush(WriteSession session,\r\n byte[] buf, int offset, int len) throws IOException;\r\n\r\n int flush(WriteSession session,\r\n byte[] buf, int offset, int len,\r\n byte[] next, int nextoffset, int nextlen) throws IOException;\r\n\r\n int flush(WriteSession session,\r\n LinkedBuffer lb,\r\n byte[] buf, int offset, int len) throws IOException;\r\n }\r\n\r\n /**\r\n * The main/root/head buffer of this write session.\r\n */\r\n public final LinkedBuffer head;\r\n\r\n /**\r\n * The last buffer of this write session (This points to head if growing not needed).\r\n */\r\n protected LinkedBuffer tail;\r\n\r\n /**\r\n * The actual number of bytes written to the buffer.\r\n */\r\n protected int size = 0;\r\n\r\n /**\r\n * The next buffer size used when growing the buffer.\r\n */\r\n public final int nextBufferSize;\r\n\r\n /**\r\n * The sink of this buffer.\r\n */\r\n public final OutputStream out;\r\n\r\n public final FlushHandler flushHandler;\r\n\r\n /**\r\n * The sink of this write session.\r\n */\r\n public final WriteSink sink;\r\n\r\n public WriteSession(LinkedBuffer head)\r\n {\r\n this(head, LinkedBuffer.DEFAULT_BUFFER_SIZE);\r\n }\r\n\r\n public WriteSession(LinkedBuffer head, int nextBufferSize)\r\n {\r\n tail = head;\r\n this.head = head;\r\n this.nextBufferSize = nextBufferSize;\r\n out = null;\r\n flushHandler = null;\r\n\r\n sink = WriteSink.BUFFERED;\r\n }\r\n\r\n public WriteSession(LinkedBuffer head, OutputStream out, FlushHandler flushHandler,\r\n int nextBufferSize)\r\n {\r\n tail = head;\r\n this.head = head;\r\n this.nextBufferSize = nextBufferSize;\r\n this.out = out;\r\n this.flushHandler = flushHandler;\r\n\r\n sink = WriteSink.STREAMED;\r\n\r\n assert out != null;\r\n }\r\n\r\n public WriteSession(LinkedBuffer head, OutputStream out)\r\n {\r\n this(head, out, null, LinkedBuffer.DEFAULT_BUFFER_SIZE);\r\n }\r\n\r\n /**\r\n * Resets this session for re-use. Meant to be overridden by subclasses that have other state to reset.\r\n */\r\n public void reset()\r\n {\r\n\r\n }\r\n\r\n /**\r\n * The buffer will be cleared (tail will point to the head) and the size will be reset to zero.\r\n */\r\n public WriteSession clear()\r\n {\r\n tail = head.clear();\r\n size = 0;\r\n return this;\r\n }\r\n\r\n /**\r\n * Returns the amount of bytes written in this session.\r\n */\r\n public final int getSize()\r\n {\r\n return size;\r\n }\r\n\r\n /**\r\n * Returns a single byte array containg all the contents written to the buffer(s).\r\n */\r\n public final byte[] toByteArray()\r\n {\r\n LinkedBuffer node = head;\r\n int offset = 0, len;\r\n final byte[] buf = new byte[size];\r\n do\r\n {\r\n if ((len = node.offset - node.start) > 0)\r\n {\r\n System.arraycopy(node.buffer, node.start, buf, offset, len);\r\n offset += len;\r\n }\r\n } while ((node = node.next) != null);\r\n\r\n return buf;\r\n }\r\n\r\n protected int flush(byte[] buf, int offset, int len) throws IOException\r\n {\r\n if (flushHandler != null)\r\n return flushHandler.flush(this, buf, offset, len);\r\n\r\n out.write(buf, offset, len);\r\n return offset;\r\n }\r\n\r\n protected int flush(byte[] buf, int offset, int len,\r\n byte[] next, int nextoffset, int nextlen) throws IOException\r\n {\r\n if (flushHandler != null)\r\n return flushHandler.flush(this, buf, offset, len, next, nextoffset, nextlen);\r\n\r\n out.write(buf, offset, len);\r\n out.write(next, nextoffset, nextlen);\r\n return offset;\r\n }\r\n\r\n protected int flush(LinkedBuffer lb,\r\n byte[] buf, int offset, int len) throws IOException\r\n {\r\n if (flushHandler != null)\r\n return flushHandler.flush(this, lb, buf, offset, len);\r\n\r\n out.write(buf, offset, len);\r\n return lb.start;\r\n }\r\n\r\n}", "file_name": "WriteSession.java", "human_label": "Copy bytes from LinkedBuffer and return.", "level": "project_runnable", "lineno": "137", "name": "toByteArray", "oracle_context": "{ \"apis\" : \"[arraycopy]\", \"classes\" : \"[LinkedBuffer, byte[]]\", \"vars\" : \"[start, buffer, next, head, size]\" }", "package": "io.protostuff", "project": "protostuff-master" }, { "_id": "6367667d1a6d9265ec017401", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.io.StringWriter;\\nimport java.io.Writer;\\nimport java.util.Locale;\\nStringEscapeUtils();\\nescapeJava(Writer out,String str);\\nescapeJavaScript(String str);\\nescapeJavaScript(Writer out,String str);\\nescapeJavaStyleString(String str,boolean escapeSingleQuotes,boolean escapeForwardSlash);\\nescapeJavaStyleString(Writer out,String str,boolean escapeSingleQuote,boolean escapeForwardSlash);\\nhex(char ch);\\nunescapeJava(String str);\\nunescapeJava(Writer out,String str);\\nunescapeJavaScript(String str);\\nunescapeJavaScript(Writer out,String str);\\nescapeJava(String str);\\n\", \"repo_level\" : \"\" }", "class_name": "StringEscapeUtils", "code": "public static String unescapeJava(String str) throws Exception {\n if (str == null) {\n return null;\n }\n StringWriter writer=new StringWriter(str.length());\n unescapeJava(writer,str);\n return writer.toString();\n}\n", "docstring": "/** \n *

Unescapes any Java literals found in the String. For example, it will turn a sequence of '\\' and 'n' into a newline character, unless the '\\' is preceded by another '\\'.

\n * @param str the String to unescape, may be null\n * @return a new unescaped String, null if null string input\n */\n", "end_lineno": "300", "file_content": "/*\n* Licensed to the Apache Software Foundation (ASF) under one or more\n* contributor license agreements. See the NOTICE file distributed with\n* this work for additional information regarding copyright ownership.\n* The ASF licenses this file to You under the Apache License, Version 2.0\n* (the \"License\"); you may not use this file except in compliance with\n* the License. You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n* Modified from original form by Tim Fox\n*/\n/*\n * Copyright 2021 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\npackage org.atmosphere.util;\n\n\nimport java.io.IOException;\nimport java.io.StringWriter;\nimport java.io.Writer;\nimport java.util.Locale;\n\n/**\n *\n * Adapted from Apache Commons code\n *\n *\n *

Escapes and unescapes Strings for\n * Java, Java Script, HTML, XML, and SQL.

\n *

\n *

#ThreadSafe#

\n *\n * @author Apache Software Foundation\n * @author Apache Jakarta Turbine\n * @author Purple Technology\n * @author Alexander Day Chaffee\n * @author Antony Riley\n * @author Helge Tesgaard\n * @author Sean Brown\n * @author Gary Gregory\n * @author Phil Steitz\n * @author Pete Gieser\n * @version $Id: StringEscapeUtils.java 1057072 2011-01-10 01:55:57Z niallp $\n * @since 2.0\n */\npublic class StringEscapeUtils {\n\n /**\n *

StringEscapeUtils instances should NOT be constructed in\n * standard programming.

\n *

\n *

Instead, the class should be used as:\n *

StringEscapeUtils.escapeJava(\"foo\");

\n *

\n *

This constructor is public to permit tools that require a JavaBean\n * instance to operate.

\n */\n public StringEscapeUtils() {\n super();\n }\n\n // Java and JavaScript\n //--------------------------------------------------------------------------\n\n /**\n *

Escapes the characters in a String using Java String rules.

\n *

\n *

Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

\n *

\n *

So a tab becomes the characters '\\\\' and\n * 't'.

\n *

\n *

The only difference between Java strings and JavaScript strings\n * is that in JavaScript, a single quote must be escaped.

\n *

\n *

Example:\n *

\n   * input string: He didn't say, \"Stop!\"\n   * output string: He didn't say, \\\"Stop!\\\"\n   * 
\n *

\n *\n * @param str String to escape values in, may be null\n * @return String with escaped values, null if null string input\n */\n public static String escapeJava(String str) throws Exception {\n return escapeJavaStyleString(str, false, false);\n }\n\n /**\n *

Escapes the characters in a String using Java String rules to\n * a Writer.

\n *

\n *

A null string input has no effect.

\n *\n * @param out Writer to write escaped string into\n * @param str String to escape values in, may be null\n * @throws IllegalArgumentException if the Writer is null\n * @throws IOException if error occurs on underlying Writer\n * @see #escapeJava(java.lang.String)\n */\n public static void escapeJava(Writer out, String str) throws IOException {\n escapeJavaStyleString(out, str, false, false);\n }\n\n /**\n *

Escapes the characters in a String using JavaScript String rules.

\n *

Escapes any values it finds into their JavaScript String form.\n * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

\n *

\n *

So a tab becomes the characters '\\\\' and\n * 't'.

\n *

\n *

The only difference between Java strings and JavaScript strings\n * is that in JavaScript, a single quote must be escaped.

\n *

\n *

Example:\n *

\n   * input string: He didn't say, \"Stop!\"\n   * output string: He didn\\'t say, \\\"Stop!\\\"\n   * 
\n *

\n *\n * @param str String to escape values in, may be null\n * @return String with escaped values, null if null string input\n */\n public static String escapeJavaScript(String str) throws Exception {\n return escapeJavaStyleString(str, true, true);\n }\n\n /**\n *

Escapes the characters in a String using JavaScript String rules\n * to a Writer.

\n *

\n *

A null string input has no effect.

\n *\n * @param out Writer to write escaped string into\n * @param str String to escape values in, may be null\n * @throws IllegalArgumentException if the Writer is null\n * @throws IOException if error occurs on underlying Writer\n * @see #escapeJavaScript(java.lang.String)\n */\n public static void escapeJavaScript(Writer out, String str) throws Exception {\n escapeJavaStyleString(out, str, true, true);\n }\n\n /**\n *

Worker method for the {@link #escapeJavaScript(String)} method.

\n *\n * @param str String to escape values in, may be null\n * @param escapeSingleQuotes escapes single quotes if true\n * @param escapeForwardSlash TODO\n * @return the escaped string\n */\n private static String escapeJavaStyleString(String str, boolean escapeSingleQuotes, boolean escapeForwardSlash)\n throws Exception {\n if (str == null) {\n return null;\n }\n StringWriter writer = new StringWriter(str.length() * 2);\n escapeJavaStyleString(writer, str, escapeSingleQuotes, escapeForwardSlash);\n return writer.toString();\n }\n\n /**\n *

Worker method for the {@link #escapeJavaScript(String)} method.

\n *\n * @param out write to receieve the escaped string\n * @param str String to escape values in, may be null\n * @param escapeSingleQuote escapes single quotes if true\n * @param escapeForwardSlash TODO\n * @throws IOException if an IOException occurs\n */\n private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote,\n boolean escapeForwardSlash) throws IOException {\n if (out == null) {\n throw new IllegalArgumentException(\"The Writer must not be null\");\n }\n if (str == null) {\n return;\n }\n int sz;\n sz = str.length();\n for (int i = 0; i < sz; i++) {\n char ch = str.charAt(i);\n\n // handle unicode\n if (ch > 0xfff) {\n out.write(\"\\\\u\" + hex(ch));\n } else if (ch > 0xff) {\n out.write(\"\\\\u0\" + hex(ch));\n } else if (ch > 0x7f) {\n out.write(\"\\\\u00\" + hex(ch));\n } else if (ch < 32) {\n switch (ch) {\n case '\\b':\n out.write('\\\\');\n out.write('b');\n break;\n case '\\n':\n out.write('\\\\');\n out.write('n');\n break;\n case '\\t':\n out.write('\\\\');\n out.write('t');\n break;\n case '\\f':\n out.write('\\\\');\n out.write('f');\n break;\n case '\\r':\n out.write('\\\\');\n out.write('r');\n break;\n default:\n if (ch > 0xf) {\n out.write(\"\\\\u00\" + hex(ch));\n } else {\n out.write(\"\\\\u000\" + hex(ch));\n }\n break;\n }\n } else {\n switch (ch) {\n case '\\'':\n if (escapeSingleQuote) {\n out.write('\\\\');\n }\n out.write('\\'');\n break;\n case '\"':\n out.write('\\\\');\n out.write('\"');\n break;\n case '\\\\':\n out.write('\\\\');\n out.write('\\\\');\n break;\n case '/':\n if (escapeForwardSlash) {\n out.write('\\\\');\n }\n out.write('/');\n break;\n default:\n out.write(ch);\n break;\n }\n }\n }\n }\n\n /**\n *

Returns an upper case hexadecimal String for the given\n * character.

\n *\n * @param ch The character to convert.\n * @return An upper case hexadecimal String\n */\n private static String hex(char ch) {\n return Integer.toHexString(ch).toUpperCase(Locale.ENGLISH);\n }\n\n /**\n *

Unescapes any Java literals found in the String.\n * For example, it will turn a sequence of '\\' and\n * 'n' into a newline character, unless the '\\'\n * is preceded by another '\\'.

\n *\n * @param str the String to unescape, may be null\n * @return a new unescaped String, null if null string input\n */\n public static String unescapeJava(String str) throws Exception {\n if (str == null) {\n return null;\n }\n StringWriter writer = new StringWriter(str.length());\n unescapeJava(writer, str);\n return writer.toString();\n }\n\n /**\n *

Unescapes any Java literals found in the String to a\n * Writer.

\n *

\n *

For example, it will turn a sequence of '\\' and\n * 'n' into a newline character, unless the '\\'\n * is preceded by another '\\'.

\n *

\n *

A null string input has no effect.

\n *\n * @param out the Writer used to output unescaped characters\n * @param str the String to unescape, may be null\n * @throws IllegalArgumentException if the Writer is null\n * @throws IOException if error occurs on underlying Writer\n */\n public static void unescapeJava(Writer out, String str) throws Exception {\n if (out == null) {\n throw new IllegalArgumentException(\"The Writer must not be null\");\n }\n if (str == null) {\n return;\n }\n int sz = str.length();\n StringBuilder unicode = new StringBuilder();\n boolean hadSlash = false;\n boolean inUnicode = false;\n for (int i = 0; i < sz; i++) {\n char ch = str.charAt(i);\n if (inUnicode) {\n // if in unicode, then we're reading unicode\n // values in somehow\n unicode.append(ch);\n if (unicode.length() == 4) {\n // unicode now contains the four hex digits\n // which represents our unicode character\n int value = Integer.parseInt(unicode.toString(), 16);\n out.write((char) value);\n unicode.setLength(0);\n inUnicode = false;\n hadSlash = false;\n }\n continue;\n }\n if (hadSlash) {\n // handle an escaped value\n hadSlash = false;\n switch (ch) {\n case '\\\\':\n out.write('\\\\');\n break;\n case '\\'':\n out.write('\\'');\n break;\n case '\\\"':\n out.write('\"');\n break;\n case 'r':\n out.write('\\r');\n break;\n case 'f':\n out.write('\\f');\n break;\n case 't':\n out.write('\\t');\n break;\n case 'n':\n out.write('\\n');\n break;\n case 'b':\n out.write('\\b');\n break;\n case 'u': {\n // uh-oh, we're in unicode country....\n inUnicode = true;\n break;\n }\n default:\n out.write(ch);\n break;\n }\n continue;\n } else if (ch == '\\\\') {\n hadSlash = true;\n continue;\n }\n out.write(ch);\n }\n if (hadSlash) {\n // then we're in the weird case of a \\ at the end of the\n // string, let's output it anyway.\n out.write('\\\\');\n }\n }\n\n /**\n *

Unescapes any JavaScript literals found in the String.

\n *

\n *

For example, it will turn a sequence of '\\' and 'n'\n * into a newline character, unless the '\\' is preceded by another\n * '\\'.

\n *\n * @param str the String to unescape, may be null\n * @return A new unescaped String, null if null string input\n * @see #unescapeJava(String)\n */\n public static String unescapeJavaScript(String str) throws Exception {\n return unescapeJava(str);\n }\n\n /**\n *

Unescapes any JavaScript literals found in the String to a\n * Writer.

\n *

\n *

For example, it will turn a sequence of '\\' and 'n'\n * into a newline character, unless the '\\' is preceded by another\n * '\\'.

\n *

\n *

A null string input has no effect.

\n *\n * @param out the Writer used to output unescaped characters\n * @param str the String to unescape, may be null\n * @throws IllegalArgumentException if the Writer is null\n * @throws IOException if error occurs on underlying Writer\n * @see #unescapeJava(Writer, String)\n */\n public static void unescapeJavaScript(Writer out, String str) throws Exception {\n unescapeJava(out, str);\n }\n\n}\n\n\n\n\n\n", "file_name": "StringEscapeUtils.java", "human_label": "Unescapes Java that found in the String.", "level": "slib_runnable", "lineno": "284", "name": "unescapeJava", "oracle_context": "{ \"apis\" : \"[length, toString]\", \"classes\" : \"[StringWriter]\", \"vars\" : \"[]\" }", "package": "org.atmosphere.util", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636766f01a6d9265ec01763e", "all_context": "{ \"class_level\" : \"import java.io.ByteArrayOutputStream;\\nimport java.io.IOException;\\nimport java.io.UnsupportedEncodingException;\\nimport java.util.HashMap;\\nimport java.util.Locale;\\nimport java.util.Map;\\nString US_ASCII_CHARSET;\\nString BASE64_ENCODING_MARKER;\\nString QUOTEDPRINTABLE_ENCODING_MARKER;\\nString ENCODED_TOKEN_MARKER;\\nString ENCODED_TOKEN_FINISHER;\\nString LINEAR_WHITESPACE;\\nMap MIME2JAVA;\\nMimeUtility();\\ndecodeWord(String word);\\njavaCharset(String charset);\\ndecodeText(String text);\\n\", \"repo_level\" : \"\" }", "class_name": "MimeUtility", "code": "private static String javaCharset(String charset){\n if (charset == null) {\n return null;\n }\n String mappedCharset=MIME2JAVA.get(charset.toLowerCase(Locale.ENGLISH));\n if (mappedCharset == null) {\n return charset;\n }\n return mappedCharset;\n}\n", "docstring": "/** \n * Translate a MIME standard character set name into the Java equivalent.\n * @param charset The MIME standard name.\n * @return The Java equivalent for this name.\n */\n", "end_lineno": "248", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.web.upload.util;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.UnsupportedEncodingException;\nimport java.util.HashMap;\nimport java.util.Locale;\nimport java.util.Map;\n\n/**\n * Utility class to decode MIME texts.\n * @since 1.3\n */\npublic final class MimeUtility {\n /**\n * The {@code US-ASCII} charset identifier constant.\n */\n private static final String US_ASCII_CHARSET = \"US-ASCII\";\n /**\n * The marker to indicate text is encoded with BASE64 algorithm.\n */\n private static final String BASE64_ENCODING_MARKER = \"B\";\n /**\n * The marker to indicate text is encoded with QuotedPrintable algorithm.\n */\n private static final String QUOTEDPRINTABLE_ENCODING_MARKER = \"Q\";\n /**\n * If the text contains any encoded tokens, those tokens will be marked with \"=?\".\n */\n private static final String ENCODED_TOKEN_MARKER = \"=?\";\n /**\n * If the text contains any encoded tokens, those tokens will terminate with \"=?\".\n */\n private static final String ENCODED_TOKEN_FINISHER = \"?=\";\n /**\n * The linear whitespace chars sequence.\n */\n private static final String LINEAR_WHITESPACE = \" \\t\\r\\n\";\n /**\n * Mappings between MIME and Java charset.\n */\n private static final Map MIME2JAVA = new HashMap();\n\n static {\n MIME2JAVA.put(\"iso-2022-cn\", \"ISO2022CN\");\n MIME2JAVA.put(\"iso-2022-kr\", \"ISO2022KR\");\n MIME2JAVA.put(\"utf-8\", \"UTF8\");\n MIME2JAVA.put(\"utf8\", \"UTF8\");\n MIME2JAVA.put(\"ja_jp.iso2022-7\", \"ISO2022JP\");\n MIME2JAVA.put(\"ja_jp.eucjp\", \"EUCJIS\");\n MIME2JAVA.put(\"euc-kr\", \"KSC5601\");\n MIME2JAVA.put(\"euckr\", \"KSC5601\");\n MIME2JAVA.put(\"us-ascii\", \"ISO-8859-1\");\n MIME2JAVA.put(\"x-us-ascii\", \"ISO-8859-1\");\n }\n\n /**\n * Hidden constructor, this class must not be instantiated.\n */\n private MimeUtility() {\n // do nothing\n }\n\n /**\n * Decode a string of text obtained from a mail header into\n * its proper form. The text generally will consist of a\n * string of tokens, some of which may be encoded using\n * base64 encoding.\n *\n * @param text The text to decode.\n *\n * @return The decoded text string.\n * @throws UnsupportedEncodingException if the detected encoding in the input text is not supported.\n */\n public static String decodeText(String text) throws UnsupportedEncodingException {\n // if the text contains any encoded tokens, those tokens will be marked with \"=?\". If the\n // source string doesn't contain that sequent, no decoding is required.\n if (text.indexOf(ENCODED_TOKEN_MARKER) < 0) {\n return text;\n }\n int offset = 0;\n int endOffset = text.length();\n int startWhiteSpace = -1;\n int endWhiteSpace = -1;\n StringBuilder decodedText = new StringBuilder(text.length());\n boolean previousTokenEncoded = false;\n while (offset < endOffset) {\n char ch = text.charAt(offset);\n // is this a whitespace character?\n if (LINEAR_WHITESPACE.indexOf(ch) != -1) { // whitespace found\n startWhiteSpace = offset;\n while (offset < endOffset) {\n // step over the white space characters.\n ch = text.charAt(offset);\n if (LINEAR_WHITESPACE.indexOf(ch) != -1) { // whitespace found\n offset++;\n } else {\n // record the location of the first non lwsp and drop down to process the\n // token characters.\n endWhiteSpace = offset;\n break;\n }\n }\n } else {\n // we have a word token. We need to scan over the word and then try to parse it.\n int wordStart = offset;\n while (offset < endOffset) {\n // step over the non white space characters.\n ch = text.charAt(offset);\n if (LINEAR_WHITESPACE.indexOf(ch) == -1) { // not white space\n offset++;\n } else {\n break;\n }\n //NB: Trailing whitespace on these header strings will just be discarded.\n }\n // pull out the word token.\n String word = text.substring(wordStart, offset);\n // is the token encoded? decode the word\n if (word.startsWith(ENCODED_TOKEN_MARKER)) {\n try {\n // if this gives a parsing failure, treat it like a non-encoded word.\n String decodedWord = decodeWord(word);\n // are any whitespace characters significant? Append 'em if we've got 'em.\n if (!previousTokenEncoded && startWhiteSpace != -1) {\n decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));\n startWhiteSpace = -1;\n }\n // this is definitely a decoded token.\n previousTokenEncoded = true;\n // and add this to the text.\n decodedText.append(decodedWord);\n // we continue parsing from here...we allow parsing errors to fall through\n // and get handled as normal text.\n continue;\n } catch (IllegalArgumentException e) {\n // just ignore it, skip to next word\n }\n }\n // this is a normal token, so it doesn't matter what the previous token was. Add the white space\n // if we have it.\n if (startWhiteSpace != -1) {\n decodedText.append(text.substring(startWhiteSpace, endWhiteSpace));\n startWhiteSpace = -1;\n }\n // this is not a decoded token.\n previousTokenEncoded = false;\n decodedText.append(word);\n }\n }\n return decodedText.toString();\n }\n\n /**\n * Parse a string using the RFC 2047 rules for an \"encoded-word\"\n * type. This encoding has the syntax:\n *\n * encoded-word = \"=?\" charset \"?\" encoding \"?\" encoded-text \"?=\"\n *\n * @param word The possibly encoded word value.\n *\n * @return The decoded word.\n * @throws UnsupportedEncodingException\n */\n private static String decodeWord(String word) throws UnsupportedEncodingException {\n // encoded words start with the characters \"=?\". If this not an encoded word, we throw a\n // ParseException for the caller.\n if (!word.startsWith(ENCODED_TOKEN_MARKER)) {\n throw new UnsupportedEncodingException(\"Invalid RFC 2047 encoded-word: \" + word);\n }\n int charsetPos = word.indexOf('?', 2);\n if (charsetPos == -1) {\n throw new UnsupportedEncodingException(\"Missing charset in RFC 2047 encoded-word: \" + word);\n }\n // pull out the character set information (this is the MIME name at this point).\n String charset = word.substring(2, charsetPos).toLowerCase();\n // now pull out the encoding token the same way.\n int encodingPos = word.indexOf('?', charsetPos + 1);\n if (encodingPos == -1) {\n throw new UnsupportedEncodingException(\"Missing encoding in RFC 2047 encoded-word: \" + word);\n }\n String encoding = word.substring(charsetPos + 1, encodingPos);\n // and finally the encoded text.\n int encodedTextPos = word.indexOf(ENCODED_TOKEN_FINISHER, encodingPos + 1);\n if (encodedTextPos == -1) {\n throw new UnsupportedEncodingException(\"Missing encoded text in RFC 2047 encoded-word: \" + word);\n }\n String encodedText = word.substring(encodingPos + 1, encodedTextPos);\n // seems a bit silly to encode a null string, but easy to deal with.\n if (encodedText.length() == 0) {\n return \"\";\n }\n try {\n // the decoder writes directly to an output stream.\n ByteArrayOutputStream out = new ByteArrayOutputStream(encodedText.length());\n byte[] encodedData = encodedText.getBytes(US_ASCII_CHARSET);\n // Base64 encoded?\n if (encoding.equals(BASE64_ENCODING_MARKER)) {\n Base64Decoder.decode(encodedData, out);\n } else if (encoding.equals(QUOTEDPRINTABLE_ENCODING_MARKER)) { // maybe quoted printable.\n QuotedPrintableDecoder.decode(encodedData, out);\n } else {\n throw new UnsupportedEncodingException(\"Unknown RFC 2047 encoding: \" + encoding);\n }\n // get the decoded byte data and convert into a string.\n byte[] decodedData = out.toByteArray();\n return new String(decodedData, javaCharset(charset));\n } catch (IOException e) {\n throw new UnsupportedEncodingException(\"Invalid RFC 2047 encoding\");\n }\n }\n\n /**\n * Translate a MIME standard character set name into the Java\n * equivalent.\n *\n * @param charset The MIME standard name.\n *\n * @return The Java equivalent for this name.\n */\n private static String javaCharset(String charset) {\n // nothing in, nothing out.\n if (charset == null) {\n return null;\n }\n String mappedCharset = MIME2JAVA.get(charset.toLowerCase(Locale.ENGLISH));\n // if there is no mapping, then the original name is used. Many of the MIME character set\n // names map directly back into Java. The reverse isn't necessarily true.\n if (mappedCharset == null) {\n return charset;\n }\n return mappedCharset;\n }\n}\n", "file_name": "MimeUtility.java", "human_label": "Translate a MIME standard charset name into the Java equivalent.", "level": "class_runnable", "lineno": "228", "name": "javaCharset", "oracle_context": "{ \"apis\" : \"[get, toLowerCase]\", \"classes\" : \"[String, Locale]\", \"vars\" : \"[ENGLISH, MIME2JAVA]\" }", "package": "net.hasor.web.upload.util", "project": "hasor-master" }, { "_id": "6367676a1a6d9265ec0181bf", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static Object quoteIfString(Object obj){\n return (obj instanceof String ? quote((String)obj) : obj);\n}\n", "docstring": "/** \n * Turn the given Object into a String with single quotes if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),or the input object as-is if not a String\n */\n", "end_lineno": "455", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *
\n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
\n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Check whether an obj variable is of the String type.", "level": "class_runnable", "lineno": "446", "name": "quoteIfString", "oracle_context": "{ \"apis\" : \"[quote]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636767501a6d9265ec017e86", "all_context": "{ \"class_level\" : \"import org.jgrapht.alg.util.*;\\nimport java.util.*;\\nimport java.util.function.*;\\nListNodeImpl head;\\nint size;\\nint nextIndex;\\nListNodeImpl next;\\nListNodeImpl last;\\nint expectedModCount;\\nV value;\\nDoublyLinkedList list;\\nListNodeImpl next;\\nListNodeImpl prev;\\ntail();\\nsize();\\nclear();\\naddListNode(ListNodeImpl node);\\nmoveAllListNodes(DoublyLinkedList list);\\nremoveListNode(ListNodeImpl node);\\nlink(ListNodeImpl predecessor,ListNodeImpl successor);\\nlinkBefore(ListNodeImpl node,ListNodeImpl successor);\\nlinkLast(ListNodeImpl node);\\nlinkListIntoThisBefore(int index,DoublyLinkedList list);\\nunlink(ListNodeImpl node);\\naddNode(int index,ListNode node);\\naddNodeFirst(ListNode node);\\naddNodeLast(ListNode node);\\naddNodeBefore(ListNode node,ListNode successor);\\ngetFirstNode();\\ngetLastNode();\\ngetNode(int index);\\ngetNodeAt(int index);\\nindexOfNode(ListNode node);\\ncontainsNode(ListNode node);\\nremoveNode(ListNode node);\\nnodeOf(Object element);\\nlastNodeOf(Object element);\\nsearchNode(Supplier first,UnaryOperator next,Object element);\\naddElementFirst(E element);\\naddElementLast(E element);\\naddElementBeforeNode(ListNode successor,E element);\\nadd(int index,E element);\\nget(int index);\\nremove(int index);\\naddFirst(E e);\\naddLast(E e);\\nofferFirst(E e);\\nofferLast(E e);\\nremoveFirst();\\nremoveLast();\\npollFirst();\\npollLast();\\ngetFirst();\\ngetLast();\\npeekFirst();\\npeekLast();\\nremoveFirstOccurrence(Object o);\\nremoveLastOccurrence(Object o);\\noffer(E e);\\nremove();\\npoll();\\nelement();\\npeek();\\npush(E e);\\npop();\\ninvert();\\nmoveFrom(int index,DoublyLinkedList movedList);\\nappend(DoublyLinkedList movedList);\\nprepend(DoublyLinkedList movedList);\\ncircularIterator(E firstElement);\\nreverseCircularIterator(E firstElement);\\ndescendingIterator();\\niterator();\\nlistIterator();\\nlistIterator(int index);\\nlistIterator(E element);\\nnext();\\nnextNode();\\nprevious();\\npreviousNode();\\nListNodeIteratorImpl(int startIndex);\\nListNodeIteratorImpl(int startIndex,ListNodeImpl startNode);\\nhasNext();\\nhasPrevious();\\nnextIndex();\\npreviousIndex();\\nadd(E e);\\nset(E e);\\ncheckForComodification();\\nreverseIterator(ListNodeIterator listIterator);\\ngetValue();\\ngetNext();\\ngetPrev();\\nListNodeImpl(V value);\\ntoString();\\nisEmpty();\\n\", \"repo_level\" : \"\" }", "class_name": "DoublyLinkedList", "code": "@Override public ListNode previousNode(){\n checkForComodification();\n if (!hasPrevious()) {\n throw new NoSuchElementException();\n }\n last=next=next.prev;\n nextIndex--;\n return last;\n}\n", "docstring": "/** \n * {@inheritDoc}\n */\n", "end_lineno": "1237", "file_content": "/*\n * (C) Copyright 2018-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.util;\n\nimport org.jgrapht.alg.util.*;\n\nimport java.util.*;\nimport java.util.function.*;\n\n/**\n * {@code DoublyLinkedList} implements a doubly linked {@link List} data structure, that exposes its\n * {@link ListNode ListNodes} where the data is stored in.\n *

\n * An element holding {@code ListNode} can be removed or added to a {@code DoublyLinkedList} in\n * constant time O(1). Other methods that operate on {@code ListNodes} directly also have constant\n * runtime. This is also the case for methods that operate on the first(head) and last(tail) node or\n * element. Random access methods have a runtime O(n) that is linearly dependent on the size of the\n * {@code DoublyLinkedList}.\n *

\n *

\n * A {@code DoublyLinkedList} supports {@code null} elements but does not support\n * {@code null ListNodes}. This class is not thread safe and needs to be synchronized externally if\n * modified by concurrent threads.\n *

\n *

\n * The iterators over this list have a fail-fast behavior meaning that they throw a\n * {@link ConcurrentModificationException} after they detect a structural modification of the list,\n * that they're not responsible for.\n *

\n *

\n * This class is similar to {@link LinkedList}. The general difference is that the {@code ListNodes}\n * of this {@code List} are accessible and can be removed or added directly. To ensure the integrity\n * of the {@code List} nodes of this List have a reference to the List they belong to. This\n * increases the memory occupied by this list implementation compared to {@code LinkedList} for the\n * same elements. Instances of {@code LinkedList.Node} have three references each (the element, next\n * and previous), instances of {@code DoublyLinkedList.ListNode} have four (the element, next,\n * previous and the list).\n *

\n *\n * @param the list element type\n * @author Timofey Chudakov\n * @author Hannes Wellmann\n */\npublic class DoublyLinkedList\n extends\n AbstractSequentialList\n implements\n Deque\n{\n /** The first element of the list, {@code null} if this list is empty. */\n private ListNodeImpl head = null;\n private int size;\n\n private ListNodeImpl tail()\n {\n return head.prev;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean isEmpty()\n {\n return head == null;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int size()\n {\n return size;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void clear()\n {\n if (!isEmpty()) {\n ListNodeImpl node = head;\n do {\n ListNodeImpl next = node.next;\n boolean removed = removeListNode(node); // clears all links of removed node\n assert removed;\n node = next;\n } while (node != head);\n\n head = null;\n assert size == 0;\n }\n }\n\n // internal modification methods\n\n /**\n * Adds the given {@link ListNode} to this {@code List}.\n *

\n * Sets the {@code list} reference of {@code node} to this list, increases this lists\n * {@code size} and {@code modcount} by one.\n *

\n * \n * @param node the node to add to this list\n * @throws IllegalArgumentException if {@code node} is already contained in this or another\n * {@code DoublyLinkedList}\n */\n private void addListNode(ListNodeImpl node)\n { // call this before any modification of this list is done\n if (node.list != null) {\n String list = (node.list == this) ? \"this\" : \"other\";\n throw new IllegalArgumentException(\n \"Node <\" + node + \"> already contained in \" + list + \" list\");\n }\n node.list = this;\n size++;\n modCount++;\n }\n\n /**\n * Atomically moves all {@link ListNode ListNodes} from {@code list} to this list as if each\n * node was removed with {@link #removeListNode(ListNodeImpl)} from {@code list} and\n * subsequently added to this list by {@link #addListNode(ListNodeImpl)}.\n */\n private void moveAllListNodes(DoublyLinkedList list)\n { // call this before any modification of this list is done\n\n for (ListNodeIteratorImpl it = list.new ListNodeIteratorImpl(0); it.hasNext();) {\n ListNodeImpl node = it.nextNode();\n assert node.list == list;\n node.list = this;\n }\n size += list.size;\n list.size = 0;\n modCount++;\n list.modCount++;\n }\n\n /**\n * Removes the given {@link ListNode} from this {@code List}, if it is contained in this\n * {@code List}.\n *

\n * If {@code node} is contained in this list, sets the {@code list}, {@code next} and\n * {@code prev} reference of {@code node} to {@code null} decreases this list's {@code size} and\n * increases the {@code modcount} by one.\n *

\n * \n * @param node the node to remove from this list\n * @return true if {@code node} was removed from this list, else false\n */\n private boolean removeListNode(ListNodeImpl node)\n { // call this before any modification of this list is done\n if (node.list == this) {\n\n node.list = null;\n node.next = null;\n node.prev = null;\n\n size--;\n modCount++;\n return true;\n }\n return false;\n }\n\n /**\n * Establishes the links between the given {@link ListNodeImpl nodes} in such a way that the\n * {@code predecessor} is linked before the {@code successor}.\n * \n * @param predecessor the first node linked before the other\n * @param successor the second node linked after the other\n */\n private void link(ListNodeImpl predecessor, ListNodeImpl successor)\n {\n predecessor.next = successor;\n successor.prev = predecessor;\n }\n\n /** Insert non null {@code node} before non null {@code successor} into the list. */\n private void linkBefore(ListNodeImpl node, ListNodeImpl successor)\n {\n addListNode(node);\n link(successor.prev, node);\n link(node, successor);\n }\n\n /** Insert non null {@code node} as last node into the list. */\n private void linkLast(ListNodeImpl node)\n {\n if (isEmpty()) { // node will be the first and only one\n addListNode(node);\n link(node, node); // self link\n head = node;\n } else {\n linkBefore(node, head);\n }\n }\n\n /** Insert non null {@code list} before node at {@code index} into the list. */\n private void linkListIntoThisBefore(int index, DoublyLinkedList list)\n {\n int previousSize = size;\n moveAllListNodes(list);\n\n // link list's node into this list\n if (previousSize == 0) {\n head = list.head; // head and tail already linked together\n } else {\n ListNodeImpl refNode = (index == previousSize) ? head : getNodeAt(index);\n\n ListNodeImpl listTail = list.tail();\n link(refNode.prev, list.head); // changes list.tail()\n link(listTail, refNode);\n\n if (index == 0) {\n head = list.head;\n }\n }\n // clear list but do not call list.clear(), since their nodes are still used\n list.head = null;\n }\n\n /** Remove the non null {@code node} from the list. */\n private boolean unlink(ListNodeImpl node)\n {\n ListNodeImpl prev = node.prev;\n ListNodeImpl next = node.next;\n if (removeListNode(node)) { // clears prev and next of node\n if (size == 0) {\n head = null;\n } else {\n // list is circular, don't have to worry about null values\n link(prev, next);\n\n if (head == node) {\n head = next;\n }\n }\n return true;\n }\n return false;\n }\n\n // ----------------------------------------------------------------------------\n // public modification and access methods\n\n // ListNode methods:\n // Base methods to access, add and remove nodes to/from this list.\n // Used by all public methods if possible\n\n /**\n * Inserts the specified {@link ListNode node} at the specified position in this list.\n *

\n * This method has a linear runtime complexity O(n) that depends linearly on the distance of the\n * index to the nearest end. Adding {@code node} as first or last takes only constant time O(1).\n *

\n * \n * @param index index at which the specified {@code node} is to be inserted\n * @param node the node to add\n * @throws IndexOutOfBoundsException if the index is out of range\n * ({@code index < 0 || index > size()})\n * @throws IllegalArgumentException if {@code node} is already part of this or another\n * {@code DoublyLinkedList}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public void addNode(int index, ListNode node)\n {\n ListNodeImpl nodeImpl = (ListNodeImpl) node;\n if (index == size) { // also true if this is empty\n linkLast(nodeImpl);\n } else {\n ListNodeImpl successor = index == 0 ? head : getNodeAt(index);\n linkBefore(nodeImpl, successor);\n if (head == successor) {\n head = nodeImpl;\n }\n }\n }\n\n /**\n * Inserts the specified {@link ListNode node} at the front of this list.\n *

\n * This method has constant runtime complexity O(1).\n *

\n * \n * @param node the node to add\n * @throws IllegalArgumentException if {@code node} is already part of this or another\n * {@code DoublyLinkedList}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public void addNodeFirst(ListNode node)\n {\n addNode(0, node);\n }\n\n /**\n * Inserts the specified {@link ListNode node} at the end of this list.\n *

\n * This method has constant runtime complexity O(1).\n *

\n * \n * @param node the node to add\n * @throws IllegalArgumentException if {@code node} is already part of this or another\n * {@code DoublyLinkedList}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public void addNodeLast(ListNode node)\n {\n addNode(size, node);\n }\n\n /**\n * Inserts the specified {@link ListNode node} before the specified {@code successor} in this\n * list.\n *

\n * This method has constant runtime complexity O(1).\n *

\n * \n * @param node the node to add\n * @param successor {@code ListNode} before which the {@code node} is inserted\n * @throws IllegalArgumentException if {@code node} is already contained in this or another\n * {@code DoublyLinkedList} or {@code successor} is not contained in this list\n * @throws NullPointerException if {@code successor} or {@code node} is {@code null}\n */\n public void addNodeBefore(ListNode node, ListNode successor)\n {\n ListNodeImpl successorImpl = (ListNodeImpl) successor;\n ListNodeImpl nodeImpl = (ListNodeImpl) node;\n\n if (successorImpl.list != this) {\n throw new IllegalArgumentException(\"Node <\" + successorImpl + \"> not in this list\");\n }\n linkBefore(nodeImpl, successorImpl);\n if (head == successorImpl) {\n head = nodeImpl;\n }\n }\n\n /**\n * Returns the first {@link ListNode node} of this list.\n *

\n * This method has constant runtime complexity O(1).\n *

\n * \n * @return the first {@code ListNode} of this list\n * @throws NoSuchElementException if this list is empty\n */\n public ListNode getFirstNode()\n {\n if (isEmpty()) {\n throw new NoSuchElementException();\n }\n return head;\n }\n\n /**\n * Returns the last {@link ListNode node} of this list.\n *

\n * This method has constant runtime complexity O(1).\n *

\n * \n * @return the last {@code ListNode} of this list\n * @throws NoSuchElementException if this list is empty\n */\n public ListNode getLastNode()\n {\n if (isEmpty()) {\n throw new NoSuchElementException();\n }\n return tail();\n }\n\n /**\n * Returns the {@link ListNode node} at the specified position in this list.\n *

\n * This method has linear runtime complexity O(n).\n *

\n * \n * @param index index of the {@code ListNode} to return\n * @return the {@code ListNode} at the specified position in this list\n * @throws IndexOutOfBoundsException if the index is out of range\n * ({@code index < 0 || index >= size()})\n */\n public ListNode getNode(int index)\n {\n return getNodeAt(index);\n }\n\n /**\n * Returns the {@link ListNodeImpl node} at the specified position in this list.\n * \n * @param index index of the {@code ListNodeImpl} to return\n * @return the {@code ListNode} at the specified position in this list\n * @throws IndexOutOfBoundsException if the index is out of range\n * ({@code index < 0 || index >= size()})\n */\n private ListNodeImpl getNodeAt(int index)\n {\n if (index < 0 || size <= index) {\n throw new IndexOutOfBoundsException(\"Index: \" + index);\n }\n ListNodeImpl node;\n if (index < size / 2) {\n node = head;\n for (int i = 0; i < index; i++) {\n node = node.next;\n }\n } else {\n node = tail();\n for (int i = size - 1; index < i; i--) {\n node = node.prev;\n }\n }\n return node;\n }\n\n /**\n * Returns the index of the specified {@link ListNode node} in this list, or -1 if this list\n * does not contain the {@code node}.\n *

\n * More formally, returns the index {@code i} such that {@code node == getNode(i)}, or -1 if\n * there is no such index. Because a {@code ListNode} is contained in at most one list exactly\n * once, the returned index (if not -1) is the only occurrence of that {@code node}.\n *

\n *

\n * This method has linear runtime complexity O(n) to find {@code node} but returns in constant\n * time O(1) if {@code node} is not {@link #containsNode(ListNode) contained} in this list.\n *

\n * \n * @param node the node to search for\n * @return the index of the specified {@code node} in this list, or -1 if this list does not\n * contain {@code node}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public int indexOfNode(ListNode node)\n {\n if (!containsNode(node)) {\n return -1;\n }\n ListNodeImpl current = head;\n for (int i = 0; i < size; i++) {\n if (current == node) {\n return i;\n }\n current = current.next;\n }\n // should never happen:\n throw new IllegalStateException(\"Node contained in list not found: \" + node);\n }\n\n /**\n * Returns true if this {@code DoublyLinkedList} contains the specified {@link ListNode}.\n *

\n * This method has constant runtime complexity O(1).\n *

\n * \n * @param node the node whose presence in this {@code DoublyLinkedList} is to be tested\n * @return true if this {@code DoublyLinkedList} contains the {@link ListNode}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public boolean containsNode(ListNode node)\n {\n return ((ListNodeImpl) node).list == this;\n }\n\n /**\n * Removes the {@link ListNode node} from this list. Returns true if {@code node} was in this\n * list and is now removed. If {@code node} is not contained in this list, the list is left\n * unchanged.\n *

\n * This method has constant runtime complexity O(1).\n *

\n *\n * @param node the node to remove from this list\n * @return true if node was removed from this list\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public boolean removeNode(ListNode node)\n {\n return unlink((ListNodeImpl) node);\n }\n\n /**\n * Returns the first {@link ListNode node} holding the specified {@code element} in this list.\n * More formally, returns the first {@code ListNode} such that\n * {@code Objects.equals(element, node.getValue())}, or {@code null} if there is no such node.\n *

\n * This method has linear runtime complexity O(n).\n *

\n * \n * @param element the element whose {@code ListNode} is to return\n * @return the first {@code ListNode} holding the {@code element} or null if no node was found\n */\n public ListNode nodeOf(Object element)\n {\n return searchNode(() -> head, n -> n.next, element).getFirst();\n }\n\n /**\n * Returns the last {@link ListNode node} holding the specified {@code element} in this list.\n * More formally, returns the last {@code ListNode} such that\n * {@code Objects.equals(element, node.getValue())}, or {@code null} if there is no such node.\n *

\n * This method has linear runtime complexity O(n).\n *

\n * \n * @param element the element whose {@code ListNode} is to return\n * @return the last {@code ListNode} holding the {@code element} or null if no node was found\n */\n public ListNode lastNodeOf(Object element)\n {\n return searchNode(this::tail, n -> n.prev, element).getFirst();\n }\n\n /**\n * Returns a {@link Pair} of the first encountered {@link ListNode} in this list, whose\n * {@code value} is equal to the given {@code element}, and its index. Or if this list does not\n * contain such node a Pair of {@code null} and {@code -1};\n *

\n * The search starts at the node supplied by {@code first} and advances in the direction induced\n * by the specified {@code next} operator.\n *

\n * \n * @param first supplier of the first node to check if this list is not empty\n * @param next {@code Function} to get from the current node the next node to check\n * @param element the element for that the first node with equal value is searched.\n * @return a {@link Pair} of the first encountered {@code ListNode} holding a {@code value}\n * equal to {@code element} and its index, or if no such node was found a\n * {@code Pair.of(null, -1)}\n */\n private Pair, Integer> searchNode(\n Supplier> first, UnaryOperator> next, Object element)\n {\n if (!isEmpty()) {\n int index = 0;\n ListNodeImpl firstNode = first.get();\n ListNodeImpl node = firstNode;\n do {\n if (Objects.equals(node.value, element)) {\n return Pair.of(node, index);\n }\n index++;\n node = next.apply(node);\n } while (node != firstNode);\n }\n return Pair.of(null, -1);\n }\n\n /**\n * Inserts the specified element at the front of this list. Returns the {@link ListNode}\n * allocated to store the {@code value}. The returned {@code ListNode} is the new head of the\n * list.\n *

\n * This method is equivalent to {@link #addFirst(Object)} but returns the allocated\n * {@code ListNode}.\n *

\n * \n * @param element the element to add\n * @return the {@code ListNode} allocated to store the {@code value}\n */\n public ListNode addElementFirst(E element)\n {\n ListNode node = new ListNodeImpl<>(element);\n addNode(0, node);\n return node;\n }\n\n /**\n * Inserts the specified element at the end of this list. Returns the {@link ListNode} allocated\n * to store the {@code value}. The returned {@code ListNode} is the new tail of the list.\n *

\n * This method is equivalent to {@link #addLast(Object)} but returns the allocated\n * {@code ListNode}.\n *

\n * \n * @param element the element to add\n * @return the {@code ListNode} allocated to store the {@code value}\n */\n public ListNode addElementLast(E element)\n {\n ListNode node = new ListNodeImpl<>(element);\n addNode(size, node);\n return node;\n }\n\n /**\n * Inserts the specified element before the specified {@link ListNode successor} in this list.\n * Returns the {@code ListNode} allocated to store the {@code value}.\n *\n * @param successor {@code ListNode} before which the node holding {@code value} is inserted\n * @param element the element to add\n * @return the {@code ListNode} allocated to store the {@code value}\n * @throws IllegalArgumentException if {@code successor} is not contained in this list\n * @throws NullPointerException if {@code successor} is {@code null}\n */\n public ListNode addElementBeforeNode(ListNode successor, E element)\n {\n ListNode node = new ListNodeImpl<>(element);\n addNodeBefore(node, successor);\n return node;\n }\n\n // List methods (shortcut for most commonly used methods to avoid iterator creation)\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void add(int index, E element)\n {\n if (index == size) { // also true if this is empty\n addElementLast(element);\n } else {\n addElementBeforeNode(getNode(index), element);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E get(int index)\n {\n return getNodeAt(index).value;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E remove(int index)\n {\n ListNode node = getNode(index);\n removeNode(node);\n return node.getValue();\n }\n\n // Deque methods\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void addFirst(E e)\n {\n addElementFirst(e);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void addLast(E e)\n {\n addElementLast(e);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean offerFirst(E e)\n {\n addElementFirst(e);\n return true;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean offerLast(E e)\n {\n addElementLast(e);\n return true;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E removeFirst()\n {\n if (isEmpty()) {\n throw new NoSuchElementException();\n }\n\n ListNode node = head;\n removeNode(node); // changes head\n return node.getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E removeLast()\n {\n if (isEmpty()) {\n throw new NoSuchElementException();\n }\n\n ListNode node = tail();\n removeNode(node); // changes tail\n return node.getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E pollFirst()\n {\n if (isEmpty()) {\n return null;\n }\n ListNode node = head;\n removeNode(node); // changes head\n return node.getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E pollLast()\n {\n if (isEmpty()) {\n return null;\n }\n ListNode node = tail();\n removeNode(node); // changes tail()\n return node.getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E getFirst()\n {\n return getFirstNode().getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E getLast()\n {\n return getLastNode().getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E peekFirst()\n {\n return isEmpty() ? null : getFirst();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E peekLast()\n {\n return isEmpty() ? null : getLast();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean removeFirstOccurrence(Object o)\n {\n ListNode node = nodeOf(o);\n if (node != null) {\n removeNode(node);\n return true;\n }\n return false;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean removeLastOccurrence(Object o)\n {\n ListNode node = lastNodeOf(o);\n if (node != null) {\n removeNode(node);\n return true;\n }\n return false;\n }\n\n // Queue methods\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean offer(E e)\n {\n return offerLast(e);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E remove()\n {\n return removeFirst();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E poll()\n {\n return pollFirst();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E element()\n {\n return getFirst();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E peek()\n {\n return peekFirst();\n }\n\n // Stack methods\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void push(E e)\n {\n addFirst(e);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E pop()\n {\n return removeFirst();\n }\n\n // special bulk methods\n\n /**\n * Inverts the list. For instance, calling this method on the list $(a,b,c,\\dots,x,y,z)$ will\n * result in the list $(z,y,x,\\dots,c,b,a)$. This method does only pointer manipulation, meaning\n * that all the list nodes allocated for the previously added elements are valid after this\n * method finishes.\n */\n public void invert()\n {\n if (size < 2) {\n return;\n }\n ListNodeImpl newHead = tail();\n ListNodeImpl current = head;\n do {\n ListNodeImpl next = current.next;\n\n current.next = current.prev;\n current.prev = next;\n\n current = next;\n } while (current != head);\n head = newHead;\n ++modCount;\n }\n\n /**\n * Moves all {@link ListNode ListNodes} of the given {@code sourceList} to this list and inserts\n * them all before the node previously at the given position. All the {@code nodes} of\n * {@code movedList} are moved to this list. When this method terminates this list contains all\n * nodes of {@code movedList} and {@code movedList} is empty.\n *\n * @param index index of the first element of {@code list} in this {@code list} after it was\n * added\n * @param movedList the {@code DoublyLinkedList} to move to this one\n * @throws NullPointerException if {@code movedList} is {@code null}\n */\n public void moveFrom(int index, DoublyLinkedList movedList)\n {\n linkListIntoThisBefore(index, movedList);\n }\n\n /**\n * Appends the {@code movedList} to the end of this list. All the elements from\n * {@code movedList} are transferred to this list, i.e. the {@code list} is empty after calling\n * this method.\n *\n * @param movedList the {@code DoublyLinkedList} to append to this one\n * @throws NullPointerException if {@code movedList} is {@code null}\n */\n public void append(DoublyLinkedList movedList)\n {\n moveFrom(size, movedList);\n }\n\n /**\n * Prepends the {@code movedList} to the beginning of this list. All the elements from\n * {@code movedList} are transferred to this list, i.e. the {@code movedList} is empty after\n * calling this method.\n *\n * @param movedList the {@code DoublyLinkedList} to prepend to this one\n * @throws NullPointerException if {@code movedList} is {@code null}\n */\n public void prepend(DoublyLinkedList movedList)\n {\n moveFrom(0, movedList);\n }\n\n // ----------------------------------------------------------------------------\n // (List)Iterators\n\n /**\n * Returns a {@link NodeIterator} that starts at the first {@link ListNode} of this list that is\n * equal to the specified {@code firstElement}, iterates in forward direction over the end of\n * this list until the first node.\n *

\n * The first call to {@link NodeIterator#nextNode()} returns the first {@code node} that holds a\n * value such that {@code Objects.equals(node.getValue, firstElement)} returns {@code true}. The\n * returned {@code NodeIterator} iterates in forward direction returning the respective next\n * element in subsequent calls to {@code next(Node)}. The returned iterator ignores the actual\n * bounds of this {@code DoublyLinkedList} and iterates until the node before the first one is\n * reached. Its {@link NodeIterator#hasNext() hasNext()} returns {@code false} if the next node\n * would be the first one.\n *

\n * \n * @param firstElement the element equal to the first {@code next()}\n * @return a circular {@code NodeIterator} iterating forward from {@code firstElement}\n */\n public NodeIterator circularIterator(E firstElement)\n {\n ListNodeImpl startNode = (ListNodeImpl) nodeOf(firstElement);\n if (startNode == null) {\n throw new NoSuchElementException();\n }\n return new ListNodeIteratorImpl(0, startNode);\n }\n\n /**\n * Returns a {@link NodeIterator} that starts at the first {@link ListNode} of this list that is\n * equal to the specified {@code firstElement}, iterates in reverse direction over the end of\n * this list until the first node.\n *

\n * The first call to {@link NodeIterator#nextNode()} returns the first {@code node} that holds a\n * value such that {@code Objects.equals(node.getValue, firstElement)} returns {@code true}. The\n * returned {@code NodeIterator} iterates in reverse direction returning the respective previous\n * element in subsequent calls to {@code next(Node)}. The returned iterator ignores the actual\n * bounds of this {@code DoublyLinkedList} and iterates until the node before the first one is\n * reached. Its {@link NodeIterator#hasNext() hasNext()} returns {@code false} if the next node\n * would be the first one.\n *

\n * \n * @param firstElement the element equal to the first {@code next()}\n * @return a circular {@code NodeIterator} iterating backwards from {@code firstElement}\n */\n public NodeIterator reverseCircularIterator(E firstElement)\n {\n ListNodeImpl startNode = (ListNodeImpl) nodeOf(firstElement);\n if (startNode == null) {\n throw new NoSuchElementException();\n }\n return reverseIterator(new ListNodeIteratorImpl(size, startNode.next));\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public NodeIterator descendingIterator()\n {\n return reverseIterator(listIterator(size));\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public NodeIterator iterator()\n {\n return listIterator();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeIterator listIterator()\n {\n return listIterator(0);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeIterator listIterator(int index)\n {\n return new ListNodeIteratorImpl(index);\n }\n\n /**\n * Returns a {@link ListNodeIterator} over the elements in this list (in proper sequence)\n * starting with the first {@link ListNode} whose value is equal to the specified\n * {@code element}.\n *\n * @param element the first element to be returned from the list iterator (by a call to the\n * {@code next} method)\n * @return a list iterator over the elements in this list (in proper sequence)\n * @throws NoSuchElementException if {@code element} is not in the list\n */\n public ListNodeIterator listIterator(E element)\n {\n Pair, Integer> startPair = searchNode(() -> head, n -> n.next, element);\n ListNodeImpl startNode = startPair.getFirst();\n int startIndex = startPair.getSecond();\n if (startNode == null) {\n throw new NoSuchElementException();\n }\n return new ListNodeIteratorImpl(startIndex, startNode);\n }\n\n /**\n * An extension of the {@link Iterator} interface for {@link DoublyLinkedList DoublyLinkedLists}\n * exposing their {@link ListNode ListNodes}.\n *\n * @param the list element type\n */\n public interface NodeIterator\n extends\n Iterator\n {\n /**\n * {@inheritDoc}\n */\n @Override\n default E next()\n {\n return nextNode().getValue();\n }\n\n /**\n * Returns the next {@link ListNode} in the list and advances the cursor position.\n *\n * @return the next {@code ListNode}\n * @see ListIterator#next()\n */\n ListNode nextNode();\n\n }\n\n /**\n * An extension of the {@link ListIterator} interface for {@link DoublyLinkedList\n * DoublyLinkedLists} exposing their {@link ListNode ListNodes}.\n *\n * @param the list element type\n */\n public interface ListNodeIterator\n extends\n ListIterator,\n NodeIterator\n {\n /**\n * {@inheritDoc}\n */\n @Override\n default E next()\n {\n return nextNode().getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n default E previous()\n {\n return previousNode().getValue();\n }\n\n /**\n * Returns the previous {@link ListNode} in the list and moves the cursor position\n * backwards.\n *\n * @return the previous {@code ListNode}\n * @see ListIterator#previous()\n */\n ListNode previousNode();\n\n }\n\n /**\n * An implementation of the {@link DoublyLinkedList.ListNodeIterator} interface.\n */\n private class ListNodeIteratorImpl\n implements\n ListNodeIterator\n {\n /** Index in this list of the ListNode returned next. */\n private int nextIndex;\n /** ListNode this iterator will return next. Null if this list is empty. */\n private ListNodeImpl next;\n /** ListNode this iterator returned last. */\n private ListNodeImpl last = null;\n\n /**\n * The number of modifications the list have had at the moment when this iterator was\n * created\n */\n private int expectedModCount = modCount;\n\n private ListNodeIteratorImpl(int startIndex)\n {\n this.nextIndex = startIndex;\n if (startIndex == size) {\n this.next = isEmpty() ? null : head;\n } else {\n this.next = getNodeAt(startIndex);\n }\n }\n\n private ListNodeIteratorImpl(int startIndex, ListNodeImpl startNode)\n {\n this.nextIndex = startIndex;\n this.next = startNode;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean hasNext()\n {\n return nextIndex < size;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean hasPrevious()\n {\n return nextIndex > 0;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int nextIndex()\n {\n return nextIndex;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int previousIndex()\n {\n return nextIndex - 1;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeImpl nextNode()\n {\n checkForComodification();\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n\n last = next;\n next = next.next;\n nextIndex++;\n return last;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNode previousNode()\n {\n checkForComodification();\n if (!hasPrevious()) {\n throw new NoSuchElementException();\n }\n\n last = next = next.prev;\n nextIndex--;\n return last;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void add(E e)\n {\n checkForComodification();\n\n if (nextIndex == size) {\n addElementLast(e); // sets head to new node of e if was empty\n if (size == 1) { // was empty\n next = head; // jump over head threshold, so cursor is at the end\n }\n } else {\n addElementBeforeNode(next, e);\n }\n last = null;\n nextIndex++;\n expectedModCount++;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void set(E e)\n {\n if (last == null) {\n throw new IllegalStateException();\n }\n checkForComodification();\n // replace node returned last with a new node holding e\n\n ListNode nextNode = last.next;\n boolean wasLast = last == tail();\n removeNode(last);\n if (wasLast) { // or the sole node\n last = (ListNodeImpl) addElementLast(e);\n } else {\n last = (ListNodeImpl) addElementBeforeNode(nextNode, e);\n }\n expectedModCount += 2; // because of unlink and add\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void remove()\n {\n if (last == null) {\n throw new IllegalStateException();\n }\n checkForComodification();\n\n ListNodeImpl lastsNext = last.next;\n removeNode(last);\n if (next == last) { // previousNode() called before\n // removed element after cursor (which would have been next)\n next = lastsNext;\n } else { // nextNode() called before\n // removed element before cursor (next is unaffected but the index decreases)\n nextIndex--;\n }\n last = null;\n expectedModCount++;\n }\n\n /**\n * Verifies that the list structure hasn't been changed since the iteration started\n */\n private void checkForComodification()\n {\n if (expectedModCount != modCount) {\n throw new ConcurrentModificationException();\n }\n }\n }\n\n /**\n * Returns a {@link NodeIterator} that iterates in reverse order, assuming the cursor of the\n * specified {@link ListNodeIterator} is behind the tail of the list.\n */\n private static NodeIterator reverseIterator(ListNodeIterator listIterator)\n {\n return new NodeIterator()\n {\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean hasNext()\n {\n return listIterator.hasPrevious();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNode nextNode()\n {\n return listIterator.previousNode();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void remove()\n {\n listIterator.remove();\n }\n };\n }\n\n /**\n * Container for the elements stored in a {@link DoublyLinkedList}.\n *

\n * A {@link ListNode} is either contained exactly once in exactly one {@code DoublyLinkedList}\n * or contained in no {@code DoublyLinkedList}.\n *

\n * \n * @param the type of the element stored in this node\n */\n public interface ListNode\n {\n /**\n * Returns the immutable value this {@code ListNode} contains.\n *\n * @return the value this list node contains\n */\n V getValue();\n\n /**\n * Returns the next node in the list structure with respect to this node\n *\n * @return the next node in the list structure with respect to this node\n */\n ListNode getNext();\n\n /**\n * Returns the previous node in the list structure with respect to this node\n *\n * @return the previous node in the list structure with respect to this node\n */\n ListNode getPrev();\n }\n\n /**\n * The default {@link ListNode} implementation that enables checks and enforcement of a single\n * container list policy.\n */\n private static class ListNodeImpl\n implements\n ListNode\n {\n private final V value;\n private DoublyLinkedList list = null;\n private ListNodeImpl next = null;\n private ListNodeImpl prev = null;\n\n /**\n * Creates new list node\n *\n * @param value the value this list node stores\n */\n ListNodeImpl(V value)\n {\n this.value = value;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n if (list == null) {\n return \" - \" + value + \" - \"; // not in a list\n } else {\n return prev.value + \" -> \" + value + \" -> \" + next.value;\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public V getValue()\n {\n return value;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeImpl getNext()\n {\n return next;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeImpl getPrev()\n {\n return prev;\n }\n }\n}\n", "file_name": "DoublyLinkedList.java", "human_label": "Returns the previous ListNode.", "level": "class_runnable", "lineno": "1223", "name": "previousNode", "oracle_context": "{ \"apis\" : \"[checkForComodification, hasPrevious, next, nextIndex]\", \"classes\" : \"[next]\", \"vars\" : \"[prev, last, next, nextIndex]\" }", "package": "org.jgrapht.util", "project": "jgrapht-master" }, { "_id": "636766f21a6d9265ec017667", "all_context": "{ \"class_level\" : \"import java.io.ByteArrayOutputStream;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nint SKIP_CODE;\\nint SKIP_DEBUG;\\nint SKIP_FRAMES;\\nint EXPAND_FRAMES;\\nint EXPAND_ASM_INSNS;\\nint INPUT_STREAM_DATA_CHUNK_SIZE;\\nbyte[] b;\\nbyte[] classFileBuffer;\\nint[] cpInfoOffsets;\\nString[] constantUtf8Values;\\nConstantDynamic[] constantDynamicValues;\\nint[] bootstrapMethodOffsets;\\nint maxStringLength;\\nint header;\\nClassReader(byte[] classFile);\\nClassReader(byte[] classFileBuffer,int classFileOffset,int classFileLength);\\nClassReader(byte[] classFileBuffer,int classFileOffset,boolean checkClassVersion);\\nClassReader(InputStream inputStream);\\nClassReader(String className);\\ngetAccess();\\ngetClassName();\\ngetSuperName();\\ngetInterfaces();\\naccept(ClassVisitor classVisitor,int parsingOptions);\\naccept(ClassVisitor classVisitor,Attribute[] attributePrototypes,int parsingOptions);\\nreadModuleAttributes(ClassVisitor classVisitor,Context context,int moduleOffset,int modulePackagesOffset,String moduleMainClass);\\nreadRecordComponent(ClassVisitor classVisitor,Context context,int recordComponentOffset);\\nreadField(ClassVisitor classVisitor,Context context,int fieldInfoOffset);\\nreadMethod(ClassVisitor classVisitor,Context context,int methodInfoOffset);\\nreadCode(MethodVisitor methodVisitor,Context context,int codeOffset);\\nreadLabel(int bytecodeOffset,Label[] labels);\\ncreateLabel(int bytecodeOffset,Label[] labels);\\ncreateDebugLabel(int bytecodeOffset,Label[] labels);\\nreadTypeAnnotations(MethodVisitor methodVisitor,Context context,int runtimeTypeAnnotationsOffset,boolean visible);\\ngetTypeAnnotationBytecodeOffset(int[] typeAnnotationOffsets,int typeAnnotationIndex);\\nreadTypeAnnotationTarget(Context context,int typeAnnotationOffset);\\nreadParameterAnnotations(MethodVisitor methodVisitor,Context context,int runtimeParameterAnnotationsOffset,boolean visible);\\nreadElementValues(AnnotationVisitor annotationVisitor,int annotationOffset,boolean named,char[] charBuffer);\\nreadElementValue(AnnotationVisitor annotationVisitor,int elementValueOffset,String elementName,char[] charBuffer);\\ncomputeImplicitFrame(Context context);\\nreadStackMapFrame(int stackMapFrameOffset,boolean compressed,boolean expand,Context context);\\nreadVerificationTypeInfo(int verificationTypeInfoOffset,Object[] frame,int index,char[] charBuffer,Label[] labels);\\ngetFirstAttributeOffset();\\nreadBootstrapMethodsAttribute(int maxStringLength);\\nreadAttribute(Attribute[] attributePrototypes,String type,int offset,int length,char[] charBuffer,int codeAttributeOffset,Label[] labels);\\ngetItemCount();\\ngetItem(int constantPoolEntryIndex);\\ngetMaxStringLength();\\nreadByte(int offset);\\nreadUnsignedShort(int offset);\\nreadShort(int offset);\\nreadInt(int offset);\\nreadLong(int offset);\\nreadUTF8(int offset,char[] charBuffer);\\nreadUtf(int constantPoolEntryIndex,char[] charBuffer);\\nreadUtf(int utfOffset,int utfLength,char[] charBuffer);\\nreadStringish(int offset,char[] charBuffer);\\nreadClass(int offset,char[] charBuffer);\\nreadModule(int offset,char[] charBuffer);\\nreadPackage(int offset,char[] charBuffer);\\nreadConstantDynamic(int constantPoolEntryIndex,char[] charBuffer);\\nreadConst(int constantPoolEntryIndex,char[] charBuffer);\\nreadStream(InputStream inputStream,boolean close);\\n\", \"repo_level\" : \"\" }", "class_name": "ClassReader", "code": "public short readShort(final int offset){\n byte[] classBuffer=classFileBuffer;\n return (short)(((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF));\n}\n", "docstring": "/** \n * Reads a signed short value in this {@link ClassReader}. This method is intended for {@link Attribute} sub classes, and is normally not needed by class generators or adapters.\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n", "end_lineno": "3109", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage net.hasor.utils.asm;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/**\n * A parser to make a {@link ClassVisitor} visit a ClassFile structure, as defined in the Java\n * Virtual Machine Specification (JVMS). This class parses the ClassFile content and calls the\n * appropriate visit methods of a given {@link ClassVisitor} for each field, method and bytecode\n * instruction encountered.\n *\n * @see JVMS 4\n * @author Eric Bruneton\n * @author Eugene Kuleshov\n */\npublic class ClassReader {\n /**\n * A flag to skip the Code attributes. If this flag is set the Code attributes are neither parsed\n * nor visited.\n */\n public static final int SKIP_CODE = 1;\n /**\n * A flag to skip the SourceFile, SourceDebugExtension, LocalVariableTable,\n * LocalVariableTypeTable, LineNumberTable and MethodParameters attributes. If this flag is set\n * these attributes are neither parsed nor visited (i.e. {@link ClassVisitor#visitSource}, {@link\n * MethodVisitor#visitLocalVariable}, {@link MethodVisitor#visitLineNumber} and {@link\n * MethodVisitor#visitParameter} are not called).\n */\n public static final int SKIP_DEBUG = 2;\n /**\n * A flag to skip the StackMap and StackMapTable attributes. If this flag is set these attributes\n * are neither parsed nor visited (i.e. {@link MethodVisitor#visitFrame} is not called). This flag\n * is useful when the {@link ClassWriter#COMPUTE_FRAMES} option is used: it avoids visiting frames\n * that will be ignored and recomputed from scratch.\n */\n public static final int SKIP_FRAMES = 4;\n /**\n * A flag to expand the stack map frames. By default stack map frames are visited in their\n * original format (i.e. \"expanded\" for classes whose version is less than V1_6, and \"compressed\"\n * for the other classes). If this flag is set, stack map frames are always visited in expanded\n * format (this option adds a decompression/compression step in ClassReader and ClassWriter which\n * degrades performance quite a lot).\n */\n public static final int EXPAND_FRAMES = 8;\n /**\n * A flag to expand the ASM specific instructions into an equivalent sequence of standard bytecode\n * instructions. When resolving a forward jump it may happen that the signed 2 bytes offset\n * reserved for it is not sufficient to store the bytecode offset. In this case the jump\n * instruction is replaced with a temporary ASM specific instruction using an unsigned 2 bytes\n * offset (see {@link Label#resolve}). This internal flag is used to re-read classes containing\n * such instructions, in order to replace them with standard instructions. In addition, when this\n * flag is used, goto_w and jsr_w are not converted into goto and jsr, to make sure that\n * infinite loops where a goto_w is replaced with a goto in ClassReader and converted back to a\n * goto_w in ClassWriter cannot occur.\n */\n static final int EXPAND_ASM_INSNS = 256;\n /** The size of the temporary byte array used to read class input streams chunk by chunk. */\n private static final int INPUT_STREAM_DATA_CHUNK_SIZE = 4096;\n /**\n * A byte array containing the JVMS ClassFile structure to be parsed.\n *\n * @deprecated Use {@link #readByte(int)} and the other read methods instead. This field will\n * eventually be deleted.\n */\n @Deprecated\n // DontCheck(MemberName): can't be renamed (for backward binary compatibility).\n public final byte[] b;\n /**\n * A byte array containing the JVMS ClassFile structure to be parsed. The content of this array\n * must not be modified. This field is intended for {@link Attribute} sub classes, and is normally\n * not needed by class visitors.\n *\n *

NOTE: the ClassFile structure can start at any offset within this array, i.e. it does not\n * necessarily start at offset 0. Use {@link #getItem} and {@link #header} to get correct\n * ClassFile element offsets within this byte array.\n */\n final byte[] classFileBuffer;\n /**\n * The offset in bytes, in {@link #classFileBuffer}, of each cp_info entry of the ClassFile's\n * constant_pool array, plus one. In other words, the offset of constant pool entry i is\n * given by cpInfoOffsets[i] - 1, i.e. its cp_info's tag field is given by b[cpInfoOffsets[i] -\n * 1].\n */\n private final int[] cpInfoOffsets;\n /**\n * The String objects corresponding to the CONSTANT_Utf8 constant pool items. This cache avoids\n * multiple parsing of a given CONSTANT_Utf8 constant pool item.\n */\n private final String[] constantUtf8Values;\n /**\n * The ConstantDynamic objects corresponding to the CONSTANT_Dynamic constant pool items. This\n * cache avoids multiple parsing of a given CONSTANT_Dynamic constant pool item.\n */\n private final ConstantDynamic[] constantDynamicValues;\n /**\n * The start offsets in {@link #classFileBuffer} of each element of the bootstrap_methods array\n * (in the BootstrapMethods attribute).\n *\n * @see JVMS\n * 4.7.23\n */\n private final int[] bootstrapMethodOffsets;\n /**\n * A conservative estimate of the maximum length of the strings contained in the constant pool of\n * the class.\n */\n private final int maxStringLength;\n /** The offset in bytes of the ClassFile's access_flags field. */\n public final int header;\n // -----------------------------------------------------------------------------------------------\n // Constructors\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param classFile the JVMS ClassFile structure to be read.\n */\n public ClassReader(final byte[] classFile) {\n this(classFile, 0, classFile.length);\n }\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read.\n * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read.\n * @param classFileLength the length in bytes of the ClassFile to be read.\n */\n public ClassReader(final byte[] classFileBuffer, final int classFileOffset, final int classFileLength) { // NOPMD(UnusedFormalParameter) used for backward compatibility.\n this(classFileBuffer, classFileOffset, /* checkClassVersion = */ true);\n }\n\n /**\n * Constructs a new {@link ClassReader} object. This internal constructor must not be exposed\n * as a public API.\n *\n * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read.\n * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read.\n * @param checkClassVersion whether to check the class version or not.\n */\n ClassReader(final byte[] classFileBuffer, final int classFileOffset, final boolean checkClassVersion) {\n this.classFileBuffer = classFileBuffer;\n this.b = classFileBuffer;\n // Check the class' major_version. This field is after the magic and minor_version fields, which\n // use 4 and 2 bytes respectively.\n if (checkClassVersion && readShort(classFileOffset + 6) > Opcodes.V15) {\n throw new IllegalArgumentException(\"Unsupported class file major version \" + readShort(classFileOffset + 6));\n }\n // Create the constant pool arrays. The constant_pool_count field is after the magic,\n // minor_version and major_version fields, which use 4, 2 and 2 bytes respectively.\n int constantPoolCount = readUnsignedShort(classFileOffset + 8);\n cpInfoOffsets = new int[constantPoolCount];\n constantUtf8Values = new String[constantPoolCount];\n // Compute the offset of each constant pool entry, as well as a conservative estimate of the\n // maximum length of the constant pool strings. The first constant pool entry is after the\n // magic, minor_version, major_version and constant_pool_count fields, which use 4, 2, 2 and 2\n // bytes respectively.\n int currentCpInfoIndex = 1;\n int currentCpInfoOffset = classFileOffset + 10;\n int currentMaxStringLength = 0;\n boolean hasBootstrapMethods = false;\n boolean hasConstantDynamic = false;\n // The offset of the other entries depend on the total size of all the previous entries.\n while (currentCpInfoIndex < constantPoolCount) {\n cpInfoOffsets[currentCpInfoIndex++] = currentCpInfoOffset + 1;\n int cpInfoSize;\n switch (classFileBuffer[currentCpInfoOffset]) {\n case Symbol.CONSTANT_FIELDREF_TAG:\n case Symbol.CONSTANT_METHODREF_TAG:\n case Symbol.CONSTANT_INTERFACE_METHODREF_TAG:\n case Symbol.CONSTANT_INTEGER_TAG:\n case Symbol.CONSTANT_FLOAT_TAG:\n case Symbol.CONSTANT_NAME_AND_TYPE_TAG:\n cpInfoSize = 5;\n break;\n case Symbol.CONSTANT_DYNAMIC_TAG:\n cpInfoSize = 5;\n hasBootstrapMethods = true;\n hasConstantDynamic = true;\n break;\n case Symbol.CONSTANT_INVOKE_DYNAMIC_TAG:\n cpInfoSize = 5;\n hasBootstrapMethods = true;\n break;\n case Symbol.CONSTANT_LONG_TAG:\n case Symbol.CONSTANT_DOUBLE_TAG:\n cpInfoSize = 9;\n currentCpInfoIndex++;\n break;\n case Symbol.CONSTANT_UTF8_TAG:\n cpInfoSize = 3 + readUnsignedShort(currentCpInfoOffset + 1);\n if (cpInfoSize > currentMaxStringLength) {\n // The size in bytes of this CONSTANT_Utf8 structure provides a conservative estimate\n // of the length in characters of the corresponding string, and is much cheaper to\n // compute than this exact length.\n currentMaxStringLength = cpInfoSize;\n }\n break;\n case Symbol.CONSTANT_METHOD_HANDLE_TAG:\n cpInfoSize = 4;\n break;\n case Symbol.CONSTANT_CLASS_TAG:\n case Symbol.CONSTANT_STRING_TAG:\n case Symbol.CONSTANT_METHOD_TYPE_TAG:\n case Symbol.CONSTANT_PACKAGE_TAG:\n case Symbol.CONSTANT_MODULE_TAG:\n cpInfoSize = 3;\n break;\n default:\n throw new IllegalArgumentException();\n }\n currentCpInfoOffset += cpInfoSize;\n }\n maxStringLength = currentMaxStringLength;\n // The Classfile's access_flags field is just after the last constant pool entry.\n header = currentCpInfoOffset;\n // Allocate the cache of ConstantDynamic values, if there is at least one.\n constantDynamicValues = hasConstantDynamic ? new ConstantDynamic[constantPoolCount] : null;\n // Read the BootstrapMethods attribute, if any (only get the offset of each method).\n bootstrapMethodOffsets = hasBootstrapMethods ? readBootstrapMethodsAttribute(currentMaxStringLength) : null;\n }\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param inputStream an input stream of the JVMS ClassFile structure to be read. This input\n * stream must contain nothing more than the ClassFile structure itself. It is read from its\n * current position to its end.\n * @throws IOException if a problem occurs during reading.\n */\n public ClassReader(final InputStream inputStream) throws IOException {\n this(readStream(inputStream, false));\n }\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param className the fully qualified name of the class to be read. The ClassFile structure is\n * retrieved with the current class loader's {@link ClassLoader#getSystemResourceAsStream}.\n * @throws IOException if an exception occurs during reading.\n */\n public ClassReader(final String className) throws IOException {\n this(readStream(ClassLoader.getSystemResourceAsStream(className.replace('.', '/') + \".class\"), true));\n }\n\n /**\n * Reads the given input stream and returns its content as a byte array.\n *\n * @param inputStream an input stream.\n * @param close true to close the input stream after reading.\n * @return the content of the given input stream.\n * @throws IOException if a problem occurs during reading.\n */\n private static byte[] readStream(final InputStream inputStream, final boolean close) throws IOException {\n if (inputStream == null) {\n throw new IOException(\"Class not found\");\n }\n try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {\n byte[] data = new byte[INPUT_STREAM_DATA_CHUNK_SIZE];\n int bytesRead;\n while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {\n outputStream.write(data, 0, bytesRead);\n }\n outputStream.flush();\n return outputStream.toByteArray();\n } finally {\n if (close) {\n inputStream.close();\n }\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Accessors\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the class's access flags (see {@link Opcodes}). This value may not reflect Deprecated\n * and Synthetic flags when bytecode is before 1.5 and those flags are represented by attributes.\n *\n * @return the class access flags.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public int getAccess() {\n return readUnsignedShort(header);\n }\n\n /**\n * Returns the internal name of the class (see {@link Type#getInternalName()}).\n *\n * @return the internal class name.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public String getClassName() {\n // this_class is just after the access_flags field (using 2 bytes).\n return readClass(header + 2, new char[maxStringLength]);\n }\n\n /**\n * Returns the internal of name of the super class (see {@link Type#getInternalName()}). For\n * interfaces, the super class is {@link Object}.\n *\n * @return the internal name of the super class, or {@literal null} for {@link Object} class.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public String getSuperName() {\n // super_class is after the access_flags and this_class fields (2 bytes each).\n return readClass(header + 4, new char[maxStringLength]);\n }\n\n /**\n * Returns the internal names of the implemented interfaces (see {@link Type#getInternalName()}).\n *\n * @return the internal names of the directly implemented interfaces. Inherited implemented\n * interfaces are not returned.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public String[] getInterfaces() {\n // interfaces_count is after the access_flags, this_class and super_class fields (2 bytes each).\n int currentOffset = header + 6;\n int interfacesCount = readUnsignedShort(currentOffset);\n String[] interfaces = new String[interfacesCount];\n if (interfacesCount > 0) {\n char[] charBuffer = new char[maxStringLength];\n for (int i = 0; i < interfacesCount; ++i) {\n currentOffset += 2;\n interfaces[i] = readClass(currentOffset, charBuffer);\n }\n }\n return interfaces;\n }\n // -----------------------------------------------------------------------------------------------\n // Public methods\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this\n * {@link ClassReader}.\n *\n * @param classVisitor the visitor that must visit this class.\n * @param parsingOptions the options to use to parse this class. One or more of {@link\n * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}.\n */\n public void accept(final ClassVisitor classVisitor, final int parsingOptions) {\n accept(classVisitor, new Attribute[0], parsingOptions);\n }\n\n /**\n * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this\n * {@link ClassReader}.\n *\n * @param classVisitor the visitor that must visit this class.\n * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of\n * the class. Any attribute whose type is not equal to the type of one the prototypes will not\n * be parsed: its byte array value will be passed unchanged to the ClassWriter. This may\n * corrupt it if this value contains references to the constant pool, or has syntactic or\n * semantic links with a class element that has been transformed by a class adapter between\n * the reader and the writer.\n * @param parsingOptions the options to use to parse this class. One or more of {@link\n * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}.\n */\n public void accept(final ClassVisitor classVisitor, final Attribute[] attributePrototypes, final int parsingOptions) {\n Context context = new Context();\n context.attributePrototypes = attributePrototypes;\n context.parsingOptions = parsingOptions;\n context.charBuffer = new char[maxStringLength];\n // Read the access_flags, this_class, super_class, interface_count and interfaces fields.\n char[] charBuffer = context.charBuffer;\n int currentOffset = header;\n int accessFlags = readUnsignedShort(currentOffset);\n String thisClass = readClass(currentOffset + 2, charBuffer);\n String superClass = readClass(currentOffset + 4, charBuffer);\n String[] interfaces = new String[readUnsignedShort(currentOffset + 6)];\n currentOffset += 8;\n for (int i = 0; i < interfaces.length; ++i) {\n interfaces[i] = readClass(currentOffset, charBuffer);\n currentOffset += 2;\n }\n // Read the class attributes (the variables are ordered as in Section 4.7 of the JVMS).\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The offset of the InnerClasses attribute, or 0.\n int innerClassesOffset = 0;\n // - The offset of the EnclosingMethod attribute, or 0.\n int enclosingMethodOffset = 0;\n // - The string corresponding to the Signature attribute, or null.\n String signature = null;\n // - The string corresponding to the SourceFile attribute, or null.\n String sourceFile = null;\n // - The string corresponding to the SourceDebugExtension attribute, or null.\n String sourceDebugExtension = null;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The offset of the Module attribute, or 0.\n int moduleOffset = 0;\n // - The offset of the ModulePackages attribute, or 0.\n int modulePackagesOffset = 0;\n // - The string corresponding to the ModuleMainClass attribute, or null.\n String moduleMainClass = null;\n // - The string corresponding to the NestHost attribute, or null.\n String nestHostClass = null;\n // - The offset of the NestMembers attribute, or 0.\n int nestMembersOffset = 0;\n // - The offset of the PermittedSubtypes attribute, or 0\n int permittedSubtypesOffset = 0;\n // - The offset of the Record attribute, or 0.\n int recordOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int currentAttributeOffset = getFirstAttributeOffset();\n for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentAttributeOffset, charBuffer);\n int attributeLength = readInt(currentAttributeOffset + 2);\n currentAttributeOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.SOURCE_FILE.equals(attributeName)) {\n sourceFile = readUTF8(currentAttributeOffset, charBuffer);\n } else if (Constants.INNER_CLASSES.equals(attributeName)) {\n innerClassesOffset = currentAttributeOffset;\n } else if (Constants.ENCLOSING_METHOD.equals(attributeName)) {\n enclosingMethodOffset = currentAttributeOffset;\n } else if (Constants.NEST_HOST.equals(attributeName)) {\n nestHostClass = readClass(currentAttributeOffset, charBuffer);\n } else if (Constants.NEST_MEMBERS.equals(attributeName)) {\n nestMembersOffset = currentAttributeOffset;\n } else if (Constants.PERMITTED_SUBTYPES.equals(attributeName)) {\n permittedSubtypesOffset = currentAttributeOffset;\n } else if (Constants.SIGNATURE.equals(attributeName)) {\n signature = readUTF8(currentAttributeOffset, charBuffer);\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.SYNTHETIC.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_SYNTHETIC;\n } else if (Constants.SOURCE_DEBUG_EXTENSION.equals(attributeName)) {\n sourceDebugExtension = readUtf(currentAttributeOffset, attributeLength, new char[attributeLength]);\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.RECORD.equals(attributeName)) {\n recordOffset = currentAttributeOffset;\n } else if (Constants.MODULE.equals(attributeName)) {\n moduleOffset = currentAttributeOffset;\n } else if (Constants.MODULE_MAIN_CLASS.equals(attributeName)) {\n moduleMainClass = readClass(currentAttributeOffset, charBuffer);\n } else if (Constants.MODULE_PACKAGES.equals(attributeName)) {\n modulePackagesOffset = currentAttributeOffset;\n } else if (!Constants.BOOTSTRAP_METHODS.equals(attributeName)) {\n // The BootstrapMethods attribute is read in the constructor.\n Attribute attribute = readAttribute(attributePrototypes, attributeName, currentAttributeOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentAttributeOffset += attributeLength;\n }\n // Visit the class declaration. The minor_version and major_version fields start 6 bytes before\n // the first constant pool entry, which itself starts at cpInfoOffsets[1] - 1 (by definition).\n classVisitor.visit(readInt(cpInfoOffsets[1] - 7), accessFlags, thisClass, signature, superClass, interfaces);\n // Visit the SourceFile and SourceDebugExtenstion attributes.\n if ((parsingOptions & SKIP_DEBUG) == 0 && (sourceFile != null || sourceDebugExtension != null)) {\n classVisitor.visitSource(sourceFile, sourceDebugExtension);\n }\n // Visit the Module, ModulePackages and ModuleMainClass attributes.\n if (moduleOffset != 0) {\n readModuleAttributes(classVisitor, context, moduleOffset, modulePackagesOffset, moduleMainClass);\n }\n // Visit the NestHost attribute.\n if (nestHostClass != null) {\n classVisitor.visitNestHost(nestHostClass);\n }\n // Visit the EnclosingMethod attribute.\n if (enclosingMethodOffset != 0) {\n String className = readClass(enclosingMethodOffset, charBuffer);\n int methodIndex = readUnsignedShort(enclosingMethodOffset + 2);\n String name = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex], charBuffer);\n String type = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex] + 2, charBuffer);\n classVisitor.visitOuterClass(className, name, type);\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in ClassWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n classVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the NestedMembers attribute.\n if (nestMembersOffset != 0) {\n int numberOfNestMembers = readUnsignedShort(nestMembersOffset);\n int currentNestMemberOffset = nestMembersOffset + 2;\n while (numberOfNestMembers-- > 0) {\n classVisitor.visitNestMember(readClass(currentNestMemberOffset, charBuffer));\n currentNestMemberOffset += 2;\n }\n }\n // Visit the PermittedSubtypes attribute.\n if (permittedSubtypesOffset != 0) {\n int numberOfPermittedSubtypes = readUnsignedShort(permittedSubtypesOffset);\n int currentPermittedSubtypeOffset = permittedSubtypesOffset + 2;\n while (numberOfPermittedSubtypes-- > 0) {\n classVisitor.visitPermittedSubtypeExperimental(readClass(currentPermittedSubtypeOffset, charBuffer));\n currentPermittedSubtypeOffset += 2;\n }\n }\n // Visit the InnerClasses attribute.\n if (innerClassesOffset != 0) {\n int numberOfClasses = readUnsignedShort(innerClassesOffset);\n int currentClassesOffset = innerClassesOffset + 2;\n while (numberOfClasses-- > 0) {\n classVisitor.visitInnerClass(readClass(currentClassesOffset, charBuffer), readClass(currentClassesOffset + 2, charBuffer), readUTF8(currentClassesOffset + 4, charBuffer), readUnsignedShort(currentClassesOffset + 6));\n currentClassesOffset += 8;\n }\n }\n // Visit Record components.\n if (recordOffset != 0) {\n int recordComponentsCount = readUnsignedShort(recordOffset);\n recordOffset += 2;\n while (recordComponentsCount-- > 0) {\n recordOffset = readRecordComponent(classVisitor, context, recordOffset);\n }\n }\n // Visit the fields and methods.\n int fieldsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (fieldsCount-- > 0) {\n currentOffset = readField(classVisitor, context, currentOffset);\n }\n int methodsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (methodsCount-- > 0) {\n currentOffset = readMethod(classVisitor, context, currentOffset);\n }\n // Visit the end of the class.\n classVisitor.visitEnd();\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse modules, fields and methods\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Reads the Module, ModulePackages and ModuleMainClass attributes and visit them.\n *\n * @param classVisitor the current class visitor\n * @param context information about the class being parsed.\n * @param moduleOffset the offset of the Module attribute (excluding the attribute_info's\n * attribute_name_index and attribute_length fields).\n * @param modulePackagesOffset the offset of the ModulePackages attribute (excluding the\n * attribute_info's attribute_name_index and attribute_length fields), or 0.\n * @param moduleMainClass the string corresponding to the ModuleMainClass attribute, or {@literal\n * null}.\n */\n private void readModuleAttributes(final ClassVisitor classVisitor, final Context context, final int moduleOffset, final int modulePackagesOffset, final String moduleMainClass) {\n char[] buffer = context.charBuffer;\n // Read the module_name_index, module_flags and module_version_index fields and visit them.\n int currentOffset = moduleOffset;\n String moduleName = readModule(currentOffset, buffer);\n int moduleFlags = readUnsignedShort(currentOffset + 2);\n String moduleVersion = readUTF8(currentOffset + 4, buffer);\n currentOffset += 6;\n ModuleVisitor moduleVisitor = classVisitor.visitModule(moduleName, moduleFlags, moduleVersion);\n if (moduleVisitor == null) {\n return;\n }\n // Visit the ModuleMainClass attribute.\n if (moduleMainClass != null) {\n moduleVisitor.visitMainClass(moduleMainClass);\n }\n // Visit the ModulePackages attribute.\n if (modulePackagesOffset != 0) {\n int packageCount = readUnsignedShort(modulePackagesOffset);\n int currentPackageOffset = modulePackagesOffset + 2;\n while (packageCount-- > 0) {\n moduleVisitor.visitPackage(readPackage(currentPackageOffset, buffer));\n currentPackageOffset += 2;\n }\n }\n // Read the 'requires_count' and 'requires' fields.\n int requiresCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (requiresCount-- > 0) {\n // Read the requires_index, requires_flags and requires_version fields and visit them.\n String requires = readModule(currentOffset, buffer);\n int requiresFlags = readUnsignedShort(currentOffset + 2);\n String requiresVersion = readUTF8(currentOffset + 4, buffer);\n currentOffset += 6;\n moduleVisitor.visitRequire(requires, requiresFlags, requiresVersion);\n }\n // Read the 'exports_count' and 'exports' fields.\n int exportsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (exportsCount-- > 0) {\n // Read the exports_index, exports_flags, exports_to_count and exports_to_index fields\n // and visit them.\n String exports = readPackage(currentOffset, buffer);\n int exportsFlags = readUnsignedShort(currentOffset + 2);\n int exportsToCount = readUnsignedShort(currentOffset + 4);\n currentOffset += 6;\n String[] exportsTo = null;\n if (exportsToCount != 0) {\n exportsTo = new String[exportsToCount];\n for (int i = 0; i < exportsToCount; ++i) {\n exportsTo[i] = readModule(currentOffset, buffer);\n currentOffset += 2;\n }\n }\n moduleVisitor.visitExport(exports, exportsFlags, exportsTo);\n }\n // Reads the 'opens_count' and 'opens' fields.\n int opensCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (opensCount-- > 0) {\n // Read the opens_index, opens_flags, opens_to_count and opens_to_index fields and visit them.\n String opens = readPackage(currentOffset, buffer);\n int opensFlags = readUnsignedShort(currentOffset + 2);\n int opensToCount = readUnsignedShort(currentOffset + 4);\n currentOffset += 6;\n String[] opensTo = null;\n if (opensToCount != 0) {\n opensTo = new String[opensToCount];\n for (int i = 0; i < opensToCount; ++i) {\n opensTo[i] = readModule(currentOffset, buffer);\n currentOffset += 2;\n }\n }\n moduleVisitor.visitOpen(opens, opensFlags, opensTo);\n }\n // Read the 'uses_count' and 'uses' fields.\n int usesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (usesCount-- > 0) {\n moduleVisitor.visitUse(readClass(currentOffset, buffer));\n currentOffset += 2;\n }\n // Read the 'provides_count' and 'provides' fields.\n int providesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (providesCount-- > 0) {\n // Read the provides_index, provides_with_count and provides_with_index fields and visit them.\n String provides = readClass(currentOffset, buffer);\n int providesWithCount = readUnsignedShort(currentOffset + 2);\n currentOffset += 4;\n String[] providesWith = new String[providesWithCount];\n for (int i = 0; i < providesWithCount; ++i) {\n providesWith[i] = readClass(currentOffset, buffer);\n currentOffset += 2;\n }\n moduleVisitor.visitProvide(provides, providesWith);\n }\n // Visit the end of the module attributes.\n moduleVisitor.visitEnd();\n }\n\n /**\n * Reads a record component and visit it.\n *\n * @param classVisitor the current class visitor\n * @param context information about the class being parsed.\n * @param recordComponentOffset the offset of the current record component.\n * @return the offset of the first byte following the record component.\n */\n private int readRecordComponent(final ClassVisitor classVisitor, final Context context, final int recordComponentOffset) {\n char[] charBuffer = context.charBuffer;\n int currentOffset = recordComponentOffset;\n String name = readUTF8(currentOffset, charBuffer);\n String descriptor = readUTF8(currentOffset + 2, charBuffer);\n currentOffset += 4;\n // Read the record component attributes (the variables are ordered as in Section 4.7 of the\n // JVMS).\n int accessFlags = 0;\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The string corresponding to the Signature attribute, or null.\n String signature = null;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.SIGNATURE.equals(attributeName)) {\n signature = readUTF8(currentOffset, charBuffer);\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentOffset;\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n RecordComponentVisitor recordComponentVisitor = classVisitor.visitRecordComponentExperimental(accessFlags, name, descriptor, signature);\n if (recordComponentVisitor == null) {\n return currentOffset;\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitAnnotationExperimental(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitAnnotationExperimental(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitTypeAnnotationExperimental(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitTypeAnnotationExperimental(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in FieldWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n recordComponentVisitor.visitAttributeExperimental(attributes);\n attributes = nextAttribute;\n }\n // Visit the end of the field.\n recordComponentVisitor.visitEndExperimental();\n return currentOffset;\n }\n\n /**\n * Reads a JVMS field_info structure and makes the given visitor visit it.\n *\n * @param classVisitor the visitor that must visit the field.\n * @param context information about the class being parsed.\n * @param fieldInfoOffset the start offset of the field_info structure.\n * @return the offset of the first byte following the field_info structure.\n */\n private int readField(final ClassVisitor classVisitor, final Context context, final int fieldInfoOffset) {\n char[] charBuffer = context.charBuffer;\n // Read the access_flags, name_index and descriptor_index fields.\n int currentOffset = fieldInfoOffset;\n int accessFlags = readUnsignedShort(currentOffset);\n String name = readUTF8(currentOffset + 2, charBuffer);\n String descriptor = readUTF8(currentOffset + 4, charBuffer);\n currentOffset += 6;\n // Read the field attributes (the variables are ordered as in Section 4.7 of the JVMS).\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The value corresponding to the ConstantValue attribute, or null.\n Object constantValue = null;\n // - The string corresponding to the Signature attribute, or null.\n String signature = null;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.CONSTANT_VALUE.equals(attributeName)) {\n int constantvalueIndex = readUnsignedShort(currentOffset);\n constantValue = constantvalueIndex == 0 ? null : readConst(constantvalueIndex, charBuffer);\n } else if (Constants.SIGNATURE.equals(attributeName)) {\n signature = readUTF8(currentOffset, charBuffer);\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.SYNTHETIC.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_SYNTHETIC;\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentOffset;\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n // Visit the field declaration.\n FieldVisitor fieldVisitor = classVisitor.visitField(accessFlags, name, descriptor, signature, constantValue);\n if (fieldVisitor == null) {\n return currentOffset;\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in FieldWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n fieldVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the end of the field.\n fieldVisitor.visitEnd();\n return currentOffset;\n }\n\n /**\n * Reads a JVMS method_info structure and makes the given visitor visit it.\n *\n * @param classVisitor the visitor that must visit the method.\n * @param context information about the class being parsed.\n * @param methodInfoOffset the start offset of the method_info structure.\n * @return the offset of the first byte following the method_info structure.\n */\n private int readMethod(final ClassVisitor classVisitor, final Context context, final int methodInfoOffset) {\n char[] charBuffer = context.charBuffer;\n // Read the access_flags, name_index and descriptor_index fields.\n int currentOffset = methodInfoOffset;\n context.currentMethodAccessFlags = readUnsignedShort(currentOffset);\n context.currentMethodName = readUTF8(currentOffset + 2, charBuffer);\n context.currentMethodDescriptor = readUTF8(currentOffset + 4, charBuffer);\n currentOffset += 6;\n // Read the method attributes (the variables are ordered as in Section 4.7 of the JVMS).\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The offset of the Code attribute, or 0.\n int codeOffset = 0;\n // - The offset of the Exceptions attribute, or 0.\n int exceptionsOffset = 0;\n // - The strings corresponding to the Exceptions attribute, or null.\n String[] exceptions = null;\n // - Whether the method has a Synthetic attribute.\n boolean synthetic = false;\n // - The constant pool index contained in the Signature attribute, or 0.\n int signatureIndex = 0;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleParameterAnnotations attribute, or 0.\n int runtimeVisibleParameterAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleParameterAnnotations attribute, or 0.\n int runtimeInvisibleParameterAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The offset of the AnnotationDefault attribute, or 0.\n int annotationDefaultOffset = 0;\n // - The offset of the MethodParameters attribute, or 0.\n int methodParametersOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.CODE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_CODE) == 0) {\n codeOffset = currentOffset;\n }\n } else if (Constants.EXCEPTIONS.equals(attributeName)) {\n exceptionsOffset = currentOffset;\n exceptions = new String[readUnsignedShort(exceptionsOffset)];\n int currentExceptionOffset = exceptionsOffset + 2;\n for (int i = 0; i < exceptions.length; ++i) {\n exceptions[i] = readClass(currentExceptionOffset, charBuffer);\n currentExceptionOffset += 2;\n }\n } else if (Constants.SIGNATURE.equals(attributeName)) {\n signatureIndex = readUnsignedShort(currentOffset);\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n context.currentMethodAccessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.ANNOTATION_DEFAULT.equals(attributeName)) {\n annotationDefaultOffset = currentOffset;\n } else if (Constants.SYNTHETIC.equals(attributeName)) {\n synthetic = true;\n context.currentMethodAccessFlags |= Opcodes.ACC_SYNTHETIC;\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleParameterAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleParameterAnnotationsOffset = currentOffset;\n } else if (Constants.METHOD_PARAMETERS.equals(attributeName)) {\n methodParametersOffset = currentOffset;\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n // Visit the method declaration.\n MethodVisitor methodVisitor = classVisitor.visitMethod(context.currentMethodAccessFlags, context.currentMethodName, context.currentMethodDescriptor, signatureIndex == 0 ? null : readUtf(signatureIndex, charBuffer), exceptions);\n if (methodVisitor == null) {\n return currentOffset;\n }\n // If the returned MethodVisitor is in fact a MethodWriter, it means there is no method\n // adapter between the reader and the writer. In this case, it might be possible to copy\n // the method attributes directly into the writer. If so, return early without visiting\n // the content of these attributes.\n if (methodVisitor instanceof MethodWriter) {\n MethodWriter methodWriter = (MethodWriter) methodVisitor;\n if (methodWriter.canCopyMethodAttributes(this, synthetic, (context.currentMethodAccessFlags & Opcodes.ACC_DEPRECATED) != 0, readUnsignedShort(methodInfoOffset + 4), signatureIndex, exceptionsOffset)) {\n methodWriter.setMethodAttributesSource(methodInfoOffset, currentOffset - methodInfoOffset);\n return currentOffset;\n }\n }\n // Visit the MethodParameters attribute.\n if (methodParametersOffset != 0 && (context.parsingOptions & SKIP_DEBUG) == 0) {\n int parametersCount = readByte(methodParametersOffset);\n int currentParameterOffset = methodParametersOffset + 1;\n while (parametersCount-- > 0) {\n // Read the name_index and access_flags fields and visit them.\n methodVisitor.visitParameter(readUTF8(currentParameterOffset, charBuffer), readUnsignedShort(currentParameterOffset + 2));\n currentParameterOffset += 4;\n }\n }\n // Visit the AnnotationDefault attribute.\n if (annotationDefaultOffset != 0) {\n AnnotationVisitor annotationVisitor = methodVisitor.visitAnnotationDefault();\n readElementValue(annotationVisitor, annotationDefaultOffset, null, charBuffer);\n if (annotationVisitor != null) {\n annotationVisitor.visitEnd();\n }\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleParameterAnnotations attribute.\n if (runtimeVisibleParameterAnnotationsOffset != 0) {\n readParameterAnnotations(methodVisitor, context, runtimeVisibleParameterAnnotationsOffset, /* visible = */ true);\n }\n // Visit the RuntimeInvisibleParameterAnnotations attribute.\n if (runtimeInvisibleParameterAnnotationsOffset != 0) {\n readParameterAnnotations(methodVisitor, context, runtimeInvisibleParameterAnnotationsOffset,\n /* visible = */ false);\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in MethodWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n methodVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the Code attribute.\n if (codeOffset != 0) {\n methodVisitor.visitCode();\n readCode(methodVisitor, context, codeOffset);\n }\n // Visit the end of the method.\n methodVisitor.visitEnd();\n return currentOffset;\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse a Code attribute\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Reads a JVMS 'Code' attribute and makes the given visitor visit it.\n *\n * @param methodVisitor the visitor that must visit the Code attribute.\n * @param context information about the class being parsed.\n * @param codeOffset the start offset in {@link #classFileBuffer} of the Code attribute, excluding\n * its attribute_name_index and attribute_length fields.\n */\n private void readCode(final MethodVisitor methodVisitor, final Context context, final int codeOffset) {\n int currentOffset = codeOffset;\n // Read the max_stack, max_locals and code_length fields.\n final byte[] classBuffer = classFileBuffer;\n final char[] charBuffer = context.charBuffer;\n final int maxStack = readUnsignedShort(currentOffset);\n final int maxLocals = readUnsignedShort(currentOffset + 2);\n final int codeLength = readInt(currentOffset + 4);\n currentOffset += 8;\n // Read the bytecode 'code' array to create a label for each referenced instruction.\n final int bytecodeStartOffset = currentOffset;\n final int bytecodeEndOffset = currentOffset + codeLength;\n final Label[] labels = context.currentMethodLabels = new Label[codeLength + 1];\n while (currentOffset < bytecodeEndOffset) {\n final int bytecodeOffset = currentOffset - bytecodeStartOffset;\n final int opcode = classBuffer[currentOffset] & 0xFF;\n switch (opcode) {\n case Constants.NOP:\n case Constants.ACONST_NULL:\n case Constants.ICONST_M1:\n case Constants.ICONST_0:\n case Constants.ICONST_1:\n case Constants.ICONST_2:\n case Constants.ICONST_3:\n case Constants.ICONST_4:\n case Constants.ICONST_5:\n case Constants.LCONST_0:\n case Constants.LCONST_1:\n case Constants.FCONST_0:\n case Constants.FCONST_1:\n case Constants.FCONST_2:\n case Constants.DCONST_0:\n case Constants.DCONST_1:\n case Constants.IALOAD:\n case Constants.LALOAD:\n case Constants.FALOAD:\n case Constants.DALOAD:\n case Constants.AALOAD:\n case Constants.BALOAD:\n case Constants.CALOAD:\n case Constants.SALOAD:\n case Constants.IASTORE:\n case Constants.LASTORE:\n case Constants.FASTORE:\n case Constants.DASTORE:\n case Constants.AASTORE:\n case Constants.BASTORE:\n case Constants.CASTORE:\n case Constants.SASTORE:\n case Constants.POP:\n case Constants.POP2:\n case Constants.DUP:\n case Constants.DUP_X1:\n case Constants.DUP_X2:\n case Constants.DUP2:\n case Constants.DUP2_X1:\n case Constants.DUP2_X2:\n case Constants.SWAP:\n case Constants.IADD:\n case Constants.LADD:\n case Constants.FADD:\n case Constants.DADD:\n case Constants.ISUB:\n case Constants.LSUB:\n case Constants.FSUB:\n case Constants.DSUB:\n case Constants.IMUL:\n case Constants.LMUL:\n case Constants.FMUL:\n case Constants.DMUL:\n case Constants.IDIV:\n case Constants.LDIV:\n case Constants.FDIV:\n case Constants.DDIV:\n case Constants.IREM:\n case Constants.LREM:\n case Constants.FREM:\n case Constants.DREM:\n case Constants.INEG:\n case Constants.LNEG:\n case Constants.FNEG:\n case Constants.DNEG:\n case Constants.ISHL:\n case Constants.LSHL:\n case Constants.ISHR:\n case Constants.LSHR:\n case Constants.IUSHR:\n case Constants.LUSHR:\n case Constants.IAND:\n case Constants.LAND:\n case Constants.IOR:\n case Constants.LOR:\n case Constants.IXOR:\n case Constants.LXOR:\n case Constants.I2L:\n case Constants.I2F:\n case Constants.I2D:\n case Constants.L2I:\n case Constants.L2F:\n case Constants.L2D:\n case Constants.F2I:\n case Constants.F2L:\n case Constants.F2D:\n case Constants.D2I:\n case Constants.D2L:\n case Constants.D2F:\n case Constants.I2B:\n case Constants.I2C:\n case Constants.I2S:\n case Constants.LCMP:\n case Constants.FCMPL:\n case Constants.FCMPG:\n case Constants.DCMPL:\n case Constants.DCMPG:\n case Constants.IRETURN:\n case Constants.LRETURN:\n case Constants.FRETURN:\n case Constants.DRETURN:\n case Constants.ARETURN:\n case Constants.RETURN:\n case Constants.ARRAYLENGTH:\n case Constants.ATHROW:\n case Constants.MONITORENTER:\n case Constants.MONITOREXIT:\n case Constants.ILOAD_0:\n case Constants.ILOAD_1:\n case Constants.ILOAD_2:\n case Constants.ILOAD_3:\n case Constants.LLOAD_0:\n case Constants.LLOAD_1:\n case Constants.LLOAD_2:\n case Constants.LLOAD_3:\n case Constants.FLOAD_0:\n case Constants.FLOAD_1:\n case Constants.FLOAD_2:\n case Constants.FLOAD_3:\n case Constants.DLOAD_0:\n case Constants.DLOAD_1:\n case Constants.DLOAD_2:\n case Constants.DLOAD_3:\n case Constants.ALOAD_0:\n case Constants.ALOAD_1:\n case Constants.ALOAD_2:\n case Constants.ALOAD_3:\n case Constants.ISTORE_0:\n case Constants.ISTORE_1:\n case Constants.ISTORE_2:\n case Constants.ISTORE_3:\n case Constants.LSTORE_0:\n case Constants.LSTORE_1:\n case Constants.LSTORE_2:\n case Constants.LSTORE_3:\n case Constants.FSTORE_0:\n case Constants.FSTORE_1:\n case Constants.FSTORE_2:\n case Constants.FSTORE_3:\n case Constants.DSTORE_0:\n case Constants.DSTORE_1:\n case Constants.DSTORE_2:\n case Constants.DSTORE_3:\n case Constants.ASTORE_0:\n case Constants.ASTORE_1:\n case Constants.ASTORE_2:\n case Constants.ASTORE_3:\n currentOffset += 1;\n break;\n case Constants.IFEQ:\n case Constants.IFNE:\n case Constants.IFLT:\n case Constants.IFGE:\n case Constants.IFGT:\n case Constants.IFLE:\n case Constants.IF_ICMPEQ:\n case Constants.IF_ICMPNE:\n case Constants.IF_ICMPLT:\n case Constants.IF_ICMPGE:\n case Constants.IF_ICMPGT:\n case Constants.IF_ICMPLE:\n case Constants.IF_ACMPEQ:\n case Constants.IF_ACMPNE:\n case Constants.GOTO:\n case Constants.JSR:\n case Constants.IFNULL:\n case Constants.IFNONNULL:\n createLabel(bytecodeOffset + readShort(currentOffset + 1), labels);\n currentOffset += 3;\n break;\n case Constants.ASM_IFEQ:\n case Constants.ASM_IFNE:\n case Constants.ASM_IFLT:\n case Constants.ASM_IFGE:\n case Constants.ASM_IFGT:\n case Constants.ASM_IFLE:\n case Constants.ASM_IF_ICMPEQ:\n case Constants.ASM_IF_ICMPNE:\n case Constants.ASM_IF_ICMPLT:\n case Constants.ASM_IF_ICMPGE:\n case Constants.ASM_IF_ICMPGT:\n case Constants.ASM_IF_ICMPLE:\n case Constants.ASM_IF_ACMPEQ:\n case Constants.ASM_IF_ACMPNE:\n case Constants.ASM_GOTO:\n case Constants.ASM_JSR:\n case Constants.ASM_IFNULL:\n case Constants.ASM_IFNONNULL:\n createLabel(bytecodeOffset + readUnsignedShort(currentOffset + 1), labels);\n currentOffset += 3;\n break;\n case Constants.GOTO_W:\n case Constants.JSR_W:\n case Constants.ASM_GOTO_W:\n createLabel(bytecodeOffset + readInt(currentOffset + 1), labels);\n currentOffset += 5;\n break;\n case Constants.WIDE:\n switch (classBuffer[currentOffset + 1] & 0xFF) {\n case Constants.ILOAD:\n case Constants.FLOAD:\n case Constants.ALOAD:\n case Constants.LLOAD:\n case Constants.DLOAD:\n case Constants.ISTORE:\n case Constants.FSTORE:\n case Constants.ASTORE:\n case Constants.LSTORE:\n case Constants.DSTORE:\n case Constants.RET:\n currentOffset += 4;\n break;\n case Constants.IINC:\n currentOffset += 6;\n break;\n default:\n throw new IllegalArgumentException();\n }\n break;\n case Constants.TABLESWITCH:\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (bytecodeOffset & 3);\n // Read the default label and the number of table entries.\n createLabel(bytecodeOffset + readInt(currentOffset), labels);\n int numTableEntries = readInt(currentOffset + 8) - readInt(currentOffset + 4) + 1;\n currentOffset += 12;\n // Read the table labels.\n while (numTableEntries-- > 0) {\n createLabel(bytecodeOffset + readInt(currentOffset), labels);\n currentOffset += 4;\n }\n break;\n case Constants.LOOKUPSWITCH:\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (bytecodeOffset & 3);\n // Read the default label and the number of switch cases.\n createLabel(bytecodeOffset + readInt(currentOffset), labels);\n int numSwitchCases = readInt(currentOffset + 4);\n currentOffset += 8;\n // Read the switch labels.\n while (numSwitchCases-- > 0) {\n createLabel(bytecodeOffset + readInt(currentOffset + 4), labels);\n currentOffset += 8;\n }\n break;\n case Constants.ILOAD:\n case Constants.LLOAD:\n case Constants.FLOAD:\n case Constants.DLOAD:\n case Constants.ALOAD:\n case Constants.ISTORE:\n case Constants.LSTORE:\n case Constants.FSTORE:\n case Constants.DSTORE:\n case Constants.ASTORE:\n case Constants.RET:\n case Constants.BIPUSH:\n case Constants.NEWARRAY:\n case Constants.LDC:\n currentOffset += 2;\n break;\n case Constants.SIPUSH:\n case Constants.LDC_W:\n case Constants.LDC2_W:\n case Constants.GETSTATIC:\n case Constants.PUTSTATIC:\n case Constants.GETFIELD:\n case Constants.PUTFIELD:\n case Constants.INVOKEVIRTUAL:\n case Constants.INVOKESPECIAL:\n case Constants.INVOKESTATIC:\n case Constants.NEW:\n case Constants.ANEWARRAY:\n case Constants.CHECKCAST:\n case Constants.INSTANCEOF:\n case Constants.IINC:\n currentOffset += 3;\n break;\n case Constants.INVOKEINTERFACE:\n case Constants.INVOKEDYNAMIC:\n currentOffset += 5;\n break;\n case Constants.MULTIANEWARRAY:\n currentOffset += 4;\n break;\n default:\n throw new IllegalArgumentException();\n }\n }\n // Read the 'exception_table_length' and 'exception_table' field to create a label for each\n // referenced instruction, and to make methodVisitor visit the corresponding try catch blocks.\n int exceptionTableLength = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (exceptionTableLength-- > 0) {\n Label start = createLabel(readUnsignedShort(currentOffset), labels);\n Label end = createLabel(readUnsignedShort(currentOffset + 2), labels);\n Label handler = createLabel(readUnsignedShort(currentOffset + 4), labels);\n String catchType = readUTF8(cpInfoOffsets[readUnsignedShort(currentOffset + 6)], charBuffer);\n currentOffset += 8;\n methodVisitor.visitTryCatchBlock(start, end, handler, catchType);\n }\n // Read the Code attributes to create a label for each referenced instruction (the variables\n // are ordered as in Section 4.7 of the JVMS). Attribute offsets exclude the\n // attribute_name_index and attribute_length fields.\n // - The offset of the current 'stack_map_frame' in the StackMap[Table] attribute, or 0.\n // Initially, this is the offset of the first 'stack_map_frame' entry. Then this offset is\n // updated after each stack_map_frame is read.\n int stackMapFrameOffset = 0;\n // - The end offset of the StackMap[Table] attribute, or 0.\n int stackMapTableEndOffset = 0;\n // - Whether the stack map frames are compressed (i.e. in a StackMapTable) or not.\n boolean compressedFrames = true;\n // - The offset of the LocalVariableTable attribute, or 0.\n int localVariableTableOffset = 0;\n // - The offset of the LocalVariableTypeTable attribute, or 0.\n int localVariableTypeTableOffset = 0;\n // - The offset of each 'type_annotation' entry in the RuntimeVisibleTypeAnnotations\n // attribute, or null.\n int[] visibleTypeAnnotationOffsets = null;\n // - The offset of each 'type_annotation' entry in the RuntimeInvisibleTypeAnnotations\n // attribute, or null.\n int[] invisibleTypeAnnotationOffsets = null;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n if (Constants.LOCAL_VARIABLE_TABLE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_DEBUG) == 0) {\n localVariableTableOffset = currentOffset;\n // Parse the attribute to find the corresponding (debug only) labels.\n int currentLocalVariableTableOffset = currentOffset;\n int localVariableTableLength = readUnsignedShort(currentLocalVariableTableOffset);\n currentLocalVariableTableOffset += 2;\n while (localVariableTableLength-- > 0) {\n int startPc = readUnsignedShort(currentLocalVariableTableOffset);\n createDebugLabel(startPc, labels);\n int length = readUnsignedShort(currentLocalVariableTableOffset + 2);\n createDebugLabel(startPc + length, labels);\n // Skip the name_index, descriptor_index and index fields (2 bytes each).\n currentLocalVariableTableOffset += 10;\n }\n }\n } else if (Constants.LOCAL_VARIABLE_TYPE_TABLE.equals(attributeName)) {\n localVariableTypeTableOffset = currentOffset;\n // Here we do not extract the labels corresponding to the attribute content. We assume they\n // are the same or a subset of those of the LocalVariableTable attribute.\n } else if (Constants.LINE_NUMBER_TABLE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_DEBUG) == 0) {\n // Parse the attribute to find the corresponding (debug only) labels.\n int currentLineNumberTableOffset = currentOffset;\n int lineNumberTableLength = readUnsignedShort(currentLineNumberTableOffset);\n currentLineNumberTableOffset += 2;\n while (lineNumberTableLength-- > 0) {\n int startPc = readUnsignedShort(currentLineNumberTableOffset);\n int lineNumber = readUnsignedShort(currentLineNumberTableOffset + 2);\n currentLineNumberTableOffset += 4;\n createDebugLabel(startPc, labels);\n labels[startPc].addLineNumber(lineNumber);\n }\n }\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n visibleTypeAnnotationOffsets = readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ true);\n // Here we do not extract the labels corresponding to the attribute content. This would\n // require a full parsing of the attribute, which would need to be repeated when parsing\n // the bytecode instructions (see below). Instead, the content of the attribute is read one\n // type annotation at a time (i.e. after a type annotation has been visited, the next type\n // annotation is read), and the labels it contains are also extracted one annotation at a\n // time. This assumes that type annotations are ordered by increasing bytecode offset.\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n invisibleTypeAnnotationOffsets = readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ false);\n // Same comment as above for the RuntimeVisibleTypeAnnotations attribute.\n } else if (Constants.STACK_MAP_TABLE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_FRAMES) == 0) {\n stackMapFrameOffset = currentOffset + 2;\n stackMapTableEndOffset = currentOffset + attributeLength;\n }\n // Here we do not extract the labels corresponding to the attribute content. This would\n // require a full parsing of the attribute, which would need to be repeated when parsing\n // the bytecode instructions (see below). Instead, the content of the attribute is read one\n // frame at a time (i.e. after a frame has been visited, the next frame is read), and the\n // labels it contains are also extracted one frame at a time. Thanks to the ordering of\n // frames, having only a \"one frame lookahead\" is not a problem, i.e. it is not possible to\n // see an offset smaller than the offset of the current instruction and for which no Label\n // exist. Except for UNINITIALIZED type offsets. We solve this by parsing the stack map\n // table without a full decoding (see below).\n } else if (\"StackMap\".equals(attributeName)) {\n if ((context.parsingOptions & SKIP_FRAMES) == 0) {\n stackMapFrameOffset = currentOffset + 2;\n stackMapTableEndOffset = currentOffset + attributeLength;\n compressedFrames = false;\n }\n // IMPORTANT! Here we assume that the frames are ordered, as in the StackMapTable attribute,\n // although this is not guaranteed by the attribute format. This allows an incremental\n // extraction of the labels corresponding to this attribute (see the comment above for the\n // StackMapTable attribute).\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, codeOffset, labels);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n // Initialize the context fields related to stack map frames, and generate the first\n // (implicit) stack map frame, if needed.\n final boolean expandFrames = (context.parsingOptions & EXPAND_FRAMES) != 0;\n if (stackMapFrameOffset != 0) {\n // The bytecode offset of the first explicit frame is not offset_delta + 1 but only\n // offset_delta. Setting the implicit frame offset to -1 allows us to use of the\n // \"offset_delta + 1\" rule in all cases.\n context.currentFrameOffset = -1;\n context.currentFrameType = 0;\n context.currentFrameLocalCount = 0;\n context.currentFrameLocalCountDelta = 0;\n context.currentFrameLocalTypes = new Object[maxLocals];\n context.currentFrameStackCount = 0;\n context.currentFrameStackTypes = new Object[maxStack];\n if (expandFrames) {\n computeImplicitFrame(context);\n }\n // Find the labels for UNINITIALIZED frame types. Instead of decoding each element of the\n // stack map table, we look for 3 consecutive bytes that \"look like\" an UNINITIALIZED type\n // (tag ITEM_Uninitialized, offset within bytecode bounds, NEW instruction at this offset).\n // We may find false positives (i.e. not real UNINITIALIZED types), but this should be rare,\n // and the only consequence will be the creation of an unneeded label. This is better than\n // creating a label for each NEW instruction, and faster than fully decoding the whole stack\n // map table.\n for (int offset = stackMapFrameOffset; offset < stackMapTableEndOffset - 2; ++offset) {\n if (classBuffer[offset] == Frame.ITEM_UNINITIALIZED) {\n int potentialBytecodeOffset = readUnsignedShort(offset + 1);\n if (potentialBytecodeOffset >= 0 && potentialBytecodeOffset < codeLength && (classBuffer[bytecodeStartOffset + potentialBytecodeOffset] & 0xFF) == Opcodes.NEW) {\n createLabel(potentialBytecodeOffset, labels);\n }\n }\n }\n }\n if (expandFrames && (context.parsingOptions & EXPAND_ASM_INSNS) != 0) {\n // Expanding the ASM specific instructions can introduce F_INSERT frames, even if the method\n // does not currently have any frame. These inserted frames must be computed by simulating the\n // effect of the bytecode instructions, one by one, starting from the implicit first frame.\n // For this, MethodWriter needs to know maxLocals before the first instruction is visited. To\n // ensure this, we visit the implicit first frame here (passing only maxLocals - the rest is\n // computed in MethodWriter).\n methodVisitor.visitFrame(Opcodes.F_NEW, maxLocals, null, 0, null);\n }\n // Visit the bytecode instructions. First, introduce state variables for the incremental parsing\n // of the type annotations.\n // Index of the next runtime visible type annotation to read (in the\n // visibleTypeAnnotationOffsets array).\n int currentVisibleTypeAnnotationIndex = 0;\n // The bytecode offset of the next runtime visible type annotation to read, or -1.\n int currentVisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(visibleTypeAnnotationOffsets, 0);\n // Index of the next runtime invisible type annotation to read (in the\n // invisibleTypeAnnotationOffsets array).\n int currentInvisibleTypeAnnotationIndex = 0;\n // The bytecode offset of the next runtime invisible type annotation to read, or -1.\n int currentInvisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(invisibleTypeAnnotationOffsets, 0);\n // Whether a F_INSERT stack map frame must be inserted before the current instruction.\n boolean insertFrame = false;\n // The delta to subtract from a goto_w or jsr_w opcode to get the corresponding goto or jsr\n // opcode, or 0 if goto_w and jsr_w must be left unchanged (i.e. when expanding ASM specific\n // instructions).\n final int wideJumpOpcodeDelta = (context.parsingOptions & EXPAND_ASM_INSNS) == 0 ? Constants.WIDE_JUMP_OPCODE_DELTA : 0;\n currentOffset = bytecodeStartOffset;\n while (currentOffset < bytecodeEndOffset) {\n final int currentBytecodeOffset = currentOffset - bytecodeStartOffset;\n // Visit the label and the line number(s) for this bytecode offset, if any.\n Label currentLabel = labels[currentBytecodeOffset];\n if (currentLabel != null) {\n currentLabel.accept(methodVisitor, (context.parsingOptions & SKIP_DEBUG) == 0);\n }\n // Visit the stack map frame for this bytecode offset, if any.\n while (stackMapFrameOffset != 0 && (context.currentFrameOffset == currentBytecodeOffset || context.currentFrameOffset == -1)) {\n // If there is a stack map frame for this offset, make methodVisitor visit it, and read the\n // next stack map frame if there is one.\n if (context.currentFrameOffset != -1) {\n if (!compressedFrames || expandFrames) {\n methodVisitor.visitFrame(Opcodes.F_NEW, context.currentFrameLocalCount, context.currentFrameLocalTypes, context.currentFrameStackCount, context.currentFrameStackTypes);\n } else {\n methodVisitor.visitFrame(context.currentFrameType, context.currentFrameLocalCountDelta, context.currentFrameLocalTypes, context.currentFrameStackCount, context.currentFrameStackTypes);\n }\n // Since there is already a stack map frame for this bytecode offset, there is no need to\n // insert a new one.\n insertFrame = false;\n }\n if (stackMapFrameOffset < stackMapTableEndOffset) {\n stackMapFrameOffset = readStackMapFrame(stackMapFrameOffset, compressedFrames, expandFrames, context);\n } else {\n stackMapFrameOffset = 0;\n }\n }\n // Insert a stack map frame for this bytecode offset, if requested by setting insertFrame to\n // true during the previous iteration. The actual frame content is computed in MethodWriter.\n if (insertFrame) {\n if ((context.parsingOptions & EXPAND_FRAMES) != 0) {\n methodVisitor.visitFrame(Constants.F_INSERT, 0, null, 0, null);\n }\n insertFrame = false;\n }\n // Visit the instruction at this bytecode offset.\n int opcode = classBuffer[currentOffset] & 0xFF;\n switch (opcode) {\n case Constants.NOP:\n case Constants.ACONST_NULL:\n case Constants.ICONST_M1:\n case Constants.ICONST_0:\n case Constants.ICONST_1:\n case Constants.ICONST_2:\n case Constants.ICONST_3:\n case Constants.ICONST_4:\n case Constants.ICONST_5:\n case Constants.LCONST_0:\n case Constants.LCONST_1:\n case Constants.FCONST_0:\n case Constants.FCONST_1:\n case Constants.FCONST_2:\n case Constants.DCONST_0:\n case Constants.DCONST_1:\n case Constants.IALOAD:\n case Constants.LALOAD:\n case Constants.FALOAD:\n case Constants.DALOAD:\n case Constants.AALOAD:\n case Constants.BALOAD:\n case Constants.CALOAD:\n case Constants.SALOAD:\n case Constants.IASTORE:\n case Constants.LASTORE:\n case Constants.FASTORE:\n case Constants.DASTORE:\n case Constants.AASTORE:\n case Constants.BASTORE:\n case Constants.CASTORE:\n case Constants.SASTORE:\n case Constants.POP:\n case Constants.POP2:\n case Constants.DUP:\n case Constants.DUP_X1:\n case Constants.DUP_X2:\n case Constants.DUP2:\n case Constants.DUP2_X1:\n case Constants.DUP2_X2:\n case Constants.SWAP:\n case Constants.IADD:\n case Constants.LADD:\n case Constants.FADD:\n case Constants.DADD:\n case Constants.ISUB:\n case Constants.LSUB:\n case Constants.FSUB:\n case Constants.DSUB:\n case Constants.IMUL:\n case Constants.LMUL:\n case Constants.FMUL:\n case Constants.DMUL:\n case Constants.IDIV:\n case Constants.LDIV:\n case Constants.FDIV:\n case Constants.DDIV:\n case Constants.IREM:\n case Constants.LREM:\n case Constants.FREM:\n case Constants.DREM:\n case Constants.INEG:\n case Constants.LNEG:\n case Constants.FNEG:\n case Constants.DNEG:\n case Constants.ISHL:\n case Constants.LSHL:\n case Constants.ISHR:\n case Constants.LSHR:\n case Constants.IUSHR:\n case Constants.LUSHR:\n case Constants.IAND:\n case Constants.LAND:\n case Constants.IOR:\n case Constants.LOR:\n case Constants.IXOR:\n case Constants.LXOR:\n case Constants.I2L:\n case Constants.I2F:\n case Constants.I2D:\n case Constants.L2I:\n case Constants.L2F:\n case Constants.L2D:\n case Constants.F2I:\n case Constants.F2L:\n case Constants.F2D:\n case Constants.D2I:\n case Constants.D2L:\n case Constants.D2F:\n case Constants.I2B:\n case Constants.I2C:\n case Constants.I2S:\n case Constants.LCMP:\n case Constants.FCMPL:\n case Constants.FCMPG:\n case Constants.DCMPL:\n case Constants.DCMPG:\n case Constants.IRETURN:\n case Constants.LRETURN:\n case Constants.FRETURN:\n case Constants.DRETURN:\n case Constants.ARETURN:\n case Constants.RETURN:\n case Constants.ARRAYLENGTH:\n case Constants.ATHROW:\n case Constants.MONITORENTER:\n case Constants.MONITOREXIT:\n methodVisitor.visitInsn(opcode);\n currentOffset += 1;\n break;\n case Constants.ILOAD_0:\n case Constants.ILOAD_1:\n case Constants.ILOAD_2:\n case Constants.ILOAD_3:\n case Constants.LLOAD_0:\n case Constants.LLOAD_1:\n case Constants.LLOAD_2:\n case Constants.LLOAD_3:\n case Constants.FLOAD_0:\n case Constants.FLOAD_1:\n case Constants.FLOAD_2:\n case Constants.FLOAD_3:\n case Constants.DLOAD_0:\n case Constants.DLOAD_1:\n case Constants.DLOAD_2:\n case Constants.DLOAD_3:\n case Constants.ALOAD_0:\n case Constants.ALOAD_1:\n case Constants.ALOAD_2:\n case Constants.ALOAD_3:\n opcode -= Constants.ILOAD_0;\n methodVisitor.visitVarInsn(Opcodes.ILOAD + (opcode >> 2), opcode & 0x3);\n currentOffset += 1;\n break;\n case Constants.ISTORE_0:\n case Constants.ISTORE_1:\n case Constants.ISTORE_2:\n case Constants.ISTORE_3:\n case Constants.LSTORE_0:\n case Constants.LSTORE_1:\n case Constants.LSTORE_2:\n case Constants.LSTORE_3:\n case Constants.FSTORE_0:\n case Constants.FSTORE_1:\n case Constants.FSTORE_2:\n case Constants.FSTORE_3:\n case Constants.DSTORE_0:\n case Constants.DSTORE_1:\n case Constants.DSTORE_2:\n case Constants.DSTORE_3:\n case Constants.ASTORE_0:\n case Constants.ASTORE_1:\n case Constants.ASTORE_2:\n case Constants.ASTORE_3:\n opcode -= Constants.ISTORE_0;\n methodVisitor.visitVarInsn(Opcodes.ISTORE + (opcode >> 2), opcode & 0x3);\n currentOffset += 1;\n break;\n case Constants.IFEQ:\n case Constants.IFNE:\n case Constants.IFLT:\n case Constants.IFGE:\n case Constants.IFGT:\n case Constants.IFLE:\n case Constants.IF_ICMPEQ:\n case Constants.IF_ICMPNE:\n case Constants.IF_ICMPLT:\n case Constants.IF_ICMPGE:\n case Constants.IF_ICMPGT:\n case Constants.IF_ICMPLE:\n case Constants.IF_ACMPEQ:\n case Constants.IF_ACMPNE:\n case Constants.GOTO:\n case Constants.JSR:\n case Constants.IFNULL:\n case Constants.IFNONNULL:\n methodVisitor.visitJumpInsn(opcode, labels[currentBytecodeOffset + readShort(currentOffset + 1)]);\n currentOffset += 3;\n break;\n case Constants.GOTO_W:\n case Constants.JSR_W:\n methodVisitor.visitJumpInsn(opcode - wideJumpOpcodeDelta, labels[currentBytecodeOffset + readInt(currentOffset + 1)]);\n currentOffset += 5;\n break;\n case Constants.ASM_IFEQ:\n case Constants.ASM_IFNE:\n case Constants.ASM_IFLT:\n case Constants.ASM_IFGE:\n case Constants.ASM_IFGT:\n case Constants.ASM_IFLE:\n case Constants.ASM_IF_ICMPEQ:\n case Constants.ASM_IF_ICMPNE:\n case Constants.ASM_IF_ICMPLT:\n case Constants.ASM_IF_ICMPGE:\n case Constants.ASM_IF_ICMPGT:\n case Constants.ASM_IF_ICMPLE:\n case Constants.ASM_IF_ACMPEQ:\n case Constants.ASM_IF_ACMPNE:\n case Constants.ASM_GOTO:\n case Constants.ASM_JSR:\n case Constants.ASM_IFNULL:\n case Constants.ASM_IFNONNULL: {\n // A forward jump with an offset > 32767. In this case we automatically replace ASM_GOTO\n // with GOTO_W, ASM_JSR with JSR_W and ASM_IFxxx with IFNOTxxx GOTO_W L:...,\n // where IFNOTxxx is the \"opposite\" opcode of ASMS_IFxxx (e.g. IFNE for ASM_IFEQ) and\n // where designates the instruction just after the GOTO_W.\n // First, change the ASM specific opcodes ASM_IFEQ ... ASM_JSR, ASM_IFNULL and\n // ASM_IFNONNULL to IFEQ ... JSR, IFNULL and IFNONNULL.\n opcode = opcode < Constants.ASM_IFNULL ? opcode - Constants.ASM_OPCODE_DELTA : opcode - Constants.ASM_IFNULL_OPCODE_DELTA;\n Label target = labels[currentBytecodeOffset + readUnsignedShort(currentOffset + 1)];\n if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) {\n // Replace GOTO with GOTO_W and JSR with JSR_W.\n methodVisitor.visitJumpInsn(opcode + Constants.WIDE_JUMP_OPCODE_DELTA, target);\n } else {\n // Compute the \"opposite\" of opcode. This can be done by flipping the least\n // significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ\n // (with a pre and post offset by 1).\n opcode = opcode < Opcodes.GOTO ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1;\n Label endif = createLabel(currentBytecodeOffset + 3, labels);\n methodVisitor.visitJumpInsn(opcode, endif);\n methodVisitor.visitJumpInsn(Constants.GOTO_W, target);\n // endif designates the instruction just after GOTO_W, and is visited as part of the\n // next instruction. Since it is a jump target, we need to insert a frame here.\n insertFrame = true;\n }\n currentOffset += 3;\n break;\n }\n case Constants.ASM_GOTO_W:\n // Replace ASM_GOTO_W with GOTO_W.\n methodVisitor.visitJumpInsn(Constants.GOTO_W, labels[currentBytecodeOffset + readInt(currentOffset + 1)]);\n // The instruction just after is a jump target (because ASM_GOTO_W is used in patterns\n // IFNOTxxx ASM_GOTO_W L:..., see MethodWriter), so we need to insert a frame\n // here.\n insertFrame = true;\n currentOffset += 5;\n break;\n case Constants.WIDE:\n opcode = classBuffer[currentOffset + 1] & 0xFF;\n if (opcode == Opcodes.IINC) {\n methodVisitor.visitIincInsn(readUnsignedShort(currentOffset + 2), readShort(currentOffset + 4));\n currentOffset += 6;\n } else {\n methodVisitor.visitVarInsn(opcode, readUnsignedShort(currentOffset + 2));\n currentOffset += 4;\n }\n break;\n case Constants.TABLESWITCH: {\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (currentBytecodeOffset & 3);\n // Read the instruction.\n Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)];\n int low = readInt(currentOffset + 4);\n int high = readInt(currentOffset + 8);\n currentOffset += 12;\n Label[] table = new Label[high - low + 1];\n for (int i = 0; i < table.length; ++i) {\n table[i] = labels[currentBytecodeOffset + readInt(currentOffset)];\n currentOffset += 4;\n }\n methodVisitor.visitTableSwitchInsn(low, high, defaultLabel, table);\n break;\n }\n case Constants.LOOKUPSWITCH: {\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (currentBytecodeOffset & 3);\n // Read the instruction.\n Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)];\n int numPairs = readInt(currentOffset + 4);\n currentOffset += 8;\n int[] keys = new int[numPairs];\n Label[] values = new Label[numPairs];\n for (int i = 0; i < numPairs; ++i) {\n keys[i] = readInt(currentOffset);\n values[i] = labels[currentBytecodeOffset + readInt(currentOffset + 4)];\n currentOffset += 8;\n }\n methodVisitor.visitLookupSwitchInsn(defaultLabel, keys, values);\n break;\n }\n case Constants.ILOAD:\n case Constants.LLOAD:\n case Constants.FLOAD:\n case Constants.DLOAD:\n case Constants.ALOAD:\n case Constants.ISTORE:\n case Constants.LSTORE:\n case Constants.FSTORE:\n case Constants.DSTORE:\n case Constants.ASTORE:\n case Constants.RET:\n methodVisitor.visitVarInsn(opcode, classBuffer[currentOffset + 1] & 0xFF);\n currentOffset += 2;\n break;\n case Constants.BIPUSH:\n case Constants.NEWARRAY:\n methodVisitor.visitIntInsn(opcode, classBuffer[currentOffset + 1]);\n currentOffset += 2;\n break;\n case Constants.SIPUSH:\n methodVisitor.visitIntInsn(opcode, readShort(currentOffset + 1));\n currentOffset += 3;\n break;\n case Constants.LDC:\n methodVisitor.visitLdcInsn(readConst(classBuffer[currentOffset + 1] & 0xFF, charBuffer));\n currentOffset += 2;\n break;\n case Constants.LDC_W:\n case Constants.LDC2_W:\n methodVisitor.visitLdcInsn(readConst(readUnsignedShort(currentOffset + 1), charBuffer));\n currentOffset += 3;\n break;\n case Constants.GETSTATIC:\n case Constants.PUTSTATIC:\n case Constants.GETFIELD:\n case Constants.PUTFIELD:\n case Constants.INVOKEVIRTUAL:\n case Constants.INVOKESPECIAL:\n case Constants.INVOKESTATIC:\n case Constants.INVOKEINTERFACE: {\n int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)];\n String owner = readClass(cpInfoOffset, charBuffer);\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n if (opcode < Opcodes.INVOKEVIRTUAL) {\n methodVisitor.visitFieldInsn(opcode, owner, name, descriptor);\n } else {\n boolean isInterface = classBuffer[cpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG;\n methodVisitor.visitMethodInsn(opcode, owner, name, descriptor, isInterface);\n }\n if (opcode == Opcodes.INVOKEINTERFACE) {\n currentOffset += 5;\n } else {\n currentOffset += 3;\n }\n break;\n }\n case Constants.INVOKEDYNAMIC: {\n int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)];\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)];\n Handle handle = (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n Object[] bootstrapMethodArguments = new Object[readUnsignedShort(bootstrapMethodOffset + 2)];\n bootstrapMethodOffset += 4;\n for (int i = 0; i < bootstrapMethodArguments.length; i++) {\n bootstrapMethodArguments[i] = readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n bootstrapMethodOffset += 2;\n }\n methodVisitor.visitInvokeDynamicInsn(name, descriptor, handle, bootstrapMethodArguments);\n currentOffset += 5;\n break;\n }\n case Constants.NEW:\n case Constants.ANEWARRAY:\n case Constants.CHECKCAST:\n case Constants.INSTANCEOF:\n methodVisitor.visitTypeInsn(opcode, readClass(currentOffset + 1, charBuffer));\n currentOffset += 3;\n break;\n case Constants.IINC:\n methodVisitor.visitIincInsn(classBuffer[currentOffset + 1] & 0xFF, classBuffer[currentOffset + 2]);\n currentOffset += 3;\n break;\n case Constants.MULTIANEWARRAY:\n methodVisitor.visitMultiANewArrayInsn(readClass(currentOffset + 1, charBuffer), classBuffer[currentOffset + 3] & 0xFF);\n currentOffset += 4;\n break;\n default:\n throw new AssertionError();\n }\n // Visit the runtime visible instruction annotations, if any.\n while (visibleTypeAnnotationOffsets != null && currentVisibleTypeAnnotationIndex < visibleTypeAnnotationOffsets.length && currentVisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) {\n if (currentVisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) {\n // Parse the target_type, target_info and target_path fields.\n int currentAnnotationOffset = readTypeAnnotationTarget(context, visibleTypeAnnotationOffsets[currentVisibleTypeAnnotationIndex]);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitInsnAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n currentVisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(visibleTypeAnnotationOffsets, ++currentVisibleTypeAnnotationIndex);\n }\n // Visit the runtime invisible instruction annotations, if any.\n while (invisibleTypeAnnotationOffsets != null && currentInvisibleTypeAnnotationIndex < invisibleTypeAnnotationOffsets.length && currentInvisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) {\n if (currentInvisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) {\n // Parse the target_type, target_info and target_path fields.\n int currentAnnotationOffset = readTypeAnnotationTarget(context, invisibleTypeAnnotationOffsets[currentInvisibleTypeAnnotationIndex]);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitInsnAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n currentInvisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(invisibleTypeAnnotationOffsets, ++currentInvisibleTypeAnnotationIndex);\n }\n }\n if (labels[codeLength] != null) {\n methodVisitor.visitLabel(labels[codeLength]);\n }\n // Visit LocalVariableTable and LocalVariableTypeTable attributes.\n if (localVariableTableOffset != 0 && (context.parsingOptions & SKIP_DEBUG) == 0) {\n // The (start_pc, index, signature_index) fields of each entry of the LocalVariableTypeTable.\n int[] typeTable = null;\n if (localVariableTypeTableOffset != 0) {\n typeTable = new int[readUnsignedShort(localVariableTypeTableOffset) * 3];\n currentOffset = localVariableTypeTableOffset + 2;\n int typeTableIndex = typeTable.length;\n while (typeTableIndex > 0) {\n // Store the offset of 'signature_index', and the value of 'index' and 'start_pc'.\n typeTable[--typeTableIndex] = currentOffset + 6;\n typeTable[--typeTableIndex] = readUnsignedShort(currentOffset + 8);\n typeTable[--typeTableIndex] = readUnsignedShort(currentOffset);\n currentOffset += 10;\n }\n }\n int localVariableTableLength = readUnsignedShort(localVariableTableOffset);\n currentOffset = localVariableTableOffset + 2;\n while (localVariableTableLength-- > 0) {\n int startPc = readUnsignedShort(currentOffset);\n int length = readUnsignedShort(currentOffset + 2);\n String name = readUTF8(currentOffset + 4, charBuffer);\n String descriptor = readUTF8(currentOffset + 6, charBuffer);\n int index = readUnsignedShort(currentOffset + 8);\n currentOffset += 10;\n String signature = null;\n if (typeTable != null) {\n for (int i = 0; i < typeTable.length; i += 3) {\n if (typeTable[i] == startPc && typeTable[i + 1] == index) {\n signature = readUTF8(typeTable[i + 2], charBuffer);\n break;\n }\n }\n }\n methodVisitor.visitLocalVariable(name, descriptor, signature, labels[startPc], labels[startPc + length], index);\n }\n }\n // Visit the local variable type annotations of the RuntimeVisibleTypeAnnotations attribute.\n if (visibleTypeAnnotationOffsets != null) {\n for (int typeAnnotationOffset : visibleTypeAnnotationOffsets) {\n int targetType = readByte(typeAnnotationOffset);\n if (targetType == TypeReference.LOCAL_VARIABLE || targetType == TypeReference.RESOURCE_VARIABLE) {\n // Parse the target_type, target_info and target_path fields.\n currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitLocalVariableAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, context.currentLocalVariableAnnotationRangeStarts, context.currentLocalVariableAnnotationRangeEnds, context.currentLocalVariableAnnotationRangeIndices, annotationDescriptor,\n /* visible = */ true), currentOffset,\n /* named = */ true, charBuffer);\n }\n }\n }\n // Visit the local variable type annotations of the RuntimeInvisibleTypeAnnotations attribute.\n if (invisibleTypeAnnotationOffsets != null) {\n for (int typeAnnotationOffset : invisibleTypeAnnotationOffsets) {\n int targetType = readByte(typeAnnotationOffset);\n if (targetType == TypeReference.LOCAL_VARIABLE || targetType == TypeReference.RESOURCE_VARIABLE) {\n // Parse the target_type, target_info and target_path fields.\n currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitLocalVariableAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, context.currentLocalVariableAnnotationRangeStarts, context.currentLocalVariableAnnotationRangeEnds, context.currentLocalVariableAnnotationRangeIndices, annotationDescriptor,\n /* visible = */ false), currentOffset,\n /* named = */ true, charBuffer);\n }\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in MethodWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n methodVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the max stack and max locals values.\n methodVisitor.visitMaxs(maxStack, maxLocals);\n }\n\n /**\n * Returns the label corresponding to the given bytecode offset. The default implementation of\n * this method creates a label for the given offset if it has not been already created.\n *\n * @param bytecodeOffset a bytecode offset in a method.\n * @param labels the already created labels, indexed by their offset. If a label already exists\n * for bytecodeOffset this method must not create a new one. Otherwise it must store the new\n * label in this array.\n * @return a non null Label, which must be equal to labels[bytecodeOffset].\n */\n protected Label readLabel(final int bytecodeOffset, final Label[] labels) {\n if (labels[bytecodeOffset] == null) {\n labels[bytecodeOffset] = new Label();\n }\n return labels[bytecodeOffset];\n }\n\n /**\n * Creates a label without the {@link Label#FLAG_DEBUG_ONLY} flag set, for the given bytecode\n * offset. The label is created with a call to {@link #readLabel} and its {@link\n * Label#FLAG_DEBUG_ONLY} flag is cleared.\n *\n * @param bytecodeOffset a bytecode offset in a method.\n * @param labels the already created labels, indexed by their offset.\n * @return a Label without the {@link Label#FLAG_DEBUG_ONLY} flag set.\n */\n private Label createLabel(final int bytecodeOffset, final Label[] labels) {\n Label label = readLabel(bytecodeOffset, labels);\n label.flags &= ~Label.FLAG_DEBUG_ONLY;\n return label;\n }\n\n /**\n * Creates a label with the {@link Label#FLAG_DEBUG_ONLY} flag set, if there is no already\n * existing label for the given bytecode offset (otherwise does nothing). The label is created\n * with a call to {@link #readLabel}.\n *\n * @param bytecodeOffset a bytecode offset in a method.\n * @param labels the already created labels, indexed by their offset.\n */\n private void createDebugLabel(final int bytecodeOffset, final Label[] labels) {\n if (labels[bytecodeOffset] == null) {\n readLabel(bytecodeOffset, labels).flags |= Label.FLAG_DEBUG_ONLY;\n }\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse annotations, type annotations and parameter annotations\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Parses a Runtime[In]VisibleTypeAnnotations attribute to find the offset of each type_annotation\n * entry it contains, to find the corresponding labels, and to visit the try catch block\n * annotations.\n *\n * @param methodVisitor the method visitor to be used to visit the try catch block annotations.\n * @param context information about the class being parsed.\n * @param runtimeTypeAnnotationsOffset the start offset of a Runtime[In]VisibleTypeAnnotations\n * attribute, excluding the attribute_info's attribute_name_index and attribute_length fields.\n * @param visible true if the attribute to parse is a RuntimeVisibleTypeAnnotations attribute,\n * false it is a RuntimeInvisibleTypeAnnotations attribute.\n * @return the start offset of each entry of the Runtime[In]VisibleTypeAnnotations_attribute's\n * 'annotations' array field.\n */\n private int[] readTypeAnnotations(final MethodVisitor methodVisitor, final Context context, final int runtimeTypeAnnotationsOffset, final boolean visible) {\n char[] charBuffer = context.charBuffer;\n int currentOffset = runtimeTypeAnnotationsOffset;\n // Read the num_annotations field and create an array to store the type_annotation offsets.\n int[] typeAnnotationsOffsets = new int[readUnsignedShort(currentOffset)];\n currentOffset += 2;\n // Parse the 'annotations' array field.\n for (int i = 0; i < typeAnnotationsOffsets.length; ++i) {\n typeAnnotationsOffsets[i] = currentOffset;\n // Parse the type_annotation's target_type and the target_info fields. The size of the\n // target_info field depends on the value of target_type.\n int targetType = readInt(currentOffset);\n switch (targetType >>> 24) {\n case TypeReference.LOCAL_VARIABLE:\n case TypeReference.RESOURCE_VARIABLE:\n // A localvar_target has a variable size, which depends on the value of their table_length\n // field. It also references bytecode offsets, for which we need labels.\n int tableLength = readUnsignedShort(currentOffset + 1);\n currentOffset += 3;\n while (tableLength-- > 0) {\n int startPc = readUnsignedShort(currentOffset);\n int length = readUnsignedShort(currentOffset + 2);\n // Skip the index field (2 bytes).\n currentOffset += 6;\n createLabel(startPc, context.currentMethodLabels);\n createLabel(startPc + length, context.currentMethodLabels);\n }\n break;\n case TypeReference.CAST:\n case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:\n case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT:\n currentOffset += 4;\n break;\n case TypeReference.CLASS_EXTENDS:\n case TypeReference.CLASS_TYPE_PARAMETER_BOUND:\n case TypeReference.METHOD_TYPE_PARAMETER_BOUND:\n case TypeReference.THROWS:\n case TypeReference.EXCEPTION_PARAMETER:\n case TypeReference.INSTANCEOF:\n case TypeReference.NEW:\n case TypeReference.CONSTRUCTOR_REFERENCE:\n case TypeReference.METHOD_REFERENCE:\n currentOffset += 3;\n break;\n case TypeReference.CLASS_TYPE_PARAMETER:\n case TypeReference.METHOD_TYPE_PARAMETER:\n case TypeReference.METHOD_FORMAL_PARAMETER:\n case TypeReference.FIELD:\n case TypeReference.METHOD_RETURN:\n case TypeReference.METHOD_RECEIVER:\n default:\n // TypeReference type which can't be used in Code attribute, or which is unknown.\n throw new IllegalArgumentException();\n }\n // Parse the rest of the type_annotation structure, starting with the target_path structure\n // (whose size depends on its path_length field).\n int pathLength = readByte(currentOffset);\n if ((targetType >>> 24) == TypeReference.EXCEPTION_PARAMETER) {\n // Parse the target_path structure and create a corresponding TypePath.\n TypePath path = pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset);\n currentOffset += 1 + 2 * pathLength;\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentOffset = readElementValues(methodVisitor.visitTryCatchAnnotation(targetType & 0xFFFFFF00, path, annotationDescriptor, visible), currentOffset,\n /* named = */ true, charBuffer);\n } else {\n // We don't want to visit the other target_type annotations, so we just skip them (which\n // requires some parsing because the element_value_pairs array has a variable size). First,\n // skip the target_path structure:\n currentOffset += 3 + 2 * pathLength;\n // Then skip the num_element_value_pairs and element_value_pairs fields (by reading them\n // with a null AnnotationVisitor).\n currentOffset = readElementValues(\n /* annotationVisitor = */ null, currentOffset, /* named = */ true, charBuffer);\n }\n }\n return typeAnnotationsOffsets;\n }\n\n /**\n * Returns the bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or\n * -1 if there is no such type_annotation of if it does not have a bytecode offset.\n *\n * @param typeAnnotationOffsets the offset of each 'type_annotation' entry in a\n * Runtime[In]VisibleTypeAnnotations attribute, or {@literal null}.\n * @param typeAnnotationIndex the index a 'type_annotation' entry in typeAnnotationOffsets.\n * @return bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or -1\n * if there is no such type_annotation of if it does not have a bytecode offset.\n */\n private int getTypeAnnotationBytecodeOffset(final int[] typeAnnotationOffsets, final int typeAnnotationIndex) {\n if (typeAnnotationOffsets == null || typeAnnotationIndex >= typeAnnotationOffsets.length || readByte(typeAnnotationOffsets[typeAnnotationIndex]) < TypeReference.INSTANCEOF) {\n return -1;\n }\n return readUnsignedShort(typeAnnotationOffsets[typeAnnotationIndex] + 1);\n }\n\n /**\n * Parses the header of a JVMS type_annotation structure to extract its target_type, target_info\n * and target_path (the result is stored in the given context), and returns the start offset of\n * the rest of the type_annotation structure.\n *\n * @param context information about the class being parsed. This is where the extracted\n * target_type and target_path must be stored.\n * @param typeAnnotationOffset the start offset of a type_annotation structure.\n * @return the start offset of the rest of the type_annotation structure.\n */\n private int readTypeAnnotationTarget(final Context context, final int typeAnnotationOffset) {\n int currentOffset = typeAnnotationOffset;\n // Parse and store the target_type structure.\n int targetType = readInt(typeAnnotationOffset);\n switch (targetType >>> 24) {\n case TypeReference.CLASS_TYPE_PARAMETER:\n case TypeReference.METHOD_TYPE_PARAMETER:\n case TypeReference.METHOD_FORMAL_PARAMETER:\n targetType &= 0xFFFF0000;\n currentOffset += 2;\n break;\n case TypeReference.FIELD:\n case TypeReference.METHOD_RETURN:\n case TypeReference.METHOD_RECEIVER:\n targetType &= 0xFF000000;\n currentOffset += 1;\n break;\n case TypeReference.LOCAL_VARIABLE:\n case TypeReference.RESOURCE_VARIABLE:\n targetType &= 0xFF000000;\n int tableLength = readUnsignedShort(currentOffset + 1);\n currentOffset += 3;\n context.currentLocalVariableAnnotationRangeStarts = new Label[tableLength];\n context.currentLocalVariableAnnotationRangeEnds = new Label[tableLength];\n context.currentLocalVariableAnnotationRangeIndices = new int[tableLength];\n for (int i = 0; i < tableLength; ++i) {\n int startPc = readUnsignedShort(currentOffset);\n int length = readUnsignedShort(currentOffset + 2);\n int index = readUnsignedShort(currentOffset + 4);\n currentOffset += 6;\n context.currentLocalVariableAnnotationRangeStarts[i] = createLabel(startPc, context.currentMethodLabels);\n context.currentLocalVariableAnnotationRangeEnds[i] = createLabel(startPc + length, context.currentMethodLabels);\n context.currentLocalVariableAnnotationRangeIndices[i] = index;\n }\n break;\n case TypeReference.CAST:\n case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:\n case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT:\n targetType &= 0xFF0000FF;\n currentOffset += 4;\n break;\n case TypeReference.CLASS_EXTENDS:\n case TypeReference.CLASS_TYPE_PARAMETER_BOUND:\n case TypeReference.METHOD_TYPE_PARAMETER_BOUND:\n case TypeReference.THROWS:\n case TypeReference.EXCEPTION_PARAMETER:\n targetType &= 0xFFFFFF00;\n currentOffset += 3;\n break;\n case TypeReference.INSTANCEOF:\n case TypeReference.NEW:\n case TypeReference.CONSTRUCTOR_REFERENCE:\n case TypeReference.METHOD_REFERENCE:\n targetType &= 0xFF000000;\n currentOffset += 3;\n break;\n default:\n throw new IllegalArgumentException();\n }\n context.currentTypeAnnotationTarget = targetType;\n // Parse and store the target_path structure.\n int pathLength = readByte(currentOffset);\n context.currentTypeAnnotationTargetPath = pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset);\n // Return the start offset of the rest of the type_annotation structure.\n return currentOffset + 1 + 2 * pathLength;\n }\n\n /**\n * Reads a Runtime[In]VisibleParameterAnnotations attribute and makes the given visitor visit it.\n *\n * @param methodVisitor the visitor that must visit the parameter annotations.\n * @param context information about the class being parsed.\n * @param runtimeParameterAnnotationsOffset the start offset of a\n * Runtime[In]VisibleParameterAnnotations attribute, excluding the attribute_info's\n * attribute_name_index and attribute_length fields.\n * @param visible true if the attribute to parse is a RuntimeVisibleParameterAnnotations\n * attribute, false it is a RuntimeInvisibleParameterAnnotations attribute.\n */\n private void readParameterAnnotations(final MethodVisitor methodVisitor, final Context context, final int runtimeParameterAnnotationsOffset, final boolean visible) {\n int currentOffset = runtimeParameterAnnotationsOffset;\n int numParameters = classFileBuffer[currentOffset++] & 0xFF;\n methodVisitor.visitAnnotableParameterCount(numParameters, visible);\n char[] charBuffer = context.charBuffer;\n for (int i = 0; i < numParameters; ++i) {\n int numAnnotations = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentOffset = readElementValues(methodVisitor.visitParameterAnnotation(i, annotationDescriptor, visible), currentOffset,\n /* named = */ true, charBuffer);\n }\n }\n }\n\n /**\n * Reads the element values of a JVMS 'annotation' structure and makes the given visitor visit\n * them. This method can also be used to read the values of the JVMS 'array_value' field of an\n * annotation's 'element_value'.\n *\n * @param annotationVisitor the visitor that must visit the values.\n * @param annotationOffset the start offset of an 'annotation' structure (excluding its type_index\n * field) or of an 'array_value' structure.\n * @param named if the annotation values are named or not. This should be true to parse the values\n * of a JVMS 'annotation' structure, and false to parse the JVMS 'array_value' of an\n * annotation's element_value.\n * @param charBuffer the buffer used to read strings in the constant pool.\n * @return the end offset of the JVMS 'annotation' or 'array_value' structure.\n */\n private int readElementValues(final AnnotationVisitor annotationVisitor, final int annotationOffset, final boolean named, final char[] charBuffer) {\n int currentOffset = annotationOffset;\n // Read the num_element_value_pairs field (or num_values field for an array_value).\n int numElementValuePairs = readUnsignedShort(currentOffset);\n currentOffset += 2;\n if (named) {\n // Parse the element_value_pairs array.\n while (numElementValuePairs-- > 0) {\n String elementName = readUTF8(currentOffset, charBuffer);\n currentOffset = readElementValue(annotationVisitor, currentOffset + 2, elementName, charBuffer);\n }\n } else {\n // Parse the array_value array.\n while (numElementValuePairs-- > 0) {\n currentOffset = readElementValue(annotationVisitor, currentOffset, /* named = */ null, charBuffer);\n }\n }\n if (annotationVisitor != null) {\n annotationVisitor.visitEnd();\n }\n return currentOffset;\n }\n\n /**\n * Reads a JVMS 'element_value' structure and makes the given visitor visit it.\n *\n * @param annotationVisitor the visitor that must visit the element_value structure.\n * @param elementValueOffset the start offset in {@link #classFileBuffer} of the element_value\n * structure to be read.\n * @param elementName the name of the element_value structure to be read, or {@literal null}.\n * @param charBuffer the buffer used to read strings in the constant pool.\n * @return the end offset of the JVMS 'element_value' structure.\n */\n private int readElementValue(final AnnotationVisitor annotationVisitor, final int elementValueOffset, final String elementName, final char[] charBuffer) {\n int currentOffset = elementValueOffset;\n if (annotationVisitor == null) {\n switch (classFileBuffer[currentOffset] & 0xFF) {\n case 'e': // enum_const_value\n return currentOffset + 5;\n case '@': // annotation_value\n return readElementValues(null, currentOffset + 3, /* named = */ true, charBuffer);\n case '[': // array_value\n return readElementValues(null, currentOffset + 1, /* named = */ false, charBuffer);\n default:\n return currentOffset + 3;\n }\n }\n switch (classFileBuffer[currentOffset++] & 0xFF) {\n case 'B': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]));\n currentOffset += 2;\n break;\n case 'C': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]));\n currentOffset += 2;\n break;\n case 'D': // const_value_index, CONSTANT_Double\n case 'F': // const_value_index, CONSTANT_Float\n case 'I': // const_value_index, CONSTANT_Integer\n case 'J': // const_value_index, CONSTANT_Long\n annotationVisitor.visit(elementName, readConst(readUnsignedShort(currentOffset), charBuffer));\n currentOffset += 2;\n break;\n case 'S': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]));\n currentOffset += 2;\n break;\n case 'Z': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]) == 0 ? Boolean.FALSE : Boolean.TRUE);\n currentOffset += 2;\n break;\n case 's': // const_value_index, CONSTANT_Utf8\n annotationVisitor.visit(elementName, readUTF8(currentOffset, charBuffer));\n currentOffset += 2;\n break;\n case 'e': // enum_const_value\n annotationVisitor.visitEnum(elementName, readUTF8(currentOffset, charBuffer), readUTF8(currentOffset + 2, charBuffer));\n currentOffset += 4;\n break;\n case 'c': // class_info\n annotationVisitor.visit(elementName, Type.getType(readUTF8(currentOffset, charBuffer)));\n currentOffset += 2;\n break;\n case '@': // annotation_value\n currentOffset = readElementValues(annotationVisitor.visitAnnotation(elementName, readUTF8(currentOffset, charBuffer)), currentOffset + 2, true, charBuffer);\n break;\n case '[': // array_value\n int numValues = readUnsignedShort(currentOffset);\n currentOffset += 2;\n if (numValues == 0) {\n return readElementValues(annotationVisitor.visitArray(elementName), currentOffset - 2,\n /* named = */ false, charBuffer);\n }\n switch (classFileBuffer[currentOffset] & 0xFF) {\n case 'B':\n byte[] byteValues = new byte[numValues];\n for (int i = 0; i < numValues; i++) {\n byteValues[i] = (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, byteValues);\n break;\n case 'Z':\n boolean[] booleanValues = new boolean[numValues];\n for (int i = 0; i < numValues; i++) {\n booleanValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]) != 0;\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, booleanValues);\n break;\n case 'S':\n short[] shortValues = new short[numValues];\n for (int i = 0; i < numValues; i++) {\n shortValues[i] = (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, shortValues);\n break;\n case 'C':\n char[] charValues = new char[numValues];\n for (int i = 0; i < numValues; i++) {\n charValues[i] = (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, charValues);\n break;\n case 'I':\n int[] intValues = new int[numValues];\n for (int i = 0; i < numValues; i++) {\n intValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, intValues);\n break;\n case 'J':\n long[] longValues = new long[numValues];\n for (int i = 0; i < numValues; i++) {\n longValues[i] = readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, longValues);\n break;\n case 'F':\n float[] floatValues = new float[numValues];\n for (int i = 0; i < numValues; i++) {\n floatValues[i] = Float.intBitsToFloat(readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]));\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, floatValues);\n break;\n case 'D':\n double[] doubleValues = new double[numValues];\n for (int i = 0; i < numValues; i++) {\n doubleValues[i] = Double.longBitsToDouble(readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]));\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, doubleValues);\n break;\n default:\n currentOffset = readElementValues(annotationVisitor.visitArray(elementName), currentOffset - 2,\n /* named = */ false, charBuffer);\n break;\n }\n break;\n default:\n throw new IllegalArgumentException();\n }\n return currentOffset;\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse stack map frames\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Computes the implicit frame of the method currently being parsed (as defined in the given\n * {@link Context}) and stores it in the given context.\n *\n * @param context information about the class being parsed.\n */\n private void computeImplicitFrame(final Context context) {\n String methodDescriptor = context.currentMethodDescriptor;\n Object[] locals = context.currentFrameLocalTypes;\n int numLocal = 0;\n if ((context.currentMethodAccessFlags & Opcodes.ACC_STATIC) == 0) {\n if (\"\".equals(context.currentMethodName)) {\n locals[numLocal++] = Opcodes.UNINITIALIZED_THIS;\n } else {\n locals[numLocal++] = readClass(header + 2, context.charBuffer);\n }\n }\n // Parse the method descriptor, one argument type descriptor at each iteration. Start by\n // skipping the first method descriptor character, which is always '('.\n int currentMethodDescritorOffset = 1;\n while (true) {\n int currentArgumentDescriptorStartOffset = currentMethodDescritorOffset;\n switch (methodDescriptor.charAt(currentMethodDescritorOffset++)) {\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n locals[numLocal++] = Opcodes.INTEGER;\n break;\n case 'F':\n locals[numLocal++] = Opcodes.FLOAT;\n break;\n case 'J':\n locals[numLocal++] = Opcodes.LONG;\n break;\n case 'D':\n locals[numLocal++] = Opcodes.DOUBLE;\n break;\n case '[':\n while (methodDescriptor.charAt(currentMethodDescritorOffset) == '[') {\n ++currentMethodDescritorOffset;\n }\n if (methodDescriptor.charAt(currentMethodDescritorOffset) == 'L') {\n ++currentMethodDescritorOffset;\n while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') {\n ++currentMethodDescritorOffset;\n }\n }\n locals[numLocal++] = methodDescriptor.substring(currentArgumentDescriptorStartOffset, ++currentMethodDescritorOffset);\n break;\n case 'L':\n while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') {\n ++currentMethodDescritorOffset;\n }\n locals[numLocal++] = methodDescriptor.substring(currentArgumentDescriptorStartOffset + 1, currentMethodDescritorOffset++);\n break;\n default:\n context.currentFrameLocalCount = numLocal;\n return;\n }\n }\n }\n\n /**\n * Reads a JVMS 'stack_map_frame' structure and stores the result in the given {@link Context}\n * object. This method can also be used to read a full_frame structure, excluding its frame_type\n * field (this is used to parse the legacy StackMap attributes).\n *\n * @param stackMapFrameOffset the start offset in {@link #classFileBuffer} of the\n * stack_map_frame_value structure to be read, or the start offset of a full_frame structure\n * (excluding its frame_type field).\n * @param compressed true to read a 'stack_map_frame' structure, false to read a 'full_frame'\n * structure without its frame_type field.\n * @param expand if the stack map frame must be expanded. See {@link #EXPAND_FRAMES}.\n * @param context where the parsed stack map frame must be stored.\n * @return the end offset of the JVMS 'stack_map_frame' or 'full_frame' structure.\n */\n private int readStackMapFrame(final int stackMapFrameOffset, final boolean compressed, final boolean expand, final Context context) {\n int currentOffset = stackMapFrameOffset;\n final char[] charBuffer = context.charBuffer;\n final Label[] labels = context.currentMethodLabels;\n int frameType;\n if (compressed) {\n // Read the frame_type field.\n frameType = classFileBuffer[currentOffset++] & 0xFF;\n } else {\n frameType = Frame.FULL_FRAME;\n context.currentFrameOffset = -1;\n }\n int offsetDelta;\n context.currentFrameLocalCountDelta = 0;\n if (frameType < Frame.SAME_LOCALS_1_STACK_ITEM_FRAME) {\n offsetDelta = frameType;\n context.currentFrameType = Opcodes.F_SAME;\n context.currentFrameStackCount = 0;\n } else if (frameType < Frame.RESERVED) {\n offsetDelta = frameType - Frame.SAME_LOCALS_1_STACK_ITEM_FRAME;\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels);\n context.currentFrameType = Opcodes.F_SAME1;\n context.currentFrameStackCount = 1;\n } else if (frameType >= Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {\n offsetDelta = readUnsignedShort(currentOffset);\n currentOffset += 2;\n if (frameType == Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels);\n context.currentFrameType = Opcodes.F_SAME1;\n context.currentFrameStackCount = 1;\n } else if (frameType >= Frame.CHOP_FRAME && frameType < Frame.SAME_FRAME_EXTENDED) {\n context.currentFrameType = Opcodes.F_CHOP;\n context.currentFrameLocalCountDelta = Frame.SAME_FRAME_EXTENDED - frameType;\n context.currentFrameLocalCount -= context.currentFrameLocalCountDelta;\n context.currentFrameStackCount = 0;\n } else if (frameType == Frame.SAME_FRAME_EXTENDED) {\n context.currentFrameType = Opcodes.F_SAME;\n context.currentFrameStackCount = 0;\n } else if (frameType < Frame.FULL_FRAME) {\n int local = expand ? context.currentFrameLocalCount : 0;\n for (int k = frameType - Frame.SAME_FRAME_EXTENDED; k > 0; k--) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameLocalTypes, local++, charBuffer, labels);\n }\n context.currentFrameType = Opcodes.F_APPEND;\n context.currentFrameLocalCountDelta = frameType - Frame.SAME_FRAME_EXTENDED;\n context.currentFrameLocalCount += context.currentFrameLocalCountDelta;\n context.currentFrameStackCount = 0;\n } else {\n final int numberOfLocals = readUnsignedShort(currentOffset);\n currentOffset += 2;\n context.currentFrameType = Opcodes.F_FULL;\n context.currentFrameLocalCountDelta = numberOfLocals;\n context.currentFrameLocalCount = numberOfLocals;\n for (int local = 0; local < numberOfLocals; ++local) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameLocalTypes, local, charBuffer, labels);\n }\n final int numberOfStackItems = readUnsignedShort(currentOffset);\n currentOffset += 2;\n context.currentFrameStackCount = numberOfStackItems;\n for (int stack = 0; stack < numberOfStackItems; ++stack) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameStackTypes, stack, charBuffer, labels);\n }\n }\n } else {\n throw new IllegalArgumentException();\n }\n context.currentFrameOffset += offsetDelta + 1;\n createLabel(context.currentFrameOffset, labels);\n return currentOffset;\n }\n\n /**\n * Reads a JVMS 'verification_type_info' structure and stores it at the given index in the given\n * array.\n *\n * @param verificationTypeInfoOffset the start offset of the 'verification_type_info' structure to\n * read.\n * @param frame the array where the parsed type must be stored.\n * @param index the index in 'frame' where the parsed type must be stored.\n * @param charBuffer the buffer used to read strings in the constant pool.\n * @param labels the labels of the method currently being parsed, indexed by their offset. If the\n * parsed type is an ITEM_Uninitialized, a new label for the corresponding NEW instruction is\n * stored in this array if it does not already exist.\n * @return the end offset of the JVMS 'verification_type_info' structure.\n */\n private int readVerificationTypeInfo(final int verificationTypeInfoOffset, final Object[] frame, final int index, final char[] charBuffer, final Label[] labels) {\n int currentOffset = verificationTypeInfoOffset;\n int tag = classFileBuffer[currentOffset++] & 0xFF;\n switch (tag) {\n case Frame.ITEM_TOP:\n frame[index] = Opcodes.TOP;\n break;\n case Frame.ITEM_INTEGER:\n frame[index] = Opcodes.INTEGER;\n break;\n case Frame.ITEM_FLOAT:\n frame[index] = Opcodes.FLOAT;\n break;\n case Frame.ITEM_DOUBLE:\n frame[index] = Opcodes.DOUBLE;\n break;\n case Frame.ITEM_LONG:\n frame[index] = Opcodes.LONG;\n break;\n case Frame.ITEM_NULL:\n frame[index] = Opcodes.NULL;\n break;\n case Frame.ITEM_UNINITIALIZED_THIS:\n frame[index] = Opcodes.UNINITIALIZED_THIS;\n break;\n case Frame.ITEM_OBJECT:\n frame[index] = readClass(currentOffset, charBuffer);\n currentOffset += 2;\n break;\n case Frame.ITEM_UNINITIALIZED:\n frame[index] = createLabel(readUnsignedShort(currentOffset), labels);\n currentOffset += 2;\n break;\n default:\n throw new IllegalArgumentException();\n }\n return currentOffset;\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse attributes\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Returns the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array\n * field entry.\n *\n * @return the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array\n * field entry.\n */\n final int getFirstAttributeOffset() {\n // Skip the access_flags, this_class, super_class, and interfaces_count fields (using 2 bytes\n // each), as well as the interfaces array field (2 bytes per interface).\n int currentOffset = header + 8 + readUnsignedShort(header + 6) * 2;\n // Read the fields_count field.\n int fieldsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n // Skip the 'fields' array field.\n while (fieldsCount-- > 0) {\n // Invariant: currentOffset is the offset of a field_info structure.\n // Skip the access_flags, name_index and descriptor_index fields (2 bytes each), and read the\n // attributes_count field.\n int attributesCount = readUnsignedShort(currentOffset + 6);\n currentOffset += 8;\n // Skip the 'attributes' array field.\n while (attributesCount-- > 0) {\n // Invariant: currentOffset is the offset of an attribute_info structure.\n // Read the attribute_length field (2 bytes after the start of the attribute_info) and skip\n // this many bytes, plus 6 for the attribute_name_index and attribute_length fields\n // (yielding the total size of the attribute_info structure).\n currentOffset += 6 + readInt(currentOffset + 2);\n }\n }\n // Skip the methods_count and 'methods' fields, using the same method as above.\n int methodsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (methodsCount-- > 0) {\n int attributesCount = readUnsignedShort(currentOffset + 6);\n currentOffset += 8;\n while (attributesCount-- > 0) {\n currentOffset += 6 + readInt(currentOffset + 2);\n }\n }\n // Skip the ClassFile's attributes_count field.\n return currentOffset + 2;\n }\n\n /**\n * Reads the BootstrapMethods attribute to compute the offset of each bootstrap method.\n *\n * @param maxStringLength a conservative estimate of the maximum length of the strings contained\n * in the constant pool of the class.\n * @return the offsets of the bootstrap methods.\n */\n private int[] readBootstrapMethodsAttribute(final int maxStringLength) {\n char[] charBuffer = new char[maxStringLength];\n int currentAttributeOffset = getFirstAttributeOffset();\n int[] currentBootstrapMethodOffsets = null;\n for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentAttributeOffset, charBuffer);\n int attributeLength = readInt(currentAttributeOffset + 2);\n currentAttributeOffset += 6;\n if (Constants.BOOTSTRAP_METHODS.equals(attributeName)) {\n // Read the num_bootstrap_methods field and create an array of this size.\n currentBootstrapMethodOffsets = new int[readUnsignedShort(currentAttributeOffset)];\n // Compute and store the offset of each 'bootstrap_methods' array field entry.\n int currentBootstrapMethodOffset = currentAttributeOffset + 2;\n for (int j = 0; j < currentBootstrapMethodOffsets.length; ++j) {\n currentBootstrapMethodOffsets[j] = currentBootstrapMethodOffset;\n // Skip the bootstrap_method_ref and num_bootstrap_arguments fields (2 bytes each),\n // as well as the bootstrap_arguments array field (of size num_bootstrap_arguments * 2).\n currentBootstrapMethodOffset += 4 + readUnsignedShort(currentBootstrapMethodOffset + 2) * 2;\n }\n return currentBootstrapMethodOffsets;\n }\n currentAttributeOffset += attributeLength;\n }\n throw new IllegalArgumentException();\n }\n\n /**\n * Reads a non standard JVMS 'attribute' structure in {@link #classFileBuffer}.\n *\n * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of\n * the class. Any attribute whose type is not equal to the type of one the prototypes will not\n * be parsed: its byte array value will be passed unchanged to the ClassWriter.\n * @param type the type of the attribute.\n * @param offset the start offset of the JVMS 'attribute' structure in {@link #classFileBuffer}.\n * The 6 attribute header bytes (attribute_name_index and attribute_length) are not taken into\n * account here.\n * @param length the length of the attribute's content (excluding the 6 attribute header bytes).\n * @param charBuffer the buffer to be used to read strings in the constant pool.\n * @param codeAttributeOffset the start offset of the enclosing Code attribute in {@link\n * #classFileBuffer}, or -1 if the attribute to be read is not a code attribute. The 6\n * attribute header bytes (attribute_name_index and attribute_length) are not taken into\n * account here.\n * @param labels the labels of the method's code, or {@literal null} if the attribute to be read\n * is not a code attribute.\n * @return the attribute that has been read.\n */\n private Attribute readAttribute(final Attribute[] attributePrototypes, final String type, final int offset, final int length, final char[] charBuffer, final int codeAttributeOffset, final Label[] labels) {\n for (Attribute attributePrototype : attributePrototypes) {\n if (attributePrototype.type.equals(type)) {\n return attributePrototype.read(this, offset, length, charBuffer, codeAttributeOffset, labels);\n }\n }\n return new Attribute(type).read(this, offset, length, null, -1, null);\n }\n // -----------------------------------------------------------------------------------------------\n // Utility methods: low level parsing\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the number of entries in the class's constant pool table.\n *\n * @return the number of entries in the class's constant pool table.\n */\n public int getItemCount() {\n return cpInfoOffsets.length;\n }\n\n /**\n * Returns the start offset in this {@link ClassReader} of a JVMS 'cp_info' structure (i.e. a\n * constant pool entry), plus one. This method is intended for {@link Attribute} sub classes,\n * and is normally not needed by class generators or adapters.\n *\n * @param constantPoolEntryIndex the index a constant pool entry in the class's constant pool\n * table.\n * @return the start offset in this {@link ClassReader} of the corresponding JVMS 'cp_info'\n * structure, plus one.\n */\n public int getItem(final int constantPoolEntryIndex) {\n return cpInfoOffsets[constantPoolEntryIndex];\n }\n\n /**\n * Returns a conservative estimate of the maximum length of the strings contained in the class's\n * constant pool table.\n *\n * @return a conservative estimate of the maximum length of the strings contained in the class's\n * constant pool table.\n */\n public int getMaxStringLength() {\n return maxStringLength;\n }\n\n /**\n * Reads a byte value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public int readByte(final int offset) {\n return classFileBuffer[offset] & 0xFF;\n }\n\n /**\n * Reads an unsigned short value in this {@link ClassReader}. This method is intended for\n * {@link Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start index of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public int readUnsignedShort(final int offset) {\n byte[] classBuffer = classFileBuffer;\n return ((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF);\n }\n\n /**\n * Reads a signed short value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public short readShort(final int offset) {\n byte[] classBuffer = classFileBuffer;\n return (short) (((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF));\n }\n\n /**\n * Reads a signed int value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public int readInt(final int offset) {\n byte[] classBuffer = classFileBuffer;\n return ((classBuffer[offset] & 0xFF) << 24) | ((classBuffer[offset + 1] & 0xFF) << 16) | ((classBuffer[offset + 2] & 0xFF) << 8) | (classBuffer[offset + 3] & 0xFF);\n }\n\n /**\n * Reads a signed long value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public long readLong(final int offset) {\n long l1 = readInt(offset);\n long l0 = readInt(offset + 4) & 0xFFFFFFFFL;\n return (l1 << 32) | l0;\n }\n\n /**\n * Reads a CONSTANT_Utf8 constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Utf8 entry in the class's constant pool table.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Utf8 entry.\n */\n // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility).\n public String readUTF8(final int offset, final char[] charBuffer) {\n int constantPoolEntryIndex = readUnsignedShort(offset);\n if (offset == 0 || constantPoolEntryIndex == 0) {\n return null;\n }\n return readUtf(constantPoolEntryIndex, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Utf8 constant pool entry in {@link #classFileBuffer}.\n *\n * @param constantPoolEntryIndex the index of a CONSTANT_Utf8 entry in the class's constant pool\n * table.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Utf8 entry.\n */\n final String readUtf(final int constantPoolEntryIndex, final char[] charBuffer) {\n String value = constantUtf8Values[constantPoolEntryIndex];\n if (value != null) {\n return value;\n }\n int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex];\n return constantUtf8Values[constantPoolEntryIndex] = readUtf(cpInfoOffset + 2, readUnsignedShort(cpInfoOffset), charBuffer);\n }\n\n /**\n * Reads an UTF8 string in {@link #classFileBuffer}.\n *\n * @param utfOffset the start offset of the UTF8 string to be read.\n * @param utfLength the length of the UTF8 string to be read.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified UTF8 string.\n */\n private String readUtf(final int utfOffset, final int utfLength, final char[] charBuffer) {\n int currentOffset = utfOffset;\n int endOffset = currentOffset + utfLength;\n int strLength = 0;\n byte[] classBuffer = classFileBuffer;\n while (currentOffset < endOffset) {\n int currentByte = classBuffer[currentOffset++];\n if ((currentByte & 0x80) == 0) {\n charBuffer[strLength++] = (char) (currentByte & 0x7F);\n } else if ((currentByte & 0xE0) == 0xC0) {\n charBuffer[strLength++] = (char) (((currentByte & 0x1F) << 6) + (classBuffer[currentOffset++] & 0x3F));\n } else {\n charBuffer[strLength++] = (char) (((currentByte & 0xF) << 12) + ((classBuffer[currentOffset++] & 0x3F) << 6) + (classBuffer[currentOffset++] & 0x3F));\n }\n }\n return new String(charBuffer, 0, strLength);\n }\n\n /**\n * Reads a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, CONSTANT_Module or\n * CONSTANT_Package constant pool entry in {@link #classFileBuffer}. This method is intended\n * for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in {@link #classFileBuffer}, whose\n * value is the index of a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType,\n * CONSTANT_Module or CONSTANT_Package entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified constant pool entry.\n */\n private String readStringish(final int offset, final char[] charBuffer) {\n // Get the start offset of the cp_info structure (plus one), and read the CONSTANT_Utf8 entry\n // designated by the first two bytes of this cp_info.\n return readUTF8(cpInfoOffsets[readUnsignedShort(offset)], charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Class constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Class entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Class entry.\n */\n public String readClass(final int offset, final char[] charBuffer) {\n return readStringish(offset, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Module constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Module entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Module entry.\n */\n public String readModule(final int offset, final char[] charBuffer) {\n return readStringish(offset, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Package constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Package entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Package entry.\n */\n public String readPackage(final int offset, final char[] charBuffer) {\n return readStringish(offset, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Dynamic constant pool entry in {@link #classFileBuffer}.\n *\n * @param constantPoolEntryIndex the index of a CONSTANT_Dynamic entry in the class's constant\n * pool table.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the ConstantDynamic corresponding to the specified CONSTANT_Dynamic entry.\n */\n private ConstantDynamic readConstantDynamic(final int constantPoolEntryIndex, final char[] charBuffer) {\n ConstantDynamic constantDynamic = constantDynamicValues[constantPoolEntryIndex];\n if (constantDynamic != null) {\n return constantDynamic;\n }\n int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)];\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)];\n Handle handle = (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n Object[] bootstrapMethodArguments = new Object[readUnsignedShort(bootstrapMethodOffset + 2)];\n bootstrapMethodOffset += 4;\n for (int i = 0; i < bootstrapMethodArguments.length; i++) {\n bootstrapMethodArguments[i] = readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n bootstrapMethodOffset += 2;\n }\n return constantDynamicValues[constantPoolEntryIndex] = new ConstantDynamic(name, descriptor, handle, bootstrapMethodArguments);\n }\n\n /**\n * Reads a numeric or string constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param constantPoolEntryIndex the index of a CONSTANT_Integer, CONSTANT_Float, CONSTANT_Long,\n * CONSTANT_Double, CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType,\n * CONSTANT_MethodHandle or CONSTANT_Dynamic entry in the class's constant pool.\n * @param charBuffer the buffer to be used to read strings. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the {@link Integer}, {@link Float}, {@link Long}, {@link Double}, {@link String},\n * {@link Type}, {@link Handle} or {@link ConstantDynamic} corresponding to the specified\n * constant pool entry.\n */\n public Object readConst(final int constantPoolEntryIndex, final char[] charBuffer) {\n int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex];\n switch (classFileBuffer[cpInfoOffset - 1]) {\n case Symbol.CONSTANT_INTEGER_TAG:\n return readInt(cpInfoOffset);\n case Symbol.CONSTANT_FLOAT_TAG:\n return Float.intBitsToFloat(readInt(cpInfoOffset));\n case Symbol.CONSTANT_LONG_TAG:\n return readLong(cpInfoOffset);\n case Symbol.CONSTANT_DOUBLE_TAG:\n return Double.longBitsToDouble(readLong(cpInfoOffset));\n case Symbol.CONSTANT_CLASS_TAG:\n return Type.getObjectType(readUTF8(cpInfoOffset, charBuffer));\n case Symbol.CONSTANT_STRING_TAG:\n return readUTF8(cpInfoOffset, charBuffer);\n case Symbol.CONSTANT_METHOD_TYPE_TAG:\n return Type.getMethodType(readUTF8(cpInfoOffset, charBuffer));\n case Symbol.CONSTANT_METHOD_HANDLE_TAG:\n int referenceKind = readByte(cpInfoOffset);\n int referenceCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 1)];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(referenceCpInfoOffset + 2)];\n String owner = readClass(referenceCpInfoOffset, charBuffer);\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n boolean isInterface = classFileBuffer[referenceCpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG;\n return new Handle(referenceKind, owner, name, descriptor, isInterface);\n case Symbol.CONSTANT_DYNAMIC_TAG:\n return readConstantDynamic(constantPoolEntryIndex, charBuffer);\n default:\n throw new IllegalArgumentException();\n }\n }\n}\n", "file_name": "ClassReader.java", "human_label": "Read a short value from classFileBuffer", "level": "class_runnable", "lineno": "3099", "name": "readShort", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[byte[]]\", \"vars\" : \"[classFileBuffer]\" }", "package": "net.hasor.utils.asm", "project": "hasor-master" }, { "_id": "636767031a6d9265ec0178ef", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(int[] array,int element);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "private static Object copyArrayGrow1(final Object array,final Class newArrayComponentType){\n if (array != null) {\n int arrayLength=Array.getLength(array);\n Object newArray=Array.newInstance(array.getClass().getComponentType(),arrayLength + 1);\n System.arraycopy(array,0,newArray,0,arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType,1);\n}\n", "docstring": "/** \n * Returns a copy of the given array of size 1 greater than the argument. The last value of the array is left to the default value.\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create asize 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n", "end_lineno": "68", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.rsf.protocol.rsf.v1;\nimport java.lang.reflect.Array;\n\n/**\n *

Operations on {@link String} that are null safe.

\n */\npublic abstract class ArrayUtils {\n /**\n *

Copies the given array and adds the given element at the end of the new array.

\n *\n *

The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

\n *\n *

If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

\n *\n *
\n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
\n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n}", "file_name": "ArrayUtils.java", "human_label": "Copy the given array and add a default value at the end.", "level": "slib_runnable", "lineno": "51", "name": "copyArrayGrow1", "oracle_context": "{ \"apis\" : \"[getLength, newInstance, getComponentType, getClass, arraycopy]\", \"classes\" : \"[Object]\", \"vars\" : \"[]\" }", "package": "net.hasor.rsf.protocol.rsf.v1", "project": "hasor-master" }, { "_id": "636767431a6d9265ec017c8d", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.graph.*;\\nimport org.jgrapht.traverse.*;\\nimport java.util.*;\\nTransitiveClosure INSTANCE;\\nTransitiveClosure();\\ncomputeBinaryLog(int n);\\ncloseDirectedAcyclicGraph(DirectedAcyclicGraph graph);\\ncloseSimpleDirectedGraph(SimpleDirectedGraph graph);\\n\", \"repo_level\" : \"\" }", "class_name": "TransitiveClosure", "code": "private int computeBinaryLog(int n){\n assert n >= 0;\n int result=0;\n while (n > 0) {\n n>>=1;\n ++result;\n }\n return result;\n}\n", "docstring": "/** \n * Computes floor($\\log_2 (n)$) $+ 1$\n */\n", "end_lineno": "111", "file_content": "/*\n * (C) Copyright 2007-2021, by Vinayak R Borkar and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg;\n\nimport org.jgrapht.*;\nimport org.jgrapht.graph.*;\nimport org.jgrapht.traverse.*;\n\nimport java.util.*;\n\n/**\n * Constructs the transitive closure of the input graph.\n *\n * @author Vinayak R. Borkar\n */\npublic class TransitiveClosure\n{\n /**\n * Singleton instance.\n */\n public static final TransitiveClosure INSTANCE = new TransitiveClosure();\n\n /**\n * Private Constructor.\n */\n private TransitiveClosure()\n {\n }\n\n /**\n * Computes the transitive closure of the given graph.\n *\n * @param graph - Graph to compute transitive closure for.\n * @param the graph vertex type\n * @param the graph edge type\n */\n public void closeSimpleDirectedGraph(SimpleDirectedGraph graph)\n {\n Set vertexSet = graph.vertexSet();\n\n Set newEdgeTargets = new HashSet<>();\n\n // At every iteration of the outer loop, we add a path of length 1\n // between nodes that originally had a path of length 2. In the worst\n // case, we need to make floor(log |V|) + 1 iterations. We stop earlier\n // if there is no change to the output graph.\n\n int bound = computeBinaryLog(vertexSet.size());\n boolean done = false;\n for (int i = 0; !done && (i < bound); ++i) {\n done = true;\n for (V v1 : vertexSet) {\n newEdgeTargets.clear();\n\n for (E v1OutEdge : graph.outgoingEdgesOf(v1)) {\n V v2 = graph.getEdgeTarget(v1OutEdge);\n for (E v2OutEdge : graph.outgoingEdgesOf(v2)) {\n V v3 = graph.getEdgeTarget(v2OutEdge);\n\n if (v1.equals(v3)) {\n // Its a simple graph, so no self loops.\n continue;\n }\n\n if (graph.getEdge(v1, v3) != null) {\n // There is already an edge from v1 ---> v3, skip;\n continue;\n }\n\n newEdgeTargets.add(v3);\n done = false;\n }\n }\n\n for (V v3 : newEdgeTargets) {\n graph.addEdge(v1, v3);\n }\n }\n }\n }\n\n /**\n * Computes floor($\\log_2 (n)$) $+ 1$\n */\n private int computeBinaryLog(int n)\n {\n assert n >= 0;\n\n int result = 0;\n while (n > 0) {\n n >>= 1;\n ++result;\n }\n\n return result;\n }\n\n /**\n * Computes the transitive closure of a directed acyclic graph in $O(nm)$\n *\n * @param graph - Graph to compute transitive closure for.\n * @param the graph vertex type\n * @param the graph edge type\n */\n public void closeDirectedAcyclicGraph(DirectedAcyclicGraph graph)\n {\n Deque orderedVertices = new ArrayDeque<>(graph.vertexSet().size());\n new TopologicalOrderIterator<>(graph).forEachRemaining(orderedVertices::addFirst);\n\n for (V vertex : orderedVertices) {\n for (V successor : Graphs.successorListOf(graph, vertex)) {\n for (V closureVertex : Graphs.successorListOf(graph, successor)) {\n graph.addEdge(vertex, closureVertex);\n }\n }\n }\n }\n\n}\n", "file_name": "TransitiveClosure.java", "human_label": "Calculate the floor of the logarithmic value of the given value in base 2.", "level": "self_contained", "lineno": "97", "name": "computeBinaryLog", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "org.jgrapht.alg", "project": "jgrapht-master" }, { "_id": "636767611a6d9265ec018116", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.alg.connectivity.*;\\nimport org.jgrapht.alg.interfaces.*;\\nimport org.jgrapht.graph.*;\\nimport java.util.*;\\nimport java.util.function.*;\\nimport java.util.stream.*;\\nGraph network;\\nSet oddVertices;\\nGusfieldGomoryHuCutTree gusfieldGomoryHuCutTreeAlgorithm;\\nSimpleWeightedGraph gomoryHuTree;\\ndouble minimumCutWeight;\\nSet sourcePartitionMinimumCut;\\nPadbergRaoOddMinimumCutset(Graph network);\\nPadbergRaoOddMinimumCutset(Graph network,double epsilon);\\nPadbergRaoOddMinimumCutset(Graph network,MinimumSTCutAlgorithm minimumSTCutAlgorithm);\\ncalculateMinCutWithoutTreeCompression();\\ncalculateMinCutWithTreeCompression();\\nsplitCluster(Set cluster,Queue queue);\\nintersection(Set set1,Set set2);\\nisOddVertexSet(Set vertices,Set oddVertices);\\ngetSourcePartition();\\ngetSinkPartition();\\ngetCutEdges();\\ncalculateMinCut(Set oddVertices,boolean useTreeCompression);\\n\", \"repo_level\" : \"\" }", "class_name": "PadbergRaoOddMinimumCutset", "code": "private Set intersection(Set set1,Set set2){\n Set a;\n Set b;\n if (set1.size() <= set2.size()) {\n a=set1;\n b=set2;\n }\n else {\n a=set2;\n b=set1;\n }\n return a.stream().filter(b::contains).collect(Collectors.toSet());\n}\n", "docstring": "/** \n * Efficient way to compute the intersection between two sets\n * @param set1 set $1$\n * @param set2 set $2$\n * @return intersection of set $1$ and $2$\n */\n", "end_lineno": "278", "file_content": "/*\n * (C) Copyright 2016-2021, by Joris Kinable and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.flow;\n\nimport org.jgrapht.*;\nimport org.jgrapht.alg.connectivity.*;\nimport org.jgrapht.alg.interfaces.*;\nimport org.jgrapht.graph.*;\n\nimport java.util.*;\nimport java.util.function.*;\nimport java.util.stream.*;\n\n/**\n * Implementation of the algorithm by Padberg and Rao to compute Odd Minimum Cut-Sets. Let $G=(V,E)$\n * be an undirected, simple weighted graph, where all edge weights are positive. Let $T \\subset V$\n * with $|T|$ even, be a set of vertices that are labelled odd. A cut-set $(U:V-U)$ is called\n * odd if $|T \\cap U|$ is an odd number. Let $c(U:V-U)$ be the weight of the cut, that is, the sum\n * of weights of the edges which have exactly one endpoint in $U$ and one endpoint in $V-U$. The\n * problem of finding an odd minimum cut-set in $G$ is stated as follows: Find $W \\subseteq V$ such\n * that $c(W:V-W)=min(c(U:V-U)|U \\subseteq V, |T \\cap U|$ is odd).\n *\n *

\n * The algorithm has been published in: Padberg, M. Rao, M. Odd Minimum Cut-Sets and b-Matchings.\n * Mathematics of Operations Research, 7(1), p67-80, 1982. A more concise description is published\n * in: Letchford, A. Reinelt, G. Theis, D. Odd minimum cut-sets and b-matchings revisited. SIAM\n * Journal of Discrete Mathematics, 22(4), p1480-1487, 2008.\n *\n *

\n * The runtime complexity of this algorithm is dominated by the runtime complexity of the algorithm\n * used to compute A Gomory-Hu tree on graph $G$. Consequently, the runtime complexity of this class\n * is $O(V^4)$.\n *\n *

\n * This class does not support changes to the underlying graph. The behavior of this class is\n * undefined when the graph is modified after instantiating this class.\n *\n * @param the graph vertex type\n * @param the graph edge type\n *\n * @author Joris Kinable\n */\npublic class PadbergRaoOddMinimumCutset\n{\n\n /* Input graph */\n private final Graph network;\n /* Set of vertices which are labeled 'odd' (set T in the paper) */\n private Set oddVertices;\n /* Algorithm used to calculate the Gomory-Hu Cut-tree */\n private final GusfieldGomoryHuCutTree gusfieldGomoryHuCutTreeAlgorithm;\n /* The Gomory-Hu tree */\n private SimpleWeightedGraph gomoryHuTree;\n\n /* Weight of the minimum odd cut-set */\n private double minimumCutWeight = Double.MAX_VALUE;\n /* Source partition constituting the minimum odd cut-set */\n private Set sourcePartitionMinimumCut;\n\n /**\n * Creates a new instance of the PadbergRaoOddMinimumCutset algorithm.\n *\n * @param network input graph\n */\n public PadbergRaoOddMinimumCutset(Graph network)\n {\n this(network, MaximumFlowAlgorithmBase.DEFAULT_EPSILON);\n }\n\n /**\n * Creates a new instance of the PadbergRaoOddMinimumCutset algorithm.\n *\n * @param network input graph\n * @param epsilon tolerance\n */\n public PadbergRaoOddMinimumCutset(Graph network, double epsilon)\n {\n this(network, new PushRelabelMFImpl<>(network, epsilon));\n }\n\n /**\n * Creates a new instance of the PadbergRaoOddMinimumCutset algorithm.\n *\n * @param network input graph\n * @param minimumSTCutAlgorithm algorithm used to calculate the Gomory-Hu tree\n */\n public PadbergRaoOddMinimumCutset(\n Graph network, MinimumSTCutAlgorithm minimumSTCutAlgorithm)\n {\n this.network = GraphTests.requireUndirected(network);\n gusfieldGomoryHuCutTreeAlgorithm =\n new GusfieldGomoryHuCutTree<>(network, minimumSTCutAlgorithm);\n }\n\n /**\n * Calculates the minimum odd cut. The implementation follows Algorithm 1 in the paper Odd\n * minimum cut sets and b-matchings revisited by Adam Letchford, Gerhard Reinelt and Dirk Theis.\n * The original algorithm runs on a compressed Gomory-Hu tree: a cut-tree with the odd vertices\n * as terminal vertices. This tree has $|T|-1$ edges as opposed to $|V|-1$ for a Gomory-Hu tree\n * defined on the input graph $G$. This compression step can however be skipped. If you want to\n * run the original algorithm in the paper, set the parameter useTreeCompression to\n * true. Alternatively, experiment which setting of this parameter produces the fastest results.\n * Both settings are guaranteed to find the optimal cut. Experiments on random graphs showed\n * that setting useTreeCompression to false was on average a bit faster.\n *\n * @param oddVertices Set of vertices which are labeled 'odd'. Note that the number of vertices\n * in this set must be even!\n * @param useTreeCompression parameter indicating whether tree compression should be used\n * (recommended: false).\n * @return weight of the minimum odd cut.\n */\n public double calculateMinCut(Set oddVertices, boolean useTreeCompression)\n {\n minimumCutWeight = Double.MAX_VALUE;\n this.oddVertices = oddVertices;\n\n if (oddVertices.size() % 2 == 1)\n throw new IllegalArgumentException(\"There needs to be an even number of odd vertices\");\n assert network.vertexSet().containsAll(oddVertices); // All odd vertices must be contained\n // in the graph\n // all edge weights must be non-negative\n assert network.edgeSet().stream().noneMatch(e -> network.getEdgeWeight(e) < 0);\n\n gomoryHuTree = gusfieldGomoryHuCutTreeAlgorithm.getGomoryHuTree();\n\n if (useTreeCompression)\n return calculateMinCutWithTreeCompression();\n else\n return calculateMinCutWithoutTreeCompression();\n }\n\n /**\n * Modified implementation of the algorithm proposed in Odd Minimum Cut-sets and b-matchings by\n * Padberg and Rao. The optimal cut is directly computed on the Gomory-Hu tree computed for\n * graph $G$. This approach iterates efficiently over all possible cuts of the graph (there are\n * $|V|$ such cuts).\n *\n * @return weight of the minimum odd cut.\n */\n private double calculateMinCutWithoutTreeCompression()\n {\n Set edges = new LinkedHashSet<>(gomoryHuTree.edgeSet());\n for (DefaultWeightedEdge edge : edges) {\n V source = gomoryHuTree.getEdgeSource(edge);\n V target = gomoryHuTree.getEdgeTarget(edge);\n double edgeWeight = gomoryHuTree.getEdgeWeight(edge);\n\n if (edgeWeight >= minimumCutWeight)\n continue;\n\n gomoryHuTree.removeEdge(edge); // Temporarily remove edge\n Set sourcePartition =\n new ConnectivityInspector<>(gomoryHuTree).connectedSetOf(source);\n if (PadbergRaoOddMinimumCutset.isOddVertexSet(sourcePartition, oddVertices)) { // If the\n // source\n // partition\n // forms\n // an odd\n // cutset,\n // check\n // whether\n // the\n // cut\n // isn't\n // better\n // than\n // the\n // one we\n // already\n // found.\n minimumCutWeight = edgeWeight;\n sourcePartitionMinimumCut = sourcePartition;\n }\n gomoryHuTree.addEdge(source, target, edge); // Place edge back\n }\n return minimumCutWeight;\n }\n\n /**\n * Implementation of the algorithm proposed in Odd Minimum Cut-sets and b-matchings by Padberg\n * and Rao. The algorithm evaluates at most $|T|$ cuts in the Gomory-Hu tree.\n *\n * @return weight of the minimum odd cut.\n */\n private double calculateMinCutWithTreeCompression()\n {\n Queue> queue = new ArrayDeque<>();\n queue.add(oddVertices);\n\n // Keep splitting the clusters until each resulting cluster containes exactly one vertex.\n while (!queue.isEmpty()) {\n Set nextCluster = queue.poll();\n this.splitCluster(nextCluster, queue);\n }\n\n return minimumCutWeight;\n }\n\n /**\n * Takes a set of odd vertices with cardinality $2$ or more, and splits them into $2$ new\n * non-empty sets.\n * \n * @param cluster group of odd vertices\n * @param queue clusters with cardinality $2$ or more\n */\n private void splitCluster(Set cluster, Queue> queue)\n {\n assert cluster.size() >= 2;\n\n // Choose 2 random odd nodes\n Iterator iterator = cluster.iterator();\n V oddNode1 = iterator.next();\n V oddNode2 = iterator.next();\n\n // Calculate the minimum cut separating these two nodes.\n double cutWeight = gusfieldGomoryHuCutTreeAlgorithm.calculateMinCut(oddNode1, oddNode2);\n Set sourcePartition = null;\n\n if (cutWeight < minimumCutWeight) {\n sourcePartition = gusfieldGomoryHuCutTreeAlgorithm.getSourcePartition();\n if (PadbergRaoOddMinimumCutset.isOddVertexSet(sourcePartition, oddVertices)) {\n this.minimumCutWeight = cutWeight;\n this.sourcePartitionMinimumCut = sourcePartition;\n }\n }\n\n if (cluster.size() == 2)\n return;\n\n if (sourcePartition == null)\n sourcePartition = gusfieldGomoryHuCutTreeAlgorithm.getSourcePartition();\n\n Set split1 = this.intersection(cluster, sourcePartition);\n Set split2 = new HashSet<>(cluster);\n split2.removeAll(split1);\n\n if (split1.size() > 1)\n queue.add(split1);\n if (split2.size() > 1)\n queue.add(split2);\n }\n\n /**\n * Efficient way to compute the intersection between two sets\n * \n * @param set1 set $1$\n * @param set2 set $2$\n * @return intersection of set $1$ and $2$\n */\n private Set intersection(Set set1, Set set2)\n {\n Set a;\n Set b;\n if (set1.size() <= set2.size()) {\n a = set1;\n b = set2;\n } else {\n a = set2;\n b = set1;\n }\n\n return a.stream().filter(b::contains).collect(Collectors.toSet());\n }\n\n /**\n * Convenience method which test whether the given set contains an odd number of odd-labeled\n * nodes.\n *\n * @param vertex type\n * @param vertices input set\n * @param oddVertices subset of vertices which are labeled odd\n * @return true if the given set contains an odd number of odd-labeled nodes.\n */\n public static boolean isOddVertexSet(Set vertices, Set oddVertices)\n {\n if (vertices.size() < oddVertices.size())\n return vertices.stream().filter(oddVertices::contains).count() % 2 == 1;\n else\n return oddVertices.stream().filter(vertices::contains).count() % 2 == 1;\n }\n\n /**\n * Returns partition $W$ of the cut obtained after the last invocation of\n * {@link #calculateMinCut(Set, boolean)}\n *\n * @return partition $W$\n */\n public Set getSourcePartition()\n {\n return sourcePartitionMinimumCut;\n }\n\n /**\n * Returns partition $V-W$ of the cut obtained after the last invocation of\n * {@link #calculateMinCut(Set, boolean)}\n *\n * @return partition $V-W$\n */\n public Set getSinkPartition()\n {\n Set sinkPartition = new LinkedHashSet<>(network.vertexSet());\n sinkPartition.removeAll(sourcePartitionMinimumCut);\n return sinkPartition;\n }\n\n /**\n * Returns the set of edges which run from the source partition to the sink partition, in the\n * $s-t$ cut obtained after the last invocation of {@link #calculateMinCut(Set, boolean)}\n *\n * @return set of edges which have one endpoint in the source partition and one endpoint in the\n * sink partition.\n */\n public Set getCutEdges()\n {\n Predicate predicate = e -> sourcePartitionMinimumCut.contains(network.getEdgeSource(e))\n ^ sourcePartitionMinimumCut.contains(network.getEdgeTarget(e));\n return network\n .edgeSet().stream().filter(predicate)\n .collect(Collectors.toCollection(LinkedHashSet::new));\n }\n\n}\n", "file_name": "PadbergRaoOddMinimumCutset.java", "human_label": "Return the intersection between two sets.", "level": "slib_runnable", "lineno": "258", "name": "intersection", "oracle_context": "{ \"apis\" : \"[size, collect, filter, stream, toSet]\", \"classes\" : \"[Set]\", \"vars\" : \"[]\" }", "package": "org.jgrapht.alg.flow", "project": "jgrapht-master" }, { "_id": "636766f71a6d9265ec017730", "all_context": "{ \"class_level\" : \"import net.hasor.utils.ArrayUtils;\\nimport net.hasor.utils.ClassUtils;\\nimport java.lang.reflect.AccessibleObject;\\nimport java.lang.reflect.Field;\\nimport java.lang.reflect.Modifier;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nboolean appendStatics;\\nboolean appendTransients;\\nString[] excludeFieldNames;\\nClass upToClass;\\ntoString(Object object,ToStringStyle style);\\ntoString(Object object,ToStringStyle style,boolean outputTransients);\\ntoString(Object object,ToStringStyle style,boolean outputTransients,boolean outputStatics);\\ntoString(Object object,ToStringStyle style,boolean outputTransients,boolean outputStatics,Class reflectUpToClass);\\ntoStringExclude(Object object,String excludeFieldName);\\ntoStringExclude(Object object,Collection excludeFieldNames);\\ntoNoNullStringArray(Collection collection);\\ntoNoNullStringArray(Object[] array);\\ntoStringExclude(Object object,String[] excludeFieldNames);\\nReflectionToStringBuilder(Object object);\\nReflectionToStringBuilder(Object object,ToStringStyle style);\\nReflectionToStringBuilder(Object object,ToStringStyle style,StringBuffer buffer);\\nReflectionToStringBuilder(Object object,ToStringStyle style,StringBuffer buffer,Class reflectUpToClass,boolean outputTransients,boolean outputStatics);\\naccept(Field field);\\nappendFieldsIn(Class clazz);\\ngetExcludeFieldNames();\\ngetUpToClass();\\ngetValue(Field field);\\nisAppendStatics();\\nisAppendTransients();\\nreflectionAppendArray(Object array);\\nsetAppendStatics(boolean appendStatics);\\nsetAppendTransients(boolean appendTransients);\\nsetExcludeFieldNames(String[] excludeFieldNamesParam);\\nsetUpToClass(Class clazz);\\ntoString();\\ntoString(Object object);\\n\", \"repo_level\" : \"public interface ArrayUtils {static Map toMap(Object[] array);\\nstatic Object[] clone(Object[] array);\\nstatic long[] clone(long[] array);\\nstatic int[] clone(int[] array);\\nstatic short[] clone(short[] array);\\nstatic char[] clone(char[] array);\\nstatic byte[] clone(byte[] array);\\nstatic double[] clone(double[] array);\\nstatic float[] clone(float[] array);\\nstatic boolean[] clone(boolean[] array);\\nstatic String[] clone(String[] array);\\nstatic Object[] nullToEmpty(Object[] array);\\nstatic String[] nullToEmpty(String[] array);\\nstatic long[] nullToEmpty(long[] array);\\nstatic int[] nullToEmpty(int[] array);\\nstatic short[] nullToEmpty(short[] array);\\nstatic char[] nullToEmpty(char[] array);\\nstatic byte[] nullToEmpty(byte[] array);\\nstatic double[] nullToEmpty(double[] array);\\nstatic float[] nullToEmpty(float[] array);\\nstatic boolean[] nullToEmpty(boolean[] array);\\nstatic Long[] nullToEmpty(Long[] array);\\nstatic Integer[] nullToEmpty(Integer[] array);\\nstatic Short[] nullToEmpty(Short[] array);\\nstatic Character[] nullToEmpty(Character[] array);\\nstatic Byte[] nullToEmpty(Byte[] array);\\nstatic Double[] nullToEmpty(Double[] array);\\nstatic Float[] nullToEmpty(Float[] array);\\nstatic Boolean[] nullToEmpty(Boolean[] array);\\nstatic Object[] subarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic long[] subarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic int[] subarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic short[] subarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic char[] subarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic byte[] subarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic double[] subarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic float[] subarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic boolean[] subarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic boolean isSameLength(Object[] array1,Object[] array2);\\nstatic boolean isSameLength(long[] array1,long[] array2);\\nstatic boolean isSameLength(int[] array1,int[] array2);\\nstatic boolean isSameLength(short[] array1,short[] array2);\\nstatic boolean isSameLength(char[] array1,char[] array2);\\nstatic boolean isSameLength(byte[] array1,byte[] array2);\\nstatic boolean isSameLength(double[] array1,double[] array2);\\nstatic boolean isSameLength(float[] array1,float[] array2);\\nstatic boolean isSameLength(boolean[] array1,boolean[] array2);\\nstatic int getLength(Object array);\\nstatic boolean isSameType(Object array1,Object array2);\\nstatic void reverse(Object[] array);\\nstatic void reverse(long[] array);\\nstatic void reverse(int[] array);\\nstatic void reverse(short[] array);\\nstatic void reverse(char[] array);\\nstatic void reverse(byte[] array);\\nstatic void reverse(double[] array);\\nstatic void reverse(float[] array);\\nstatic void reverse(boolean[] array);\\nstatic int indexOf(Object[] array,Object objectToFind);\\nstatic int indexOf(Object[] array,Object objectToFind,int startIndex);\\nstatic int lastIndexOf(Object[] array,Object objectToFind);\\nstatic int lastIndexOf(Object[] array,Object objectToFind,int startIndex);\\nstatic boolean contains(Object[] array,Object objectToFind);\\nstatic int indexOf(long[] array,long valueToFind);\\nstatic int indexOf(long[] array,long valueToFind,int startIndex);\\nstatic int lastIndexOf(long[] array,long valueToFind);\\nstatic int lastIndexOf(long[] array,long valueToFind,int startIndex);\\nstatic boolean contains(long[] array,long valueToFind);\\nstatic int indexOf(int[] array,int valueToFind);\\nstatic int indexOf(int[] array,int valueToFind,int startIndex);\\nstatic int lastIndexOf(int[] array,int valueToFind);\\nstatic int lastIndexOf(int[] array,int valueToFind,int startIndex);\\nstatic boolean contains(int[] array,int valueToFind);\\nstatic int indexOf(short[] array,short valueToFind);\\nstatic int indexOf(short[] array,short valueToFind,int startIndex);\\nstatic int lastIndexOf(short[] array,short valueToFind);\\nstatic int lastIndexOf(short[] array,short valueToFind,int startIndex);\\nstatic boolean contains(short[] array,short valueToFind);\\nstatic int indexOf(char[] array,char valueToFind);\\nstatic int indexOf(char[] array,char valueToFind,int startIndex);\\nstatic int lastIndexOf(char[] array,char valueToFind);\\nstatic int lastIndexOf(char[] array,char valueToFind,int startIndex);\\nstatic boolean contains(char[] array,char valueToFind);\\nstatic int indexOf(byte[] array,byte valueToFind);\\nstatic int indexOf(byte[] array,byte valueToFind,int startIndex);\\nstatic int lastIndexOf(byte[] array,byte valueToFind);\\nstatic int lastIndexOf(byte[] array,byte valueToFind,int startIndex);\\nstatic boolean contains(byte[] array,byte valueToFind);\\nstatic int indexOf(double[] array,double valueToFind);\\nstatic int indexOf(double[] array,double valueToFind,double tolerance);\\nstatic int indexOf(double[] array,double valueToFind,int startIndex);\\nstatic int indexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nstatic int lastIndexOf(double[] array,double valueToFind);\\nstatic int lastIndexOf(double[] array,double valueToFind,double tolerance);\\nstatic int lastIndexOf(double[] array,double valueToFind,int startIndex);\\nstatic int lastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nstatic boolean contains(double[] array,double valueToFind);\\nstatic boolean contains(double[] array,double valueToFind,double tolerance);\\nstatic int indexOf(float[] array,float valueToFind);\\nstatic int indexOf(float[] array,float valueToFind,int startIndex);\\nstatic int lastIndexOf(float[] array,float valueToFind);\\nstatic int lastIndexOf(float[] array,float valueToFind,int startIndex);\\nstatic boolean contains(float[] array,float valueToFind);\\nstatic int indexOf(boolean[] array,boolean valueToFind);\\nstatic int indexOf(boolean[] array,boolean valueToFind,int startIndex);\\nstatic int lastIndexOf(boolean[] array,boolean valueToFind);\\nstatic int lastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\nstatic boolean contains(boolean[] array,boolean valueToFind);\\nstatic char[] toPrimitive(Character[] array);\\nstatic char[] toPrimitive(Character[] array,char valueForNull);\\nstatic Character[] toObject(char[] array);\\nstatic long[] toPrimitive(Long[] array);\\nstatic long[] toPrimitive(Long[] array,long valueForNull);\\nstatic Long[] toObject(long[] array);\\nstatic int[] toPrimitive(Integer[] array);\\nstatic int[] toPrimitive(Integer[] array,int valueForNull);\\nstatic Integer[] toObject(int[] array);\\nstatic short[] toPrimitive(Short[] array);\\nstatic short[] toPrimitive(Short[] array,short valueForNull);\\nstatic Short[] toObject(short[] array);\\nstatic byte[] toPrimitive(Byte[] array);\\nstatic byte[] toPrimitive(Byte[] array,byte valueForNull);\\nstatic Byte[] toObject(byte[] array);\\nstatic double[] toPrimitive(Double[] array);\\nstatic double[] toPrimitive(Double[] array,double valueForNull);\\nstatic Double[] toObject(double[] array);\\nstatic float[] toPrimitive(Float[] array);\\nstatic float[] toPrimitive(Float[] array,float valueForNull);\\nstatic Float[] toObject(float[] array);\\nstatic boolean[] toPrimitive(Boolean[] array);\\nstatic boolean[] toPrimitive(Boolean[] array,boolean valueForNull);\\nstatic Boolean[] toObject(boolean[] array);\\nstatic boolean isEmpty(Object[] array);\\nstatic boolean isEmpty(long[] array);\\nstatic boolean isEmpty(int[] array);\\nstatic boolean isEmpty(short[] array);\\nstatic boolean isEmpty(char[] array);\\nstatic boolean isEmpty(byte[] array);\\nstatic boolean isEmpty(double[] array);\\nstatic boolean isEmpty(float[] array);\\nstatic boolean isEmpty(boolean[] array);\\nstatic boolean isNotEmpty(Object[] array);\\nstatic boolean isNotEmpty(long[] array);\\nstatic boolean isNotEmpty(int[] array);\\nstatic boolean isNotEmpty(short[] array);\\nstatic boolean isNotEmpty(char[] array);\\nstatic boolean isNotEmpty(byte[] array);\\nstatic boolean isNotEmpty(double[] array);\\nstatic boolean isNotEmpty(float[] array);\\nstatic boolean isNotEmpty(boolean[] array);\\nstatic Object[] addAll(Object[] array1,Object[] array2);\\nstatic boolean[] addAll(boolean[] array1,boolean[] array2);\\nstatic char[] addAll(char[] array1,char[] array2);\\nstatic byte[] addAll(byte[] array1,byte[] array2);\\nstatic short[] addAll(short[] array1,short[] array2);\\nstatic int[] addAll(int[] array1,int[] array2);\\nstatic long[] addAll(long[] array1,long[] array2);\\nstatic float[] addAll(float[] array1,float[] array2);\\nstatic double[] addAll(double[] array1,double[] array2);\\nstatic String[] addAll(String[] array1,String[] array2);\\nstatic T[] add(T[] array,T element);\\nstatic boolean[] add(boolean[] array,boolean element);\\nstatic byte[] add(byte[] array,byte element);\\nstatic char[] add(char[] array,char element);\\nstatic double[] add(double[] array,double element);\\nstatic float[] add(float[] array,float element);\\nstatic int[] add(int[] array,int element);\\nstatic long[] add(long[] array,long element);\\nstatic short[] add(short[] array,short element);\\nstatic Object[] add(Object[] array,int index,Object element);\\nstatic boolean[] add(boolean[] array,int index,boolean element);\\nstatic char[] add(char[] array,int index,char element);\\nstatic byte[] add(byte[] array,int index,byte element);\\nstatic short[] add(short[] array,int index,short element);\\nstatic int[] add(int[] array,int index,int element);\\nstatic long[] add(long[] array,int index,long element);\\nstatic float[] add(float[] array,int index,float element);\\nstatic double[] add(double[] array,int index,double element);\\nstatic Object[] remove(Object[] array,int index);\\nstatic Object[] removeElement(Object[] array,Object element);\\nstatic boolean[] remove(boolean[] array,int index);\\nstatic boolean[] removeElement(boolean[] array,boolean element);\\nstatic byte[] remove(byte[] array,int index);\\nstatic byte[] removeElement(byte[] array,byte element);\\nstatic char[] remove(char[] array,int index);\\nstatic char[] removeElement(char[] array,char element);\\nstatic double[] remove(double[] array,int index);\\nstatic double[] removeElement(double[] array,double element);\\nstatic float[] remove(float[] array,int index);\\nstatic float[] removeElement(float[] array,float element);\\nstatic int[] remove(int[] array,int index);\\nstatic int[] removeElement(int[] array,int element);\\nstatic long[] remove(long[] array,int index);\\nstatic long[] removeElement(long[] array,long element);\\nstatic short[] remove(short[] array,int index);\\nstatic short[] removeElement(short[] array,short element);\\nstatic Object[] clearNull(Object[] arr);\\n }\\npublic interface ClassUtils {static String getShortClassName(Object object,String valueIfNull);\\nstatic String getShortClassName(Class cls);\\nstatic String getShortClassName(String className);\\nstatic String getPackageName(Object object,String valueIfNull);\\nstatic String getPackageName(Class cls);\\nstatic String getPackageName(String className);\\nstatic List> getAllSuperclasses(Class cls);\\nstatic List> getAllInterfaces(Class cls);\\nstatic List> convertClassNamesToClasses(List classNames);\\nstatic List convertClassesToClassNames(List classes);\\nstatic boolean isAssignable(Class[] classArray,Class[] toClassArray);\\nstatic boolean isAssignable(Class[] classArray,Class[] toClassArray,boolean autoboxing);\\nstatic boolean isAssignable(Class cls,Class toClass);\\nstatic boolean isAssignable(Class cls,Class toClass,boolean autoboxing);\\nstatic Class primitiveToWrapper(Class cls);\\nstatic Class[] primitivesToWrappers(Class[] classes);\\nstatic Class wrapperToPrimitive(Class cls);\\nstatic Class[] wrappersToPrimitives(Class[] classes);\\nstatic boolean isInnerClass(Class cls);\\nstatic Class getClass(ClassLoader classLoader,String className,boolean initialize);\\nstatic Class getClass(ClassLoader classLoader,String className);\\nstatic Class getClass(String className);\\nstatic Class getClass(String className,boolean initialize);\\nstatic Method getPublicMethod(Class cls,String methodName,Class parameterTypes);\\nstatic Class[] toClass(Object[] array);\\nstatic String getShortCanonicalName(Object object,String valueIfNull);\\nstatic String getShortCanonicalName(Class cls);\\nstatic String getShortCanonicalName(String canonicalName);\\nstatic String getPackageCanonicalName(Object object,String valueIfNull);\\nstatic String getPackageCanonicalName(Class cls);\\nstatic String getPackageCanonicalName(String canonicalName);\\nstatic ClassLoader getClassLoader(ClassLoader classLoader);\\nstatic boolean isLangClass(Class target);\\nstatic String getDescName(Class type);\\nstatic String getDescNameWithOutModifiers(Method method);\\nstatic String getDescName(Method method);\\nstatic Class getSuperClassGenricType(Class clazz,int index);\\nstatic T newInstance(Class clazz);\\n }\\n\" }", "class_name": "ReflectionToStringBuilder", "code": "static String[] toNoNullStringArray(Collection collection){\n if (collection == null) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return toNoNullStringArray(collection.toArray());\n}\n", "docstring": "/** \n * Converts the given Collection into an array of Strings. The returned array does not contain null entries. Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} if an array element is null.\n * @param collection The collection to convert\n * @return A new array of Strings.\n */\n", "end_lineno": "326", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.builder;\nimport net.hasor.utils.ArrayUtils;\nimport net.hasor.utils.ClassUtils;\n\nimport java.lang.reflect.AccessibleObject;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\n\n/**\n *

\n * Assists in implementing {@link Object#toString()} methods using reflection.\n *

\n *\n *

\n * This class uses reflection to determine the fields to append. Because these fields are usually private, the class\n * uses {@link java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[], boolean)} to\n * change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are\n * set up correctly.\n *

\n *\n *

\n * A typical invocation for this method would look like:\n *

\n *\n *
\n * public String toString() {\n *   return ReflectionToStringBuilder.toString(this);\n * }
\n *\n *\n *\n *

\n * You can also use the builder to debug 3rd party objects:\n *

\n *\n *
\n * System.out.println(\"An object: \" + ReflectionToStringBuilder.toString(anObject));
\n *\n *\n *\n *

\n * A subclass can control field output by overriding the methods:\n *

    \n *
  • {@link #accept(java.lang.reflect.Field)}
  • \n *
  • {@link #getValue(java.lang.reflect.Field)}
  • \n *
\n *

\n *

\n * For example, this method does not include the password field in the returned\n * String:\n *

\n *\n *
\n * public String toString() {\n *     return (new ReflectionToStringBuilder(this) {\n *         protected boolean accept(Field f) {\n *             return super.accept(f) && !f.getName().equals(\"password\");\n *         }\n *     }).toString();\n * }
\n *\n *\n *\n *

\n * The exact format of the toString is determined by the {@link ToStringStyle} passed into the\n * constructor.\n *

\n *\n * @author Apache Software Foundation\n * @author Gary Gregory\n * @author Pete Gieser\n * @since 2.0\n * @version $Id: ReflectionToStringBuilder.java 905636 2010-02-02 14:03:32Z niallp $\n */\npublic class ReflectionToStringBuilder extends ToStringBuilder {\n /**\n *

\n * Builds a toString value using the default ToStringStyle through reflection.\n *

\n *\n *

\n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

\n *\n *

\n * Transient members will be not be included, as they are likely derived. Static fields will not be included.\n * Superclass fields will be appended.\n *

\n *\n * @param object\n * the Object to be output\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object is null\n */\n public static String toString(Object object) {\n return toString(object, null, false, false, null);\n }\n\n /**\n *

\n * Builds a toString value through reflection.\n *

\n *\n *

\n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

\n *\n *

\n * Transient members will be not be included, as they are likely derived. Static fields will not be included.\n * Superclass fields will be appended.\n *

\n *\n *

\n * If the style is null, the default ToStringStyle is used.\n *

\n *\n * @param object\n * the Object to be output\n * @param style\n * the style of the toString to create, may be null\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object or ToStringStyle is null\n */\n public static String toString(Object object, ToStringStyle style) {\n return toString(object, style, false, false, null);\n }\n\n /**\n *

\n * Builds a toString value through reflection.\n *

\n *\n *

\n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

\n *\n *

\n * If the outputTransients is true, transient members will be output, otherwise they\n * are ignored, as they are likely derived fields, and not part of the value of the Object.\n *

\n *\n *

\n * Static fields will not be included. Superclass fields will be appended.\n *

\n *\n *

\n * If the style is null, the default ToStringStyle is used.\n *

\n *\n * @param object\n * the Object to be output\n * @param style\n * the style of the toString to create, may be null\n * @param outputTransients\n * whether to include transient fields\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object is null\n */\n public static String toString(Object object, ToStringStyle style, boolean outputTransients) {\n return toString(object, style, outputTransients, false, null);\n }\n\n /**\n *

\n * Builds a toString value through reflection.\n *

\n *\n *

\n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

\n *\n *

\n * If the outputTransients is true, transient fields will be output, otherwise they\n * are ignored, as they are likely derived fields, and not part of the value of the Object.\n *

\n *\n *

\n * If the outputStatics is true, static fields will be output, otherwise they are\n * ignored.\n *

\n *\n *

\n * Static fields will not be included. Superclass fields will be appended.\n *

\n *\n *

\n * If the style is null, the default ToStringStyle is used.\n *

\n *\n * @param object\n * the Object to be output\n * @param style\n * the style of the toString to create, may be null\n * @param outputTransients\n * whether to include transient fields\n * @param outputStatics\n * whether to include transient fields\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object is null\n * @since 2.1\n */\n public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics) {\n return toString(object, style, outputTransients, outputStatics, null);\n }\n\n /**\n *

\n * Builds a toString value through reflection.\n *

\n *\n *

\n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

\n *\n *

\n * If the outputTransients is true, transient fields will be output, otherwise they\n * are ignored, as they are likely derived fields, and not part of the value of the Object.\n *

\n *\n *

\n * If the outputStatics is true, static fields will be output, otherwise they are\n * ignored.\n *

\n *\n *

\n * Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as\n * java.lang.Object.\n *

\n *\n *

\n * If the style is null, the default ToStringStyle is used.\n *

\n *\n * @param object\n * the Object to be output\n * @param style\n * the style of the toString to create, may be null\n * @param outputTransients\n * whether to include transient fields\n * @param outputStatics\n * whether to include static fields\n * @param reflectUpToClass\n * the superclass to reflect up to (inclusive), may be null\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object is null\n * @since 2.1\n */\n public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics, Class reflectUpToClass) {\n return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics).toString();\n }\n\n /**\n * Builds a String for a toString method excluding the given field name.\n *\n * @param object\n * The object to \"toString\".\n * @param excludeFieldName\n * The field name to exclude\n * @return The toString value.\n */\n public static String toStringExclude(Object object, final String excludeFieldName) {\n return toStringExclude(object, new String[] { excludeFieldName });\n }\n\n /**\n * Builds a String for a toString method excluding the given field names.\n *\n * @param object\n * The object to \"toString\".\n * @param excludeFieldNames\n * The field names to exclude. Null excludes nothing.\n * @return The toString value.\n */\n public static String toStringExclude(Object object, Collection /*String*/ excludeFieldNames) {\n return toStringExclude(object, toNoNullStringArray(excludeFieldNames));\n }\n\n /**\n * Converts the given Collection into an array of Strings. The returned array does not contain null\n * entries. Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} if an array element \n * is null.\n *\n * @param collection\n * The collection to convert\n * @return A new array of Strings.\n */\n static String[] toNoNullStringArray(Collection collection) {\n if (collection == null) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return toNoNullStringArray(collection.toArray());\n }\n\n /**\n * Returns a new array of Strings without null elements. Internal method used to normalize exclude lists\n * (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException}\n * if an array element is null.\n *\n * @param array\n * The array to check\n * @return The given array or a new array without null.\n */\n static String[] toNoNullStringArray(Object[] array) {\n ArrayList list = new ArrayList(array.length);\n for (int i = 0; i < array.length; i++) {\n Object e = array[i];\n if (e != null) {\n list.add(e.toString());\n }\n }\n return (String[]) list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);\n }\n\n /**\n * Builds a String for a toString method excluding the given field names.\n *\n * @param object\n * The object to \"toString\".\n * @param excludeFieldNames\n * The field names to exclude\n * @return The toString value.\n */\n public static String toStringExclude(Object object, String[] excludeFieldNames) {\n return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString();\n }\n\n /**\n * Whether or not to append static fields.\n */\n private boolean appendStatics = false;\n /**\n * Whether or not to append transient fields.\n */\n private boolean appendTransients = false;\n /**\n * Which field names to exclude from output. Intended for fields like \"password\".\n */\n private String[] excludeFieldNames;\n /**\n * The last super class to stop appending fields for.\n */\n private Class upToClass = null;\n\n /**\n *

\n * Constructor.\n *

\n *\n *

\n * This constructor outputs using the default style set with setDefaultStyle.\n *

\n *\n * @param object\n * the Object to build a toString for, must not be null\n * @throws IllegalArgumentException\n * if the Object passed in is null\n */\n public ReflectionToStringBuilder(Object object) {\n super(object);\n }\n\n /**\n *

\n * Constructor.\n *

\n *\n *

\n * If the style is null, the default style is used.\n *

\n *\n * @param object\n * the Object to build a toString for, must not be null\n * @param style\n * the style of the toString to create, may be null\n * @throws IllegalArgumentException\n * if the Object passed in is null\n */\n public ReflectionToStringBuilder(Object object, ToStringStyle style) {\n super(object, style);\n }\n\n /**\n *

\n * Constructor.\n *

\n *\n *

\n * If the style is null, the default style is used.\n *

\n *\n *

\n * If the buffer is null, a new one is created.\n *

\n *\n * @param object\n * the Object to build a toString for\n * @param style\n * the style of the toString to create, may be null\n * @param buffer\n * the StringBuffer to populate, may be null\n * @throws IllegalArgumentException\n * if the Object passed in is null\n */\n public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) {\n super(object, style, buffer);\n }\n\n /**\n * Constructor.\n *\n * @param object\n * the Object to build a toString for\n * @param style\n * the style of the toString to create, may be null\n * @param buffer\n * the StringBuffer to populate, may be null\n * @param reflectUpToClass\n * the superclass to reflect up to (inclusive), may be null\n * @param outputTransients\n * whether to include transient fields\n * @param outputStatics\n * whether to include static fields\n * @since 2.1\n */\n public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer, Class reflectUpToClass, boolean outputTransients, boolean outputStatics) {\n super(object, style, buffer);\n this.setUpToClass(reflectUpToClass);\n this.setAppendTransients(outputTransients);\n this.setAppendStatics(outputStatics);\n }\n\n /**\n * Returns whether or not to append the given Field.\n *
    \n *
  • Transient fields are appended only if {@link #isAppendTransients()} returns true.\n *
  • Static fields are appended only if {@link #isAppendStatics()} returns true.\n *
  • Inner class fields are not appened.
  • \n *
\n *\n * @param field The Field to test.\n * @return Whether or not to append the given Field.\n */\n protected boolean accept(Field field) {\n if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {\n // Reject field from inner class.\n return false;\n }\n if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) {\n // Reject transient fields.\n return false;\n }\n if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) {\n // Reject static fields.\n return false;\n }\n if (this.getExcludeFieldNames() != null && Arrays.binarySearch(this.getExcludeFieldNames(), field.getName()) >= 0) {\n // Reject fields from the getExcludeFieldNames list.\n return false;\n }\n return true;\n }\n\n /**\n *

\n * Appends the fields and values defined by the given object of the given Class.\n *

\n *\n *

\n * If a cycle is detected as an object is "toString()'ed", such an object is rendered as if\n * Object.toString() had been called and not implemented by the object.\n *

\n *\n * @param clazz The class of object parameter\n */\n protected void appendFieldsIn(Class clazz) {\n if (clazz.isArray()) {\n this.reflectionAppendArray(this.getObject());\n return;\n }\n Field[] fields = clazz.getDeclaredFields();\n AccessibleObject.setAccessible(fields, true);\n for (int i = 0; i < fields.length; i++) {\n Field field = fields[i];\n String fieldName = field.getName();\n if (this.accept(field)) {\n try {\n // Warning: Field.get(Object) creates wrappers objects\n // for primitive types.\n Object fieldValue = this.getValue(field);\n this.append(fieldName, fieldValue);\n } catch (IllegalAccessException ex) {\n //this can't happen. Would get a Security exception\n // instead\n //throw a runtime exception in case the impossible\n // happens.\n throw new InternalError(\"Unexpected IllegalAccessException: \" + ex.getMessage());\n }\n }\n }\n }\n\n /**\n * @return Returns the excludeFieldNames.\n */\n public String[] getExcludeFieldNames() {\n return this.excludeFieldNames;\n }\n\n /**\n *

\n * Gets the last super class to stop appending fields for.\n *

\n *\n * @return The last super class to stop appending fields for.\n */\n public Class getUpToClass() {\n return this.upToClass;\n }\n\n /**\n *

\n * Calls java.lang.reflect.Field.get(Object).\n *

\n *\n * @param field The Field to query.\n * @return The Object from the given Field.\n *\n * @throws IllegalArgumentException see {@link java.lang.reflect.Field#get(Object)}\n * @throws IllegalAccessException see {@link java.lang.reflect.Field#get(Object)}\n * @see java.lang.reflect.Field#get(Object)\n */\n protected Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException {\n return field.get(this.getObject());\n }\n\n /**\n *

\n * Gets whether or not to append static fields.\n *

\n *\n * @return Whether or not to append static fields.\n * @since 2.1\n */\n public boolean isAppendStatics() {\n return this.appendStatics;\n }\n\n /**\n *

\n * Gets whether or not to append transient fields.\n *

\n *\n * @return Whether or not to append transient fields.\n */\n public boolean isAppendTransients() {\n return this.appendTransients;\n }\n\n /**\n *

\n * Append to the toString an Object array.\n *

\n *\n * @param array\n * the array to add to the toString\n * @return this\n */\n public ToStringBuilder reflectionAppendArray(Object array) {\n this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array);\n return this;\n }\n\n /**\n *

\n * Sets whether or not to append static fields.\n *

\n *\n * @param appendStatics\n * Whether or not to append static fields.\n * @since 2.1\n */\n public void setAppendStatics(boolean appendStatics) {\n this.appendStatics = appendStatics;\n }\n\n /**\n *

\n * Sets whether or not to append transient fields.\n *

\n *\n * @param appendTransients Whether or not to append transient fields.\n */\n public void setAppendTransients(boolean appendTransients) {\n this.appendTransients = appendTransients;\n }\n\n /**\n * Sets the field names to exclude.\n *\n * @param excludeFieldNamesParam\n * The excludeFieldNames to excluding from toString or null.\n * @return this\n */\n public ReflectionToStringBuilder setExcludeFieldNames(String[] excludeFieldNamesParam) {\n if (excludeFieldNamesParam == null) {\n this.excludeFieldNames = null;\n } else {\n this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam);\n Arrays.sort(this.excludeFieldNames);\n }\n return this;\n }\n\n /**\n *

\n * Sets the last super class to stop appending fields for.\n *

\n *\n * @param clazz\n * The last super class to stop appending fields for.\n */\n public void setUpToClass(Class clazz) {\n if (clazz != null) {\n Object object = getObject();\n if (object != null && clazz.isInstance(object) == false) {\n throw new IllegalArgumentException(\"Specified class is not a superclass of the object\");\n }\n }\n this.upToClass = clazz;\n }\n\n /**\n *

\n * Gets the String built by this builder.\n *

\n *\n * @return the built string\n */\n public String toString() {\n if (this.getObject() == null) {\n return this.getStyle().getNullText();\n }\n Class clazz = this.getObject().getClass();\n this.appendFieldsIn(clazz);\n while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) {\n clazz = clazz.getSuperclass();\n this.appendFieldsIn(clazz);\n }\n return super.toString();\n }\n}\n", "file_name": "ReflectionToStringBuilder.java", "human_label": "If collection is null, convert collection to EMPTY_STRING_ARRAY. Otherwise, convert collection to an array of strings and return the array. ???", "level": "project_runnable", "lineno": "312", "name": "toNoNullStringArray", "oracle_context": "{ \"apis\" : \"[toArray]\", \"classes\" : \"[ArrayUtils]\", \"vars\" : \"[EMPTY_STRING_ARRAY]\" }", "package": "net.hasor.utils.builder", "project": "hasor-master" }, { "_id": "636767081a6d9265ec0179a2", "all_context": "{ \"class_level\" : \"import java.math.BigDecimal;\\nimport java.math.BigInteger;\\nNumberUtils();\\nstringToInt(String str,int defaultValue);\\ncreateNumber(String val);\\nisAllZeros(String s);\\ncreateFloat(String val);\\ncreateDouble(String val);\\ncreateInteger(String val);\\ncreateLong(String val);\\ncreateBigInteger(String val);\\ncreateBigDecimal(String val);\\nminimum(long a,long b,long c);\\nminimum(int a,int b,int c);\\nmaximum(long a,long b,long c);\\nmaximum(int a,int b,int c);\\ncompare(double lhs,double rhs);\\ncompare(float lhs,float rhs);\\nisDigits(String str);\\nisNumber(String str);\\nisByteType(Class targetType);\\nisShortType(Class targetType);\\nisIntType(Class targetType);\\nisLongType(Class targetType);\\nisFloatType(Class targetType);\\nisDoubleType(Class targetType);\\nstringToInt(String str);\\n\", \"repo_level\" : \"\" }", "class_name": "NumberUtils", "code": "private static boolean isAllZeros(String s){\n if (s == null) {\n return true;\n }\n for (int i=s.length() - 1; i >= 0; i--) {\n if (s.charAt(i) != '0') {\n return false;\n }\n }\n return s.length() > 0;\n}\n", "docstring": "/** \n *

Utility method for {@link #createNumber(String)}.

Returns true if s is null.

\n * @param s the String to check\n * @return if it is all zeros or null\n */\n", "end_lineno": "291", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\n\n/**\n *

Provides extra functionality for Java Number classes.

\n *\n * @author Apache Software Foundation\n * @author Rand McNeely\n * @author Steve Downey\n * @author Eric Pugh\n * @author Phil Steitz\n * @since 1.0\n * @version $Id: NumberUtils.java 905636 2010-02-02 14:03:32Z niallp $\n */\npublic final class NumberUtils {\n // DEPRECATED CLASS !!!\n\n /**\n *

NumberUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as NumberUtils.stringToInt(\"6\");.

\n *\n *

This constructor is public to permit tools that require a JavaBean instance\n * to operate.

\n */\n public NumberUtils() {\n super();\n }\n //--------------------------------------------------------------------\n\n /**\n *

Convert a String to an int, returning\n * zero if the conversion fails.

\n *\n * @param str the string to convert\n * @return the int represented by the string, or zero if\n * conversion fails\n */\n public static int stringToInt(String str) {\n return stringToInt(str, 0);\n }\n\n /**\n *

Convert a String to an int, returning a\n * default value if the conversion fails.

\n *\n * @param str the string to convert\n * @param defaultValue the default value\n * @return the int represented by the string, or the default if conversion fails\n */\n public static int stringToInt(String str, int defaultValue) {\n try {\n return Integer.parseInt(str);\n } catch (NumberFormatException nfe) {\n return defaultValue;\n }\n }\n //--------------------------------------------------------------------\n // must handle Long, Float, Integer, Float, Short,\n // BigDecimal, BigInteger and Byte\n // useful methods:\n // Byte.decode(String)\n // Byte.valueOf(String,int radix)\n // Byte.valueOf(String)\n // Double.valueOf(String)\n // Float.valueOf(String)\n // new Float(String)\n // Integer.valueOf(String,int radix)\n // Integer.valueOf(String)\n // Integer.decode(String)\n // Integer.getInteger(String)\n // Integer.getInteger(String,int val)\n // Integer.getInteger(String,Integer val)\n // new Integer(String)\n // new Double(String)\n // new Byte(String)\n // new Long(String)\n // Long.getLong(String)\n // Long.getLong(String,int)\n // Long.getLong(String,Integer)\n // Long.valueOf(String,int)\n // Long.valueOf(String)\n // new Short(String)\n // Short.decode(String)\n // Short.valueOf(String,int)\n // Short.valueOf(String)\n // new BigDecimal(String)\n // new BigInteger(String)\n // new BigInteger(String,int radix)\n // Possible inputs:\n // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd\n // plus minus everything. Prolly more. A lot are not separable.\n\n /**\n *

Turns a string value into a java.lang.Number.

\n *\n *

First, the value is examined for a type qualifier on the end\n * ('f','F','d','D','l','L'). If it is found, it starts \n * trying to create successively larger types from the type specified\n * until one is found that can hold the value.

\n *\n *

If a type specifier is not found, it will check for a decimal point\n * and then try successively larger types from Integer to\n * BigInteger and from Float to\n * BigDecimal.

\n *\n *

If the string starts with 0x or -0x, it\n * will be interpreted as a hexadecimal integer. Values with leading\n * 0's will not be interpreted as octal.

\n *\n * @param val String containing a number\n * @return Number created from the string\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Number createNumber(String val) throws NumberFormatException {\n if (val == null) {\n return null;\n }\n if (val.length() == 0) {\n throw new NumberFormatException(\"\\\"\\\" is not a valid number.\");\n }\n if (val.length() == 1 && !Character.isDigit(val.charAt(0))) {\n throw new NumberFormatException(val + \" is not a valid number.\");\n }\n if (val.startsWith(\"--\")) {\n // this is protection for poorness in java.lang.BigDecimal.\n // it accepts this as a legal value, but it does not appear \n // to be in specification of class. OS X Java parses it to \n // a wrong value.\n return null;\n }\n if (val.startsWith(\"0x\") || val.startsWith(\"-0x\")) {\n return createInteger(val);\n }\n char lastChar = val.charAt(val.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = val.indexOf('.');\n int expPos = val.indexOf('e') + val.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos) {\n throw new NumberFormatException(val + \" is not a valid number.\");\n }\n dec = val.substring(decPos + 1, expPos);\n } else {\n dec = val.substring(decPos + 1);\n }\n mant = val.substring(0, decPos);\n } else {\n if (expPos > -1) {\n mant = val.substring(0, expPos);\n } else {\n mant = val;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar)) {\n if (expPos > -1 && expPos < val.length() - 1) {\n exp = val.substring(expPos + 1, val.length() - 1);\n } else {\n exp = null;\n }\n //Requesting a specific type..\n String numeric = val.substring(0, val.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l':\n case 'L':\n if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) {\n //Too big for a long\n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(val + \" is not a valid number.\");\n case 'f':\n case 'F':\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f == 0.0F && !allZeros))) {\n //If it's too big for a float or the float value = 0 and the string\n //has non-zeros in it, then float does not have the precision we want\n return f;\n }\n } catch (NumberFormatException e) {\n // ignore the bad number\n }\n //$FALL-THROUGH$\n case 'd':\n case 'D':\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n // empty catch\n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) {\n // empty catch\n }\n //$FALL-THROUGH$\n default:\n throw new NumberFormatException(val + \" is not a valid number.\");\n }\n } else {\n //User doesn't have a preference on the return type, so let's start\n //small and go from there...\n if (expPos > -1 && expPos < val.length() - 1) {\n exp = val.substring(expPos + 1);\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n //Must be an int,long,bigint\n try {\n return createInteger(val);\n } catch (NumberFormatException nfe) {\n // empty catch\n }\n try {\n return createLong(val);\n } catch (NumberFormatException nfe) {\n // empty catch\n }\n return createBigInteger(val);\n } else {\n //Must be a float,double,BigDec\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(val);\n if (!(f.isInfinite() || (f == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n // empty catch\n }\n try {\n Double d = createDouble(val);\n if (!(d.isInfinite() || (d == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n // empty catch\n }\n return createBigDecimal(val);\n }\n }\n }\n\n /**\n *

Utility method for {@link #createNumber(String)}.

\n *\n *

Returns true if s is null.

\n *\n * @param s the String to check\n * @return if it is all zeros or null\n */\n private static boolean isAllZeros(String s) {\n if (s == null) {\n return true;\n }\n for (int i = s.length() - 1; i >= 0; i--) {\n if (s.charAt(i) != '0') {\n return false;\n }\n }\n return s.length() > 0;\n }\n //--------------------------------------------------------------------\n\n /**\n *

Convert a String to a Float.

\n *\n * @param val a String to convert\n * @return converted Float\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Float createFloat(String val) {\n return Float.valueOf(val);\n }\n\n /**\n *

Convert a String to a Double.

\n *\n * @param val a String to convert\n * @return converted Double\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Double createDouble(String val) {\n return Double.valueOf(val);\n }\n\n /**\n *

Convert a String to a Integer, handling\n * hex and octal notations.

\n *\n * @param val a String to convert\n * @return converted Integer\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Integer createInteger(String val) {\n // decode() handles 0xAABD and 0777 (hex and octal) as well.\n return Integer.decode(val);\n }\n\n /**\n *

Convert a String to a Long.

\n *\n * @param val a String to convert\n * @return converted Long\n * @throws NumberFormatException if the value cannot be converted\n */\n public static Long createLong(String val) {\n return Long.valueOf(val);\n }\n\n /**\n *

Convert a String to a BigInteger.

\n *\n * @param val a String to convert\n * @return converted BigInteger\n * @throws NumberFormatException if the value cannot be converted\n */\n public static BigInteger createBigInteger(String val) {\n return new BigInteger(val);\n }\n\n /**\n *

Convert a String to a BigDecimal.

\n *\n * @param val a String to convert\n * @return converted BigDecimal\n * @throws NumberFormatException if the value cannot be converted\n */\n public static BigDecimal createBigDecimal(String val) {\n return new BigDecimal(val);\n }\n //--------------------------------------------------------------------\n\n /**\n *

Gets the minimum of three long values.

\n *\n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the smallest of the values\n */\n public static long minimum(long a, long b, long c) {\n if (b < a) {\n a = b;\n }\n if (c < a) {\n a = c;\n }\n return a;\n }\n\n /**\n *

Gets the minimum of three int values.

\n *\n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the smallest of the values\n */\n public static int minimum(int a, int b, int c) {\n if (b < a) {\n a = b;\n }\n if (c < a) {\n a = c;\n }\n return a;\n }\n\n /**\n *

Gets the maximum of three long values.

\n *\n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the largest of the values\n */\n public static long maximum(long a, long b, long c) {\n if (b > a) {\n a = b;\n }\n if (c > a) {\n a = c;\n }\n return a;\n }\n\n /**\n *

Gets the maximum of three int values.

\n *\n * @param a value 1\n * @param b value 2\n * @param c value 3\n * @return the largest of the values\n */\n public static int maximum(int a, int b, int c) {\n if (b > a) {\n a = b;\n }\n if (c > a) {\n a = c;\n }\n return a;\n }\n //--------------------------------------------------------------------\n\n /**\n *

Compares two doubles for order.

\n *\n *

This method is more comprehensive than the standard Java greater\n * than, less than and equals operators.

\n *
    \n *
  • It returns -1 if the first value is less than the second.\n *
  • It returns +1 if the first value is greater than the second.\n *
  • It returns 0 if the values are equal.\n *
\n *\n *

\n * The ordering is as follows, largest to smallest:\n *

    \n *
  • NaN\n *
  • Positive infinity\n *
  • Maximum double\n *
  • Normal positive numbers\n *
  • +0.0\n *
  • -0.0\n *
  • Normal negative numbers\n *
  • Minimum double (-Double.MAX_VALUE)\n *
  • Negative infinity\n *
\n *

\n *\n *

Comparing NaN with NaN will\n * return 0.

\n *\n * @param lhs the first double\n * @param rhs the second double\n * @return -1 if lhs is less, +1 if greater,\n * 0 if equal to rhs\n */\n public static int compare(double lhs, double rhs) {\n if (lhs < rhs) {\n return -1;\n }\n if (lhs > rhs) {\n return +1;\n }\n // Need to compare bits to handle 0.0 == -0.0 being true\n // compare should put -0.0 < +0.0\n // Two NaNs are also == for compare purposes\n // where NaN == NaN is false\n long lhsBits = Double.doubleToLongBits(lhs);\n long rhsBits = Double.doubleToLongBits(rhs);\n if (lhsBits == rhsBits) {\n return 0;\n }\n // Something exotic! A comparison to NaN or 0.0 vs -0.0\n // Fortunately NaN's long is > than everything else\n // Also negzeros bits < poszero\n // NAN: 9221120237041090560\n // MAX: 9218868437227405311\n // NEGZERO: -9223372036854775808\n if (lhsBits < rhsBits) {\n return -1;\n } else {\n return +1;\n }\n }\n\n /**\n *

Compares two floats for order.

\n *\n *

This method is more comprehensive than the standard Java greater than,\n * less than and equals operators.

\n *
    \n *
  • It returns -1 if the first value is less than the second.\n *
  • It returns +1 if the first value is greater than the second.\n *
  • It returns 0 if the values are equal.\n *
\n *\n *

The ordering is as follows, largest to smallest:\n *

    \n *
  • NaN\n *
  • Positive infinity\n *
  • Maximum float\n *
  • Normal positive numbers\n *
  • +0.0\n *
  • -0.0\n *
  • Normal negative numbers\n *
  • Minimum float (-Float.MAX_VALUE)\n *
  • Negative infinity\n *
\n *\n *

Comparing NaN with NaN will return\n * 0.

\n *\n * @param lhs the first float\n * @param rhs the second float\n * @return -1 if lhs is less, +1 if greater,\n * 0 if equal to rhs\n */\n public static int compare(float lhs, float rhs) {\n if (lhs < rhs) {\n return -1;\n }\n if (lhs > rhs) {\n return +1;\n }\n //Need to compare bits to handle 0.0 == -0.0 being true\n // compare should put -0.0 < +0.0\n // Two NaNs are also == for compare purposes\n // where NaN == NaN is false\n int lhsBits = Float.floatToIntBits(lhs);\n int rhsBits = Float.floatToIntBits(rhs);\n if (lhsBits == rhsBits) {\n return 0;\n }\n //Something exotic! A comparison to NaN or 0.0 vs -0.0\n //Fortunately NaN's int is > than everything else\n //Also negzeros bits < poszero\n //NAN: 2143289344\n //MAX: 2139095039\n //NEGZERO: -2147483648\n if (lhsBits < rhsBits) {\n return -1;\n } else {\n return +1;\n }\n }\n //--------------------------------------------------------------------\n\n /**\n *

Checks whether the String contains only\n * digit characters.

\n *\n *

Null and empty String will return\n * false.

\n *\n * @param str the String to check\n * @return true if str contains only unicode numeric\n */\n public static boolean isDigits(String str) {\n if ((str == null) || (str.length() == 0)) {\n return false;\n }\n for (int i = 0; i < str.length(); i++) {\n if (!Character.isDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks whether the String a valid Java number.

\n *\n *

Valid numbers include hexadecimal marked with the 0x\n * qualifier, scientific notation and numbers marked with a type\n * qualifier (e.g. 123L).

\n *\n *

Null and empty String will return\n * false.

\n *\n * @param str the String to check\n * @return true if the string is a correctly formatted number\n */\n public static boolean isNumber(String str) {\n if (StringUtils.isEmpty(str)) {\n return false;\n }\n char[] chars = str.toCharArray();\n int sz = chars.length;\n boolean hasExp = false;\n boolean hasDecPoint = false;\n boolean allowSigns = false;\n boolean foundDigit = false;\n // deal with any possible sign up front\n int start = (chars[0] == '-') ? 1 : 0;\n if (sz > start + 1) {\n if (chars[start] == '0' && chars[start + 1] == 'x') {\n int i = start + 2;\n if (i == sz) {\n return false; // str == \"0x\"\n }\n // checking hex (it can't be anything else)\n for (; i < chars.length; i++) {\n if ((chars[i] < '0' || chars[i] > '9') && (chars[i] < 'a' || chars[i] > 'f') && (chars[i] < 'A' || chars[i] > 'F')) {\n return false;\n }\n }\n return true;\n }\n }\n sz--; // don't want to loop to the last char, check it afterwords\n // for type qualifiers\n int i = start;\n // loop to the next to last char or to the last char if we need another digit to\n // make a valid number (e.g. chars[0..5] = \"1234E\")\n while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {\n if (chars[i] >= '0' && chars[i] <= '9') {\n foundDigit = true;\n allowSigns = false;\n } else if (chars[i] == '.') {\n if (hasDecPoint || hasExp) {\n // two decimal points or dec in exponent \n return false;\n }\n hasDecPoint = true;\n } else if (chars[i] == 'e' || chars[i] == 'E') {\n // we've already taken care of hex.\n if (hasExp) {\n // two E's\n return false;\n }\n if (!foundDigit) {\n return false;\n }\n hasExp = true;\n allowSigns = true;\n } else if (chars[i] == '+' || chars[i] == '-') {\n if (!allowSigns) {\n return false;\n }\n allowSigns = false;\n foundDigit = false; // we need a digit after the E\n } else {\n return false;\n }\n i++;\n }\n if (i < chars.length) {\n if (chars[i] >= '0' && chars[i] <= '9') {\n // no type qualifier, OK\n return true;\n }\n if (chars[i] == 'e' || chars[i] == 'E') {\n // can't have an E at the last byte\n return false;\n }\n if (!allowSigns && (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F')) {\n return foundDigit;\n }\n if (chars[i] == 'l' || chars[i] == 'L') {\n // not allowing L with an exponent\n return foundDigit && !hasExp;\n }\n // last character is illegal\n return false;\n }\n // allowSigns is true iff the val ends in 'E'\n // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass\n return !allowSigns && foundDigit;\n }\n\n public static boolean isByteType(Class targetType) {\n return targetType.equals(Byte.class) || targetType.equals(Byte.TYPE);\n }\n\n public static boolean isShortType(Class targetType) {\n return targetType.equals(Short.class) || targetType.equals(Short.TYPE);\n }\n\n public static boolean isIntType(Class targetType) {\n return targetType.equals(Integer.class) || targetType.equals(Integer.TYPE);\n }\n\n public static boolean isLongType(Class targetType) {\n return targetType.equals(Long.class) || targetType.equals(Long.TYPE);\n }\n\n public static boolean isFloatType(Class targetType) {\n return targetType.equals(Float.class) || targetType.equals(Float.TYPE);\n }\n\n public static boolean isDoubleType(Class targetType) {\n return targetType.equals(Double.class) || targetType.equals(Double.TYPE);\n }\n}\n", "file_name": "NumberUtils.java", "human_label": "Check whether a character string is all consist of zero. ", "level": "self_contained", "lineno": "273", "name": "isAllZeros", "oracle_context": "{ \"apis\" : \"[length, charAt]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636766821a6d9265ec0174b3", "all_context": "{ \"class_level\" : \"import org.atmosphere.cache.BroadcastMessage;\\nimport org.atmosphere.cache.CacheMessage;\\nimport org.atmosphere.cpr.BroadcastFilter.BroadcastAction;\\nimport org.atmosphere.lifecycle.LifecycleHandler;\\nimport org.atmosphere.pool.PoolableBroadcasterFactory;\\nimport org.atmosphere.util.Utils;\\nimport org.slf4j.Logger;\\nimport org.slf4j.LoggerFactory;\\nimport java.io.IOException;\\nimport java.net.URI;\\nimport java.util.ArrayList;\\nimport java.util.Collection;\\nimport java.util.Collections;\\nimport java.util.HashMap;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Map;\\nimport java.util.Set;\\nimport java.util.UUID;\\nimport java.util.concurrent.BlockingQueue;\\nimport java.util.concurrent.Callable;\\nimport java.util.concurrent.ConcurrentHashMap;\\nimport java.util.concurrent.ConcurrentLinkedQueue;\\nimport java.util.concurrent.Future;\\nimport java.util.concurrent.LinkedBlockingQueue;\\nimport java.util.concurrent.RejectedExecutionException;\\nimport java.util.concurrent.TimeUnit;\\nimport java.util.concurrent.atomic.AtomicBoolean;\\nimport java.util.concurrent.atomic.AtomicInteger;\\nimport java.util.concurrent.atomic.AtomicLong;\\nimport static org.atmosphere.cpr.ApplicationConfig.BACKWARD_COMPATIBLE_WEBSOCKET_BEHAVIOR;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CACHE_STRATEGY;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_SHAREABLE_LISTENERS;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_WAIT_TIME;\\nimport static org.atmosphere.cpr.ApplicationConfig.CACHE_MESSAGE_ON_IO_FLUSH_EXCEPTION;\\nimport static org.atmosphere.cpr.ApplicationConfig.MAX_INACTIVE;\\nimport static org.atmosphere.cpr.ApplicationConfig.OUT_OF_ORDER_BROADCAST;\\nimport static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID;\\nimport static org.atmosphere.cpr.ApplicationConfig.WRITE_TIMEOUT;\\nimport static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.NEVER;\\nimport static org.atmosphere.cpr.FrameworkConfig.INJECTED_ATMOSPHERE_RESOURCE;\\nint POLLING_DEFAULT;\\nString CACHED;\\nLogger logger;\\nString DESTROYED;\\nList EMPTY_LISTENERS;\\nConcurrentLinkedQueue resources;\\nBroadcasterConfig bc;\\nBlockingQueue messages;\\nCollection broadcasterListeners;\\nAtomicBoolean started;\\nAtomicBoolean initialized;\\nAtomicBoolean destroyed;\\nSCOPE scope;\\nString name;\\nConcurrentLinkedQueue delayedBroadcast;\\nConcurrentLinkedQueue broadcastOnResume;\\nConcurrentLinkedQueue lifeCycleListeners;\\nConcurrentHashMap writeQueues;\\nWriteQueue uniqueWriteQueue;\\nAtomicInteger dispatchThread;\\nFuture[] notifierFuture;\\nFuture[] asyncWriteFuture;\\nPOLICY policy;\\nAtomicLong maxSuspendResource;\\nAtomicBoolean requestScoped;\\nAtomicBoolean recentActivity;\\nBroadcasterLifeCyclePolicy lifeCyclePolicy;\\nURI uri;\\nAtmosphereConfig config;\\nObject[] awaitBarrier;\\nAtomicBoolean outOfOrderBroadcastSupported;\\nint writeTimeoutInSecond;\\nint waitTime;\\nboolean backwardCompatible;\\nLifecycleHandler lifecycleHandler;\\nFuture currentLifecycleTask;\\nboolean cacheOnIOFlushException;\\nboolean sharedListeners;\\nboolean candidateForPoolable;\\nString usingTokenIdForAttribute;\\nBlockingQueue queue;\\nAtomicBoolean monitored;\\nString uuid;\\nAtmosphereResource r;\\nAtmosphereResourceEvent e;\\nAtomicBoolean completed;\\nAtomicBoolean executed;\\nThread ioThread;\\nAtmosphereResource resource;\\nObject msg;\\nBroadcasterFuture future;\\nObject originalMessage;\\nCacheMessage cache;\\nAtomicInteger count;\\nDefaultBroadcaster();\\ninitialize(String name,URI uri,AtmosphereConfig config);\\ninitialize(String name,AtmosphereConfig config);\\ndestroy();\\ngetAtmosphereResources();\\nsetScope(SCOPE scope);\\ngetScope();\\nsetID(String id);\\nrename(String id);\\ngetID();\\nresumeAll();\\nreleaseExternalResources();\\nsetBroadcasterLifeCyclePolicy(BroadcasterLifeCyclePolicy lifeCyclePolicy);\\ngetBroadcasterLifeCyclePolicy();\\naddBroadcasterLifeCyclePolicyListener(BroadcasterLifeCyclePolicyListener b);\\nremoveBroadcasterLifeCyclePolicyListener(BroadcasterLifeCyclePolicyListener b);\\nisDestroyed();\\nawaitAndBroadcast(Object t,long time,TimeUnit timeUnit);\\naddBroadcasterListener(BroadcasterListener b);\\nremoveBroadcasterListener(BroadcasterListener b);\\ngetBroadcastHandler();\\nrun();\\ngetAsyncWriteHandler(WriteQueue writeQueue);\\nstart();\\nspawnReactor();\\nkillReactiveThreads();\\nreactiveThreadsCount();\\npush(Deliver deliver);\\ndeliverPush(Deliver deliver,boolean rec);\\nendBroadcast(Deliver deliver,AtmosphereResource r,CacheMessage cacheMsg,boolean deliverMessage);\\nqueueWriteIO(AtmosphereResource r,Deliver deliver,AtomicInteger count);\\nexecuteBlockingWrite(AtmosphereResource r,Deliver deliver,AtomicInteger count);\\nWriteQueue(String uuid);\\nasString();\\nperRequestFilter(AtmosphereResource r,Deliver msg);\\ncallable(Object msg);\\nexecuteAsyncWrite(AsyncWriteToken token);\\ncacheMessageOnIOException(Throwable cause);\\ncheckCachedAndPush(AtmosphereResource r,AtmosphereResourceEvent e);\\nretrieveTrackedBroadcast(AtmosphereResource r,AtmosphereResourceEvent e);\\ninvokeOnStateChange(AtmosphereResource r,AtmosphereResourceEvent e);\\nprepareInvokeOnStateChange(AtmosphereResource r,AtmosphereResourceEvent e);\\nWriteOperation(AtmosphereResource r,AtmosphereResourceEvent e,Thread ioThread);\\ncall();\\ninterrupt();\\nonException(Throwable t,AtmosphereResource ar);\\nonException(Throwable t,AtmosphereResource ar,boolean notifyAndCache);\\ncacheLostMessage(AtmosphereResource r,boolean force);\\ncacheLostMessage(AtmosphereResource r,AsyncWriteToken token);\\ncacheLostMessage(AtmosphereResource r,AsyncWriteToken token,boolean force);\\nsetSuspendPolicy(long maxSuspendResource,POLICY policy);\\nbroadcast(Object msg);\\nfutureDone(Object msg);\\ndispatchMessages(Deliver e);\\nfilter(Object msg);\\nbroadcast(Object msg,AtmosphereResource r);\\nbroadcastOnResume(Object msg);\\nbroadcastOnResume(AtmosphereResource r);\\nbroadcast(Object msg,Set subset);\\naddAtmosphereResource(AtmosphereResource r);\\ncacheAndSuspend(AtmosphereResource r);\\nnotifyAndAdd(AtmosphereResource r);\\nisAtmosphereResourceValid(AtmosphereResource r);\\nentryDone(BroadcasterFuture f);\\nnotifyBroadcastListener();\\nnotifyOnAddAtmosphereResourceListener(AtmosphereResource r);\\nnotifyOnRemoveAtmosphereResourceListener(AtmosphereResource r);\\nnotifyOnMessage(Deliver deliver);\\nremoveAtmosphereResource(AtmosphereResource r);\\nremoveAtmosphereResource(AtmosphereResource r,boolean executeDone);\\nsetBroadcasterConfig(BroadcasterConfig bc);\\ngetBroadcasterConfig();\\ndelayBroadcast(Object o);\\ndelayBroadcast(Object o,long delay,TimeUnit t);\\nscheduleFixedBroadcast(Object o,long period,TimeUnit t);\\nscheduleFixedBroadcast(Object o,long waitFor,long period,TimeUnit t);\\ntoString();\\nAsyncWriteToken(AtmosphereResource resource,Object msg,BroadcasterFuture future,Object originalMessage,AtomicInteger count);\\nAsyncWriteToken(AtmosphereResource resource,Object msg,BroadcasterFuture future,Object originalMessage,CacheMessage cache,AtomicInteger count);\\nlastBroadcasted();\\ntranslateTimeUnit(long period,TimeUnit tu);\\nnotifyOnPreDestroy();\\nbroadcasterListeners();\\nlifeCyclePolicy();\\nlifeCycleListeners();\\nmessages();\\nwriteQueues();\\npolicy();\\noutOfOrderBroadcastSupported();\\nrecentActivity();\\nlifecycleHandler();\\nlifecycleHandler(LifecycleHandler lifecycleHandler);\\ncurrentLifecycleTask();\\ncurrentLifecycleTask(Future currentLifecycleTask);\\ncreateBroadcasterConfig(AtmosphereConfig config);\\n\", \"repo_level\" : \"public interface BroadcastMessage {public String id();\\npublic Object message();\\n }\\npublic interface CacheMessage {public Object getMessage();\\npublic String getId();\\npublic String toString();\\npublic long getCreateTime();\\npublic String uuid();\\n }\\npublic interface LifecycleHandler {public LifecycleHandler on(DefaultBroadcaster broadcaster);\\npublic void run();\\n void destroy(boolean resume);\\npublic LifecycleHandler offIfEmpty(DefaultBroadcaster broadcaster);\\npublic LifecycleHandler off(DefaultBroadcaster broadcaster);\\nprotected void notifyIdleListener(DefaultBroadcaster broadcaster);\\nprotected void notifyDestroyListener(DefaultBroadcaster broadcaster);\\nprotected void notifyEmptyListener(DefaultBroadcaster broadcaster);\\n }\\npublic interface PoolableBroadcasterFactory {protected void configure(String broadcasterLifeCyclePolicy);\\npublic Broadcaster get();\\npublic boolean add(Broadcaster b,Object id);\\npublic boolean remove(Broadcaster b,Object id);\\npublic T lookup(Class c,Object id,boolean createIfNull,boolean unique);\\npublic void removeAllAtmosphereResource(AtmosphereResource r);\\npublic boolean remove(Object id);\\npublic Collection lookupAll();\\npublic Broadcaster createBroadcaster();\\npublic PoolableBroadcasterFactory trackPooledBroadcaster(boolean trackPooledBroadcaster);\\npublic boolean trackPooledBroadcaster();\\npublic PoolableProvider poolableProvider();\\npublic PoolableBroadcasterFactory poolableProvider(PoolableProvider poolableProvider);\\n }\\npublic interface Utils {static boolean webSocketEnabled(HttpServletRequest request);\\nstatic boolean rawWebSocket(HttpServletRequest request);\\nstatic boolean firefoxWebSocketEnabled(HttpServletRequest request);\\nstatic boolean twoConnectionsTransport(TRANSPORT t);\\nstatic boolean webSocketQueryStringPresentOrNull(HttpServletRequest request);\\nstatic boolean resumableTransport(TRANSPORT t);\\nstatic boolean pollableTransport(TRANSPORT t);\\nstatic boolean pushMessage(TRANSPORT t);\\nstatic boolean atmosphereProtocol(AtmosphereRequest r);\\nstatic boolean webSocketMessage(AtmosphereResource r);\\nstatic boolean properProtocol(HttpServletRequest request);\\nstatic AtmosphereResource websocketResource(AtmosphereResource r);\\nstatic boolean closeMessage(HttpServletRequest request);\\nstatic Object invoke(Object proxiedInstance,Method m,Object o);\\nstatic void inject(AtmosphereResource r);\\nstatic void inject(Object object,Class clazz,AtmosphereResource r);\\nstatic void inject(Object object,Class clazz,AtmosphereConfig config);\\nstatic Set getInheritedPrivateFields(Class type);\\nstatic Set getInheritedPrivateMethod(Class type);\\nstatic boolean requestScopedInjection(AtmosphereConfig config,AtmosphereHandler h);\\nstatic boolean requestScopedInjection(AtmosphereConfig config,Object o);\\nstatic void destroyMeteor(AtmosphereRequest req);\\nstatic String pathInfo(AtmosphereRequest request);\\nstatic boolean isRunningTest();\\nstatic boolean isUnderJDK11AndUp();\\n }\\n\" }", "class_name": "DefaultBroadcaster", "code": "protected Object filter(Object msg){\n BroadcastAction a=bc.filter(msg);\n if (a.action() == BroadcastAction.ACTION.ABORT || msg == null) return null;\n else return a.message();\n}\n", "docstring": "/** \n * Invoke the {@link BroadcastFilter}\n * @param msg\n * @return\n */\n", "end_lineno": "1244", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n\npackage org.atmosphere.cpr;\n\nimport org.atmosphere.cache.BroadcastMessage;\nimport org.atmosphere.cache.CacheMessage;\nimport org.atmosphere.cpr.BroadcastFilter.BroadcastAction;\nimport org.atmosphere.lifecycle.LifecycleHandler;\nimport org.atmosphere.pool.PoolableBroadcasterFactory;\nimport org.atmosphere.util.Utils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.concurrent.RejectedExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicLong;\n\nimport static org.atmosphere.cpr.ApplicationConfig.BACKWARD_COMPATIBLE_WEBSOCKET_BEHAVIOR;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CACHE_STRATEGY;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_SHAREABLE_LISTENERS;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_WAIT_TIME;\nimport static org.atmosphere.cpr.ApplicationConfig.CACHE_MESSAGE_ON_IO_FLUSH_EXCEPTION;\nimport static org.atmosphere.cpr.ApplicationConfig.MAX_INACTIVE;\nimport static org.atmosphere.cpr.ApplicationConfig.OUT_OF_ORDER_BROADCAST;\nimport static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID;\nimport static org.atmosphere.cpr.ApplicationConfig.WRITE_TIMEOUT;\nimport static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.NEVER;\nimport static org.atmosphere.cpr.FrameworkConfig.INJECTED_ATMOSPHERE_RESOURCE;\n\n/**\n * The default {@link Broadcaster} implementation.\n *

\n * Broadcast messages to suspended responses using the caller's Thread.\n * This basic {@link Broadcaster} use an {@link java.util.concurrent.ExecutorService}\n * to broadcast messages, hence the broadcast operation is asynchronous. Make sure\n * you block on {@link #broadcast(Object)}.get()} if you need synchronous operations.\n *\n * @author Jeanfrancois Arcand\n */\npublic class DefaultBroadcaster implements Broadcaster {\n public static final int POLLING_DEFAULT = 100;\n public static final String CACHED = DefaultBroadcaster.class.getName() + \".messagesCached\";\n\n private static final Logger logger = LoggerFactory.getLogger(DefaultBroadcaster.class);\n private static final String DESTROYED = \"This Broadcaster has been destroyed and cannot be used {} by invoking {}\";\n private static final List EMPTY_LISTENERS = new ArrayList<>();\n\n protected final ConcurrentLinkedQueue resources =\n new ConcurrentLinkedQueue<>();\n protected BroadcasterConfig bc;\n protected final BlockingQueue messages = new LinkedBlockingQueue<>();\n protected Collection broadcasterListeners;\n\n protected final AtomicBoolean started = new AtomicBoolean(false);\n protected final AtomicBoolean initialized = new AtomicBoolean(false);\n protected final AtomicBoolean destroyed = new AtomicBoolean(false);\n\n protected SCOPE scope = SCOPE.APPLICATION;\n protected String name = DefaultBroadcaster.class.getSimpleName();\n protected final ConcurrentLinkedQueue delayedBroadcast = new ConcurrentLinkedQueue<>();\n protected final ConcurrentLinkedQueue broadcastOnResume = new ConcurrentLinkedQueue<>();\n protected final ConcurrentLinkedQueue lifeCycleListeners = new ConcurrentLinkedQueue<>();\n protected final ConcurrentHashMap writeQueues = new ConcurrentHashMap<>();\n protected final WriteQueue uniqueWriteQueue = new WriteQueue(\"-1\");\n protected final AtomicInteger dispatchThread = new AtomicInteger();\n\n protected Future[] notifierFuture;\n protected Future[] asyncWriteFuture;\n\n private POLICY policy = POLICY.FIFO;\n private final AtomicLong maxSuspendResource = new AtomicLong(-1);\n private final AtomicBoolean requestScoped = new AtomicBoolean(false);\n private final AtomicBoolean recentActivity = new AtomicBoolean(false);\n private BroadcasterLifeCyclePolicy lifeCyclePolicy = new BroadcasterLifeCyclePolicy.Builder()\n .policy(NEVER).build();\n protected URI uri;\n protected AtmosphereConfig config;\n private final Object[] awaitBarrier = new Object[0];\n private final AtomicBoolean outOfOrderBroadcastSupported = new AtomicBoolean(false);\n protected int writeTimeoutInSecond = -1;\n protected int waitTime = POLLING_DEFAULT;\n private boolean backwardCompatible;\n private LifecycleHandler lifecycleHandler;\n private Future currentLifecycleTask;\n private boolean cacheOnIOFlushException = true;\n protected boolean sharedListeners;\n protected boolean candidateForPoolable;\n protected final String usingTokenIdForAttribute = UUID.randomUUID().toString();\n\n public DefaultBroadcaster() {\n }\n\n public Broadcaster initialize(String name, URI uri, AtmosphereConfig config) {\n this.name = name;\n this.uri = uri;\n this.config = config;\n\n bc = createBroadcasterConfig(config);\n String s = config.getInitParameter(BROADCASTER_CACHE_STRATEGY);\n if (s != null) {\n logger.warn(\"{} is no longer supported. Use BroadcastInterceptor instead. By default the original message will be cached.\", BROADCASTER_CACHE_STRATEGY);\n }\n s = config.getInitParameter(OUT_OF_ORDER_BROADCAST);\n if (s != null) {\n outOfOrderBroadcastSupported.set(Boolean.parseBoolean(s));\n }\n\n s = config.getInitParameter(BROADCASTER_WAIT_TIME);\n if (s != null) {\n waitTime = Integer.parseInt(s);\n }\n\n s = config.getInitParameter(WRITE_TIMEOUT);\n if (s != null) {\n writeTimeoutInSecond = Integer.parseInt(s);\n }\n if (outOfOrderBroadcastSupported.get()) {\n logger.trace(\"{} supports Out Of Order Broadcast: {}\", name, outOfOrderBroadcastSupported.get());\n }\n initialized.set(true);\n backwardCompatible = Boolean.parseBoolean(config.getInitParameter(BACKWARD_COMPATIBLE_WEBSOCKET_BEHAVIOR));\n cacheOnIOFlushException = config.getInitParameter(CACHE_MESSAGE_ON_IO_FLUSH_EXCEPTION, true);\n sharedListeners = config.getInitParameter(BROADCASTER_SHAREABLE_LISTENERS, false);\n\n if (sharedListeners) {\n broadcasterListeners = config.getBroadcasterFactory().broadcasterListeners();\n } else {\n broadcasterListeners = new ConcurrentLinkedQueue<>();\n }\n\n candidateForPoolable = PoolableBroadcasterFactory.class.isAssignableFrom(config.getBroadcasterFactory().getClass());\n\n return this;\n }\n\n public Broadcaster initialize(String name, AtmosphereConfig config) {\n return initialize(name, URI.create(\"http://localhost\"), config);\n }\n\n /**\n * Create {@link BroadcasterConfig}.\n *\n * @param config the {@link AtmosphereConfig}\n * @return an instance of {@link BroadcasterConfig}\n */\n protected BroadcasterConfig createBroadcasterConfig(AtmosphereConfig config) {\n return new BroadcasterConfig(config.framework().broadcasterFilters, config, getID()).init();\n }\n\n @Override\n public synchronized void destroy() {\n try {\n logger.trace(\"Broadcaster {} will be pooled: {}\", getID(), candidateForPoolable);\n if (!candidateForPoolable) {\n if (notifyOnPreDestroy()) return;\n\n logger.trace(\"Broadcaster {} is being destroyed and cannot be re-used. Policy was {}\", getID(), policy);\n logger.trace(\"Broadcaster {} is being destroyed and cannot be re-used. Resources are {}\", getID(), resources);\n \n if (destroyed.getAndSet(true)) return;\n\n started.set(false);\n\n releaseExternalResources();\n killReactiveThreads();\n\n if (bc != null) {\n bc.destroy();\n }\n lifeCycleListeners.clear();\n delayedBroadcast.clear();\n if (!sharedListeners) {\n broadcasterListeners.clear();\n }\n }\n\n resources.clear();\n broadcastOnResume.clear();\n messages.clear();\n writeQueues.clear();\n\n if (config.getBroadcasterFactory() != null) {\n config.getBroadcasterFactory().remove(this, this.getID());\n }\n } catch (Throwable t) {\n logger.error(\"Unexpected exception during Broadcaster destroy {}\", getID(), t);\n }\n }\n\n @Override\n public Collection getAtmosphereResources() {\n return Collections.unmodifiableCollection(resources);\n }\n\n @Override\n public void setScope(SCOPE scope) {\n if (destroyed.get()) {\n logger.debug(DESTROYED, getID(), \"setScope\");\n return;\n }\n\n this.scope = scope;\n if (scope != SCOPE.REQUEST) {\n return;\n }\n\n logger.debug(\"Changing broadcaster scope for {}. This broadcaster will be destroyed.\", getID());\n synchronized (resources) {\n try {\n // Next, we need to create a new broadcaster per resource.\n for (AtmosphereResource resource : resources) {\n Broadcaster b = config.getBroadcasterFactory()\n .get(getClass(), getClass().getSimpleName() + \"/\" + config.uuidProvider().generateUuid());\n\n /**\n * REQUEST_SCOPE means one BroadcasterCache per Broadcaster,\n */\n if (DefaultBroadcaster.class.isAssignableFrom(this.getClass())) {\n BroadcasterCache cache = config.framework().newClassInstance(BroadcasterCache.class, bc.getBroadcasterCache().getClass());\n cache.configure(config);\n b.getBroadcasterConfig().setBroadcasterCache(cache);\n }\n\n resource.setBroadcaster(b);\n b.setScope(SCOPE.REQUEST);\n if (resource.getAtmosphereResourceEvent().isSuspended()) {\n b.addAtmosphereResource(resource);\n }\n logger.debug(\"Resource {} not using broadcaster {}\", resource, b.getID());\n }\n\n // Do not destroy because this is a new Broadcaster\n if (resources.isEmpty()) {\n return;\n }\n\n destroy();\n } catch (Exception e) {\n logger.error(\"Failed to set request scope for current resources\", e);\n }\n }\n }\n\n @Override\n public SCOPE getScope() {\n return scope;\n }\n\n @Override\n public synchronized void setID(String id) {\n if (id == null) {\n id = getClass().getSimpleName() + \"/\" + config.uuidProvider().generateUuid();\n }\n\n if (config.getBroadcasterFactory() == null)\n return; // we are shutdown or destroyed, but someone still reference\n\n Broadcaster b = config.getBroadcasterFactory().lookup(this.getClass(), id);\n if (b != null && b.getScope() == SCOPE.REQUEST) {\n throw new IllegalStateException(\"Broadcaster ID already assigned to SCOPE.REQUEST. Cannot change the id\");\n } else if (b != null) {\n return;\n }\n\n config.getBroadcasterFactory().remove(this, name);\n this.name = id;\n config.getBroadcasterFactory().add(this, name);\n\n bc.broadcasterID(name);\n }\n\n /**\n * Rename this Broadcaster without invoking it's associated {@link org.atmosphere.cpr.BroadcasterFactory}. This\n * method must be carefully used as it could easily create memory leak as the Broadcaster won't be removed\n * from its {@link org.atmosphere.cpr.BroadcasterFactory}.\n *\n * @param id the new name\n * @return this;\n */\n public Broadcaster rename(String id) {\n this.name = id;\n return this;\n }\n\n @Override\n public String getID() {\n return name;\n }\n\n @Override\n public void resumeAll() {\n synchronized (resources) {\n for (AtmosphereResource r : resources) {\n try {\n r.resume();\n } catch (Throwable t) {\n logger.trace(\"resumeAll\", t);\n } finally {\n removeAtmosphereResource(r);\n }\n }\n }\n }\n\n @Override\n public void releaseExternalResources() {\n }\n\n @Override\n public void setBroadcasterLifeCyclePolicy(final BroadcasterLifeCyclePolicy lifeCyclePolicy) {\n this.lifeCyclePolicy = lifeCyclePolicy;\n if (lifecycleHandler != null) lifecycleHandler.on(this);\n }\n\n @Override\n public BroadcasterLifeCyclePolicy getBroadcasterLifeCyclePolicy() {\n return lifeCyclePolicy;\n }\n\n @Override\n public void addBroadcasterLifeCyclePolicyListener(BroadcasterLifeCyclePolicyListener b) {\n lifeCycleListeners.add(b);\n }\n\n @Override\n public void removeBroadcasterLifeCyclePolicyListener(BroadcasterLifeCyclePolicyListener b) {\n lifeCycleListeners.remove(b);\n }\n\n @Override\n public boolean isDestroyed() {\n return destroyed.get();\n }\n\n @Override\n public Future awaitAndBroadcast(Object t, long time, TimeUnit timeUnit) {\n if (resources.isEmpty()) {\n synchronized (awaitBarrier) {\n try {\n logger.trace(\"Awaiting for AtmosphereResource for {} {}\", time, timeUnit);\n awaitBarrier.wait(translateTimeUnit(time, timeUnit));\n } catch (Throwable e) {\n logger.warn(\"awaitAndBroadcast\", e);\n return null;\n }\n }\n }\n return broadcast(t);\n }\n\n @Override\n public Broadcaster addBroadcasterListener(BroadcasterListener b) {\n if (!sharedListeners && !broadcasterListeners.contains(b)) {\n broadcasterListeners.add(b);\n }\n return this;\n }\n\n @Override\n public Broadcaster removeBroadcasterListener(BroadcasterListener b) {\n if (!sharedListeners) broadcasterListeners.remove(b);\n return this;\n }\n\n protected Runnable getBroadcastHandler() {\n return new Runnable() {\n public void run() {\n while (!isDestroyed()) {\n Deliver msg = null;\n try {\n msg = messages.poll(waitTime, TimeUnit.MILLISECONDS);\n if (msg == null) {\n dispatchThread.decrementAndGet();\n return;\n }\n } catch (InterruptedException ex) {\n logger.trace(\"{} got interrupted for Broadcaster {}\", Thread.currentThread().getName(), getID());\n logger.trace(\"\", ex);\n dispatchThread.decrementAndGet();\n return;\n } finally {\n if (outOfOrderBroadcastSupported.get()) {\n bc.getExecutorService().submit(this);\n }\n }\n\n try {\n logger.trace(\"{} is about to broadcast {}\", getID(), msg);\n push(msg);\n } catch (Throwable ex) {\n if (!started.get() || destroyed.get()) {\n logger.trace(\"Failed to submit broadcast handler runnable on shutdown for Broadcaster {}\", getID(), ex);\n dispatchThread.decrementAndGet();\n return;\n } else {\n logger.warn(\"This message {} will be lost\", msg);\n logger.warn(\"Failed to submit broadcast handler runnable to for Broadcaster\" + getID(), ex);\n }\n } finally {\n if (outOfOrderBroadcastSupported.get()) {\n dispatchThread.decrementAndGet();\n return;\n }\n }\n }\n }\n };\n }\n\n protected Runnable getAsyncWriteHandler(final WriteQueue writeQueue) {\n return new Runnable() {\n public void run() {\n while (!isDestroyed()) {\n AsyncWriteToken token;\n try {\n token = writeQueue.queue.poll(waitTime, TimeUnit.MILLISECONDS);\n if (token == null && !outOfOrderBroadcastSupported.get()) {\n synchronized (writeQueue) {\n if (writeQueue.queue.isEmpty()) {\n writeQueue.monitored.set(false);\n writeQueues.remove(writeQueue.uuid);\n return;\n }\n }\n } else if (token == null) {\n return;\n }\n } catch (InterruptedException ex) {\n logger.trace(\"{} got interrupted for Broadcaster {}\", Thread.currentThread().getName(), getID());\n logger.trace(\"\", ex);\n return;\n } finally {\n if (!bc.getAsyncWriteService().isShutdown() && outOfOrderBroadcastSupported.get()) {\n bc.getAsyncWriteService().submit(this);\n }\n }\n\n // Shield us from https://github.com/Atmosphere/atmosphere/issues/1187\n if (token != null) {\n synchronized (token.resource) {\n try {\n logger.trace(\"About to write to {}\", token.resource);\n executeAsyncWrite(token);\n } catch (Throwable ex) {\n if (!started.get() || destroyed.get()) {\n logger.trace(\"Failed to execute a write operation. Broadcaster is destroyed or not yet started for Broadcaster {}\", getID(), ex);\n return;\n } else {\n try {\n logger.warn(\"This message {} will be lost for AtmosphereResource {}, adding it to the BroadcasterCache\",\n token.originalMessage, token.resource != null ? token.resource.uuid() : \"null\");\n cacheLostMessage(token.resource, token, true);\n } finally {\n removeAtmosphereResource(token.resource, false);\n logger.warn(\"Failed to execute a write operation for Broadcaster \" + getID(), ex);\n }\n }\n } finally {\n if (!bc.getAsyncWriteService().isShutdown() && outOfOrderBroadcastSupported.get()) {\n return;\n }\n }\n }\n }\n }\n }\n };\n }\n\n protected void start() {\n if (!initialized.get()) {\n logger.warn(\"Broadcaster {} not initialized\", getID());\n }\n\n if (!started.getAndSet(true)) {\n bc.getBroadcasterCache().start();\n\n // Only start if we know a child haven't started them.\n if (notifierFuture == null && asyncWriteFuture == null) {\n spawnReactor();\n }\n }\n }\n\n protected void spawnReactor() {\n killReactiveThreads();\n\n int threads = outOfOrderBroadcastSupported.get() ? reactiveThreadsCount() : 1;\n notifierFuture = new Future[threads];\n\n if (outOfOrderBroadcastSupported.get()) {\n asyncWriteFuture = new Future[threads];\n for (int i = 0; i < threads; i++) {\n notifierFuture[i] = bc.getExecutorService().submit(getBroadcastHandler());\n asyncWriteFuture[i] = bc.getAsyncWriteService().submit(getAsyncWriteHandler(uniqueWriteQueue));\n }\n } else {\n notifierFuture[0] = bc.getExecutorService().submit(getBroadcastHandler());\n }\n dispatchThread.set(threads);\n }\n\n protected void killReactiveThreads() {\n if (notifierFuture != null) {\n for (Future f : notifierFuture) {\n if (f != null)\n f.cancel(false);\n }\n }\n\n if (asyncWriteFuture != null) {\n for (Future f : asyncWriteFuture) {\n if (f != null)\n f.cancel(false);\n }\n }\n }\n\n /**\n * Return the default number of reactive threads that will be waiting for work when a broadcast operation\n * is executed.\n *\n * @return the default number of reactive threads\n */\n protected int reactiveThreadsCount() {\n return Runtime.getRuntime().availableProcessors() * 2;\n }\n\n protected void push(Deliver deliver) {\n if (destroyed.get()) {\n return;\n }\n\n deliverPush(deliver, true);\n }\n\n protected void deliverPush(Deliver deliver, boolean rec) {\n recentActivity.set(true);\n\n Object prevMessage = deliver.message;\n if (rec && !delayedBroadcast.isEmpty()) {\n Iterator i = delayedBroadcast.iterator();\n StringBuilder b = new StringBuilder();\n while (i.hasNext()) {\n Deliver e = i.next();\n e.future.cancel(true);\n try {\n // Append so we do a single flush\n if (e.message instanceof String\n && deliver.message instanceof String) {\n b.append(e.message);\n } else {\n deliverPush(e, false);\n }\n } finally {\n i.remove();\n }\n }\n\n if (b.length() > 0) {\n deliver.message = b.append(deliver.message).toString();\n }\n }\n\n Object finalMsg = callable(deliver.message);\n if (finalMsg == null) {\n logger.error(\"Callable exception. Please catch all exceptions from your callable. Message {} will be lost and all AtmosphereResource \" +\n \"associated with this Broadcaster resumed.\", deliver.message);\n entryDone(deliver.future);\n switch (deliver.type) {\n case ALL:\n synchronized (resources) {\n for (AtmosphereResource r : resources) {\n if (Utils.resumableTransport(r.transport()))\n try {\n r.resume();\n } catch (Throwable t) {\n logger.trace(\"resumeAll\", t);\n }\n }\n }\n break;\n case RESOURCE:\n deliver.resource.resume();\n break;\n case SET:\n for (AtmosphereResource r : deliver.resources) {\n r.resume();\n }\n break;\n }\n return;\n }\n\n Object prevM = deliver.originalMessage;\n deliver.originalMessage = (deliver.originalMessage != deliver.message ? callable(deliver.originalMessage) : finalMsg);\n\n if (deliver.originalMessage == null) {\n logger.trace(\"Broadcasted message was null {}\", prevM);\n entryDone(deliver.future);\n return;\n }\n\n deliver.message = finalMsg;\n\n Map cacheForSet = deliver.type == Deliver.TYPE.SET ? new HashMap<>() : null;\n // We cache first, and if the broadcast succeed, we will remove it.\n switch (deliver.type) {\n case ALL:\n deliver.cache = bc.getBroadcasterCache().addToCache(getID(), BroadcasterCache.NULL, new BroadcastMessage(deliver.originalMessage));\n break;\n case RESOURCE:\n deliver.cache = bc.getBroadcasterCache().addToCache(getID(), deliver.resource.uuid(), new BroadcastMessage(deliver.originalMessage));\n break;\n case SET:\n for (AtmosphereResource r : deliver.resources) {\n cacheForSet.put(r.uuid(), bc.getBroadcasterCache().addToCache(getID(), r.uuid(), new BroadcastMessage(deliver.originalMessage)));\n }\n break;\n }\n\n notifyOnMessage(deliver);\n if (resources.isEmpty()) {\n logger.trace(\"No resource available for {} and message {}\", getID(), finalMsg);\n entryDone(deliver.future);\n if (cacheForSet != null) {\n cacheForSet.clear();\n }\n return;\n }\n\n try {\n if (logger.isTraceEnabled()) {\n for (AtmosphereResource r : resources) {\n logger.trace(\"AtmosphereResource {} available for {}\", r.uuid(), deliver.message);\n }\n }\n\n boolean hasFilters = bc.hasPerRequestFilters();\n Object beforeProcessingMessage = deliver.message;\n switch (deliver.type) {\n case ALL:\n AtomicInteger count = new AtomicInteger(resources.size());\n\n for (AtmosphereResource r : resources) {\n deliver.message = beforeProcessingMessage;\n boolean deliverMessage = perRequestFilter(r, deliver);\n\n if (endBroadcast(deliver, r, deliver.cache, deliverMessage)) continue;\n\n if (deliver.writeLocally) {\n queueWriteIO(r, hasFilters ? new Deliver(r, deliver) : deliver, count);\n }\n }\n break;\n case RESOURCE:\n boolean deliverMessage = perRequestFilter(deliver.resource, deliver);\n\n if (endBroadcast(deliver, deliver.resource, deliver.cache, deliverMessage)) return;\n\n if (deliver.writeLocally) {\n queueWriteIO(deliver.resource, deliver, new AtomicInteger(1));\n }\n break;\n case SET:\n count = new AtomicInteger(deliver.resources.size());\n\n for (AtmosphereResource r : deliver.resources) {\n deliver.message = beforeProcessingMessage;\n deliverMessage = perRequestFilter(r, deliver);\n\n CacheMessage cacheMsg = cacheForSet.remove(r.uuid());\n\n if (endBroadcast(deliver, r, cacheMsg, deliverMessage)) continue;\n\n if (deliver.writeLocally) {\n queueWriteIO(r, new Deliver(r, deliver, cacheMsg), count);\n }\n }\n break;\n }\n\n deliver.message = prevMessage;\n } catch (InterruptedException ex) {\n logger.debug(ex.getMessage(), ex);\n if (cacheForSet != null) {\n cacheForSet.clear();\n }\n }\n }\n\n protected boolean endBroadcast(Deliver deliver, AtmosphereResource r, CacheMessage cacheMsg, boolean deliverMessage) {\n if (!deliverMessage || deliver.message == null) {\n logger.debug(\"Skipping broadcast delivery {} for resource {} \", deliver.message, deliver.resource != null ? deliver.resource.uuid() : \"null\");\n bc.getBroadcasterCache().clearCache(getID(), r.uuid(), cacheMsg);\n entryDone(deliver.future);\n\n return true;\n }\n return false;\n }\n\n protected void queueWriteIO(AtmosphereResource r, Deliver deliver, AtomicInteger count) throws InterruptedException {\n if (deliver.async) {\n // The onStateChange/onRequest may change the isResumed value, hence we need to make sure only one thread flip\n // the switch to garantee the Entry will be cached in the order it was broadcasted.\n // Without synchronizing we may end up with a out of order BroadcasterCache queue.\n if (!bc.getBroadcasterCache().getClass().equals(BroadcasterCache.DEFAULT.getClass())) {\n if (r.isResumed() || r.isCancelled()) {\n logger.trace(\"AtmosphereResource {} has been resumed or cancelled, unable to Broadcast message {}\", r.uuid(), deliver.message);\n\n /*\n * https://github.com/Atmosphere/atmosphere/issues/1886\n * Before caching the message, double check if the client has reconnected, and if true, send the\n * cached message.\n */\n AtmosphereResource r2 = config.resourcesFactory().find(r.uuid());\n logger.trace(\"Found an AtmosphereResource {} in state {}\", r2, r.isSuspended());\n if (r2 != null && r2.isSuspended() && r.hashCode() != r2.hashCode()) {\n // Prevent other Broadcast to happens\n removeAtmosphereResource(r2);\n checkCachedAndPush(r2, r2.getAtmosphereResourceEvent());\n }\n return;\n }\n }\n\n AsyncWriteToken w = new AsyncWriteToken(r, deliver.message, deliver.future, deliver.originalMessage, deliver.cache, count);\n if (!outOfOrderBroadcastSupported.get()) {\n WriteQueue writeQueue = writeQueues.get(r.uuid());\n if (writeQueue == null) {\n writeQueue = new WriteQueue(r.uuid());\n writeQueues.put(r.uuid(), writeQueue);\n }\n\n writeQueue.queue.put(w);\n synchronized (writeQueue) {\n if (!writeQueue.monitored.getAndSet(true)) {\n logger.trace(\"Broadcaster {} is about to queueWriteIO for AtmosphereResource {}\", name, r.uuid());\n bc.getAsyncWriteService().submit(getAsyncWriteHandler(writeQueue));\n }\n }\n } else {\n uniqueWriteQueue.queue.offer(w);\n }\n } else {\n executeBlockingWrite(r, deliver, count);\n }\n }\n\n protected void executeBlockingWrite(AtmosphereResource r, Deliver deliver, AtomicInteger count) throws InterruptedException {\n // We deliver using the calling thread.\n synchronized (r) {\n executeAsyncWrite(new AsyncWriteToken(r, deliver.message, deliver.future, deliver.originalMessage, deliver.cache, count));\n }\n }\n\n public final static class WriteQueue {\n final BlockingQueue queue = new LinkedBlockingQueue<>();\n final AtomicBoolean monitored = new AtomicBoolean();\n final String uuid;\n\n private WriteQueue(String uuid) {\n this.uuid = uuid;\n }\n\n public List asString() {\n List l = new ArrayList<>();\n for (AsyncWriteToken w : queue) {\n l.add(w.toString());\n }\n return l;\n }\n }\n\n protected boolean perRequestFilter(AtmosphereResource r, Deliver msg) {\n // A broadcaster#broadcast(msg,Set) may contains null value.\n if (r == null) {\n logger.trace(\"Null AtmosphereResource passed inside a Set\");\n return false;\n }\n\n if (bc.hasPerRequestFilters()) {\n BroadcastAction a = bc.filter(r, msg.message, msg.originalMessage);\n if (a.action() == BroadcastAction.ACTION.ABORT) {\n return false;\n }\n msg.message = a.message();\n }\n return true;\n }\n\n private Object callable(Object msg) {\n if (Callable.class.isAssignableFrom(msg.getClass())) {\n try {\n return ((Callable) msg).call();\n } catch (Exception e) {\n logger.warn(\"Callable exception\", e);\n return null;\n }\n }\n return msg;\n }\n\n protected void executeAsyncWrite(final AsyncWriteToken token) {\n boolean notifyListeners = true;\n boolean lostCandidate = false;\n\n if (token.resource == null) throw new NullPointerException();\n\n final AtmosphereResourceEventImpl event = (AtmosphereResourceEventImpl) token.resource.getAtmosphereResourceEvent();\n final AtmosphereResourceImpl r = (AtmosphereResourceImpl) token.resource;\n final boolean willBeResumed = Utils.resumableTransport(r.transport());\n List listeners = willBeResumed ? new ArrayList<>() : EMPTY_LISTENERS;\n final AtmosphereRequest request = r.getRequest(false);\n try {\n\n event.setMessage(token.msg);\n\n // Make sure we cache the message in case the AtmosphereResource has been cancelled, resumed or the client disconnected.\n if (!isAtmosphereResourceValid(r)) {\n logger.trace(\"AtmosphereResource {} state is invalid for Broadcaster {}. Message will be cached\", r.uuid(), name);\n removeAtmosphereResource(r, false);\n return;\n }\n\n bc.getBroadcasterCache().clearCache(getID(), r.uuid(), token.cache);\n try {\n request.setAttribute(getID(), token.future);\n request.setAttribute(MAX_INACTIVE, System.currentTimeMillis());\n request.setAttribute(usingTokenIdForAttribute, token);\n\n if (willBeResumed && !r.atmosphereResourceEventListener().isEmpty()) {\n listeners.addAll(r.atmosphereResourceEventListener());\n }\n prepareInvokeOnStateChange(r, event);\n } catch (Throwable t) {\n logger.debug(\"Invalid AtmosphereResource state {}. The connection has been remotely\" +\n \" closed and message {} will be added to the configured BroadcasterCache for later retrieval\", r.uuid(), event.getMessage());\n logger.trace(\"If you are using Tomcat 7.0.22 and lower, you're most probably hitting http://is.gd/NqicFT\");\n logger.trace(\"ApplicationConfig.CACHE_MESSAGE_ON_IO_FLUSH_EXCEPTION {}\", cacheOnIOFlushException, t);\n\n lostCandidate = cacheOnIOFlushException ? cacheOnIOFlushException : cacheMessageOnIOException(t);\n // The Request/Response associated with the AtmosphereResource has already been written and commited\n removeAtmosphereResource(r, false);\n r.removeFromAllBroadcasters();\n event.setCancelled(true);\n event.setThrowable(t);\n r.setIsInScope(false);\n return;\n }\n } finally {\n if (notifyListeners) {\n // Long Polling listener will be cleared when the resume() is called.\n if (willBeResumed) {\n event.setMessage(token.msg);\n for (AtmosphereResourceEventListener e : listeners) {\n e.onBroadcast(event);\n }\n // Listener wil be called later\n } else if (!event.isResumedOnTimeout()) {\n r.notifyListeners();\n }\n }\n\n if (token.lastBroadcasted()) {\n notifyBroadcastListener();\n }\n\n if (token.future != null) token.future.done();\n\n if (lostCandidate) {\n cacheLostMessage(r, token, true);\n }\n\n try {\n request.removeAttribute(getID());\n request.removeAttribute(usingTokenIdForAttribute);\n } catch (NullPointerException ex) {\n logger.trace(\"NPE after the message has been written for {}\", r.uuid());\n }\n token.destroy();\n }\n }\n\n protected boolean cacheMessageOnIOException(Throwable cause) {\n for (StackTraceElement element : cause.getStackTrace()) {\n if (element.getMethodName().equals(\"flush\") || element.getMethodName().equals(\"flushBuffer\")) {\n return false;\n }\n }\n return true;\n }\n\n protected boolean checkCachedAndPush(final AtmosphereResource r, final AtmosphereResourceEvent e) {\n boolean cache = retrieveTrackedBroadcast(r, e);\n\n if (!cache) return false;\n\n if (!((List) e.getMessage()).isEmpty()) {\n logger.debug(\"Sending cached message {} to {}\", e.getMessage(), r.uuid());\n\n List cacheMessages = (List) e.getMessage();\n BroadcasterFuture f = new BroadcasterFuture<>(e.getMessage(), 1);\n LinkedList filteredMessage = new LinkedList<>();\n LinkedList filteredMessageClone = null;\n Deliver deliver;\n Object newMessage;\n for (Object o : cacheMessages) {\n newMessage = filter(o);\n if (newMessage == null) {\n continue;\n }\n\n deliver = new Deliver(newMessage, r, f, o);\n // Can be aborted by a Filter\n if (!perRequestFilter(r, deliver)) {\n continue;\n }\n\n if (deliver.message != null) {\n filteredMessage.addLast(deliver.message);\n }\n }\n\n if (filteredMessage.isEmpty()) {\n return false;\n }\n e.setMessage(filteredMessage);\n\n final boolean willBeResumed = Utils.resumableTransport(r.transport());\n\n if (willBeResumed) {\n filteredMessageClone = (LinkedList) filteredMessage.clone();\n }\n\n List listeners = willBeResumed ? new ArrayList<>() : EMPTY_LISTENERS;\n AtmosphereResourceImpl rImpl = (AtmosphereResourceImpl) r;\n if (willBeResumed && !rImpl.atmosphereResourceEventListener().isEmpty()) {\n listeners.addAll(rImpl.atmosphereResourceEventListener());\n }\n\n // Must make sure execute only one thread\n synchronized (rImpl) {\n try {\n rImpl.getRequest().setAttribute(CACHED, \"true\");\n prepareInvokeOnStateChange(r, e);\n } catch (Throwable t) {\n // An exception occurred\n logger.error(\"Unable to write cached message {} for {}\", e.getMessage(), r.uuid());\n logger.error(\"\", t);\n for (Object o : cacheMessages) {\n bc.getBroadcasterCache().addToCache(getID(), r.uuid(), new BroadcastMessage(o));\n }\n return true;\n }\n\n // If long-polling or JSONP is used we need to set the messages for the event again, because onResume() have cleared them\n if (willBeResumed) {\n e.setMessage(filteredMessageClone);\n }\n\n for (AtmosphereResourceEventListener l : willBeResumed ? listeners : rImpl.atmosphereResourceEventListener()) {\n l.onBroadcast(e);\n }\n\n switch (r.transport()) {\n case UNDEFINED:\n case JSONP:\n case AJAX:\n case LONG_POLLING:\n return true;\n case SSE:\n break;\n default:\n try {\n r.getResponse().flushBuffer();\n } catch (IOException ioe) {\n logger.trace(\"\", ioe);\n ((AtmosphereResourceImpl) r)._destroy();\n }\n break;\n }\n }\n }\n return false;\n }\n\n protected boolean retrieveTrackedBroadcast(final AtmosphereResource r, final AtmosphereResourceEvent e) {\n logger.trace(\"Checking cached message for {}\", r.uuid());\n List missedMsg = bc.getBroadcasterCache().retrieveFromCache(getID(), r.uuid());\n if (missedMsg != null && !missedMsg.isEmpty()) {\n e.setMessage(missedMsg);\n return true;\n }\n return false;\n }\n\n protected void invokeOnStateChange(final AtmosphereResource r, final AtmosphereResourceEvent e) {\n try {\n logger.trace(\"{} is broadcasting to {}\", name, r.uuid());\n r.getAtmosphereHandler().onStateChange(e);\n } catch (Throwable t) {\n if (!InterruptedException.class.isAssignableFrom(t.getClass())) {\n onException(t, r);\n }\n }\n }\n\n protected void prepareInvokeOnStateChange(final AtmosphereResource r, final AtmosphereResourceEvent e) {\n if (writeTimeoutInSecond != -1) {\n logger.trace(\"Registering Write timeout {} for {}\", writeTimeoutInSecond, r.uuid());\n WriteOperation w = new WriteOperation(r, e, Thread.currentThread());\n bc.getScheduledExecutorService().schedule(w, writeTimeoutInSecond, TimeUnit.MILLISECONDS);\n\n try {\n w.call();\n } catch (Exception ex) {\n logger.warn(\"\", ex);\n }\n } else {\n invokeOnStateChange(r, e);\n }\n }\n\n final class WriteOperation implements Callable {\n\n private final AtmosphereResource r;\n private final AtmosphereResourceEvent e;\n private final AtomicBoolean completed = new AtomicBoolean();\n private final AtomicBoolean executed = new AtomicBoolean();\n private final Thread ioThread;\n\n private WriteOperation(AtmosphereResource r, AtmosphereResourceEvent e, Thread ioThread) {\n this.r = r;\n this.e = e;\n this.ioThread = ioThread;\n }\n\n @Override\n public Object call() throws Exception {\n if (!completed.getAndSet(true)) {\n invokeOnStateChange(r, e);\n logger.trace(\"Cancelling Write timeout {} for {}\", writeTimeoutInSecond, r.uuid());\n executed.set(true);\n } else if (!executed.get()) {\n // https://github.com/Atmosphere/atmosphere/issues/902\n try {\n ioThread.interrupt();\n } catch (Throwable t) {\n // Swallow, this is already enough embarrassing\n logger.trace(\"I/O failure, unable to interrupt the thread\", t);\n }\n\n logger.trace(\"Honoring Write timeout {} for {}\", writeTimeoutInSecond, r.uuid());\n onException(new IOException(\"Unable to write after \" + writeTimeoutInSecond), r);\n ((AtmosphereResourceImpl) r).cancel();\n }\n return null;\n }\n\n public void interrupt() {\n }\n }\n\n public void onException(Throwable t, final AtmosphereResource ar) {\n onException(t, ar, true);\n }\n\n public void onException(Throwable t, final AtmosphereResource ar, boolean notifyAndCache) {\n final AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(ar);\n\n logger.trace(\"I/O Exception (or related) during execution of the write operation for \" +\n \"AtmosphereResource {} and Broadcaster {}. Message will be cached {}\",\n ar.uuid(), getID(), String.valueOf(notifyAndCache), t);\n\n // Remove to prevent other broadcast to re-use it.\n removeAtmosphereResource(r);\n\n if (notifyAndCache) {\n final AtmosphereResourceEventImpl event = r.getAtmosphereResourceEvent();\n event.setThrowable(t);\n\n r.notifyListeners(event);\n r.removeEventListeners();\n }\n\n if (notifyAndCache) {\n cacheLostMessage(r, (AsyncWriteToken) r.getRequest(false).getAttribute(usingTokenIdForAttribute), notifyAndCache);\n }\n\n /*\n * Make sure we resume the connection on every IOException.\n */\n if (bc != null && bc.getAsyncWriteService() != null) {\n bc.getAsyncWriteService().execute(() -> {\n try {\n logger.trace(\"Forcing connection close {}\", ar.uuid());\n r.resume();\n r.close();\n } catch (Throwable t1) {\n logger.trace(\"Was unable to resume a corrupted AtmosphereResource {}\", r);\n logger.trace(\"Cause\", t1);\n }\n });\n } else {\n r.resume();\n }\n }\n\n /**\n * Cache the message because an unexpected exception occurred.\n *\n * @param r {@link AtmosphereResource}\n */\n public void cacheLostMessage(AtmosphereResource r, boolean force) {\n AtmosphereRequest request = ((AtmosphereResourceImpl) r).getRequest(false);\n try {\n cacheLostMessage(r, (AsyncWriteToken) request.getAttribute(usingTokenIdForAttribute), force);\n } finally {\n request.removeAttribute(usingTokenIdForAttribute);\n }\n }\n\n /**\n * Cache the message because an unexpected exception occurred.\n *\n * @param r {@link AtmosphereResource}\n */\n public void cacheLostMessage(AtmosphereResource r, AsyncWriteToken token) {\n cacheLostMessage(r, token, false);\n }\n\n /**\n * Cache the message because an unexpected exception occurred.\n *\n * @param r {@link AtmosphereResource}\n */\n public void cacheLostMessage(AtmosphereResource r, AsyncWriteToken token, boolean force) {\n if (!force) {\n return;\n }\n\n try {\n if (token != null && token.originalMessage != null) {\n bc.getBroadcasterCache().addToCache(getID(), r != null ? r.uuid() : BroadcasterCache.NULL,\n new BroadcastMessage(String.valueOf(token.future.hashCode()), token.originalMessage));\n logger.trace(\"Lost message cached {}\", token.originalMessage);\n }\n } catch (Throwable t2) {\n logger.error(\"Unable to cache message {} for AtmosphereResource {}\", token.originalMessage, r != null ? r.uuid() : \"\");\n logger.error(\"Unable to cache message\", t2);\n }\n }\n\n @Override\n public void setSuspendPolicy(long maxSuspendResource, POLICY policy) {\n this.maxSuspendResource.set(maxSuspendResource);\n this.policy = policy;\n }\n\n @Override\n public Future broadcast(Object msg) {\n\n if (destroyed.get()) {\n logger.debug(DESTROYED, getID(), \"broadcast(T msg)\");\n return futureDone(msg);\n }\n\n start();\n Object newMsg = filter(msg);\n if (newMsg == null) {\n logger.debug(\"Broadcast Interrupted {}\", msg);\n return futureDone(msg);\n }\n\n int callee = resources.isEmpty() ? 1 : resources.size();\n\n BroadcasterFuture f = new BroadcasterFuture<>(newMsg, callee);\n dispatchMessages(new Deliver(newMsg, f, msg));\n return f;\n }\n\n protected BroadcasterFuture futureDone(Object msg) {\n notifyBroadcastListener();\n return (new BroadcasterFuture<>(msg)).done();\n }\n\n protected void dispatchMessages(Deliver e) {\n messages.offer(e);\n\n if (dispatchThread.get() == 0) {\n dispatchThread.incrementAndGet();\n getBroadcasterConfig().getExecutorService().submit(getBroadcastHandler());\n }\n }\n\n /**\n * Invoke the {@link BroadcastFilter}\n *\n * @param msg\n * @return\n */\n protected Object filter(Object msg) {\n BroadcastAction a = bc.filter(msg);\n if (a.action() == BroadcastAction.ACTION.ABORT || msg == null)\n return null;\n else\n return a.message();\n }\n\n @Override\n public Future broadcast(Object msg, AtmosphereResource r) {\n\n if (destroyed.get()) {\n logger.debug(DESTROYED, getID(), \"broadcast(T msg, AtmosphereResource r\");\n return futureDone(msg);\n }\n\n start();\n Object newMsg = filter(msg);\n if (newMsg == null) return futureDone(msg);\n\n BroadcasterFuture f = new BroadcasterFuture<>(newMsg, 1);\n dispatchMessages(new Deliver(newMsg, r, f, msg));\n return f;\n }\n\n @Override\n public Future broadcastOnResume(Object msg) {\n\n if (destroyed.get()) {\n logger.debug(DESTROYED, getID(), \"broadcastOnResume(T msg)\");\n return futureDone(msg);\n }\n\n start();\n Object newMsg = filter(msg);\n if (newMsg == null) return futureDone(msg);\n\n BroadcasterFuture f = new BroadcasterFuture<>(newMsg, resources.size());\n broadcastOnResume.offer(new Deliver(newMsg, f, msg));\n return f;\n }\n\n protected void broadcastOnResume(AtmosphereResource r) {\n for (Deliver e : broadcastOnResume) {\n e.async = false;\n push(new Deliver(r, e));\n }\n\n if (resources.isEmpty()) {\n broadcastOnResume.clear();\n }\n }\n\n @Override\n public Future broadcast(Object msg, Set subset) {\n\n if (destroyed.get()) {\n logger.debug(DESTROYED, getID(), \"broadcast(T msg, Set subset)\");\n return futureDone(msg);\n }\n\n start();\n Object newMsg = filter(msg);\n if (newMsg == null) return futureDone(msg);\n\n BroadcasterFuture f = new BroadcasterFuture<>(null, newMsg, subset.size());\n dispatchMessages(new Deliver(newMsg, subset, f, msg));\n return f;\n }\n\n @Override\n public Broadcaster addAtmosphereResource(AtmosphereResource r) {\n try {\n if (destroyed.get()) {\n logger.debug(DESTROYED, getID(), \"addAtmosphereResource(AtmosphereResource r\");\n return this;\n }\n\n start();\n if (scope == SCOPE.REQUEST && requestScoped.getAndSet(true)) {\n throw new IllegalStateException(\"Broadcaster \" + this\n + \" cannot be used as its scope is set to REQUEST\");\n }\n\n // To avoid excessive synchronization, we allow resources.size() to get larger that maxSuspendResource\n if (maxSuspendResource.get() > 0 && resources.size() >= maxSuspendResource.get()) {\n // Resume the first in.\n if (policy == POLICY.FIFO) {\n // TODO handle null return from poll()\n AtmosphereResource resource = resources.poll();\n try {\n logger.warn(\"Too many resource. Forcing resume of {} \", resource.uuid());\n resource.resume();\n } catch (Throwable t) {\n logger.warn(\"failed to resume resource {} \", resource, t);\n }\n } else if (policy == POLICY.REJECT) {\n throw new RejectedExecutionException(String.format(\"Maximum suspended AtmosphereResources %s\", maxSuspendResource));\n }\n }\n\n if (!r.isSuspended()) {\n logger.warn(\"AtmosphereResource {} is not suspended. If cached messages exists, this may cause unexpected situation. Suspend first\", r.uuid());\n }\n\n if (!backwardCompatible && resources.contains(r)) {\n boolean duplicate = r.transport() != AtmosphereResource.TRANSPORT.WEBSOCKET\n || ((AtmosphereResourceImpl) r).getRequest(false).getAttribute(INJECTED_ATMOSPHERE_RESOURCE) != null;\n\n if (duplicate) {\n AtmosphereResourceImpl dup = (AtmosphereResourceImpl) config.resourcesFactory().find(r.uuid());\n if (dup != null && dup != r ) {\n if ( ! dup.isPendingClose() ) {\n logger.debug(\"Duplicate resource {}. Could be caused by a dead connection not detected by your server. \" +\n \"Replacing the old one with the fresh one {}\", r.uuid(), r.transport());\n } else {\n logger.debug(\"Not yet closed resource still active {}\", r.uuid());\n }\n dup.dirtyClose();\n } else {\n logger.debug(\"Duplicate resource {}\", r.uuid());\n return this;\n }\n } else {\n logger.debug(\"Duplicate resource {}\", r.uuid());\n return this;\n }\n }\n\n // Only synchronize if we have a valid BroadcasterCache\n if (!bc.getBroadcasterCache().getClass().equals(BroadcasterCache.DEFAULT.getClass())) {\n // In case we are adding messages to the cache, we need to make sure the operation is done before.\n synchronized (resources) {\n cacheAndSuspend(r);\n }\n } else {\n cacheAndSuspend(r);\n }\n } finally {\n // OK reset\n if (!resources.isEmpty()) {\n synchronized (awaitBarrier) {\n awaitBarrier.notifyAll();\n }\n }\n }\n return this;\n }\n\n /**\n * Look in the cache to see if there are messages available, and take the appropriate actions.\n *\n * @param r AtmosphereResource\n */\n protected void cacheAndSuspend(AtmosphereResource r) {\n // In case the connection is closed, for whatever reason\n if (!isAtmosphereResourceValid(r)) {\n logger.debug(\"Unable to add AtmosphereResource {}\", r.uuid());\n return;\n }\n\n boolean wasResumed = checkCachedAndPush(r, r.getAtmosphereResourceEvent());\n if (!wasResumed && isAtmosphereResourceValid(r)) {\n logger.trace(\"Associating AtmosphereResource {} with Broadcaster {}\", r.uuid(), getID());\n\n String parentUUID = r.transport().equals(AtmosphereResource.TRANSPORT.WEBSOCKET) ?\n (String) ((AtmosphereResourceImpl) r).getRequest(false).getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID) :\n null;\n if (!backwardCompatible && parentUUID != null) {\n AtmosphereResource p = config.resourcesFactory().find(parentUUID);\n if (p != null && !resources.contains(p)) {\n notifyAndAdd(p);\n } else if (p == null) {\n notifyAndAdd(r);\n } else {\n logger.trace(\"AtmosphereResource {} was already mapped to {}\", r.uuid(), parentUUID);\n }\n } else {\n notifyAndAdd(r);\n }\n } else if (!wasResumed) {\n logger.debug(\"Unable to add AtmosphereResource {} to {}\", r.uuid(), name);\n }\n }\n\n protected void notifyAndAdd(AtmosphereResource r) {\n resources.add(r);\n r.addBroadcaster(this);\n notifyOnAddAtmosphereResourceListener(r);\n }\n\n private boolean isAtmosphereResourceValid(AtmosphereResource r) {\n return !r.isResumed()\n && !r.isCancelled()\n && ((AtmosphereResourceImpl) r).isInScope();\n }\n\n protected void entryDone(final BroadcasterFuture f) {\n notifyBroadcastListener();\n if (f != null) f.done();\n }\n\n protected void notifyBroadcastListener() {\n for (BroadcasterListener b : broadcasterListeners) {\n try {\n b.onComplete(this);\n } catch (Exception ex) {\n logger.warn(\"\", ex);\n }\n }\n }\n\n protected void notifyOnAddAtmosphereResourceListener(AtmosphereResource r) {\n for (BroadcasterListener b : broadcasterListeners) {\n try {\n b.onAddAtmosphereResource(this, r);\n } catch (Exception ex) {\n logger.warn(\"\", ex);\n }\n }\n }\n\n protected void notifyOnRemoveAtmosphereResourceListener(AtmosphereResource r) {\n for (BroadcasterListener b : broadcasterListeners) {\n try {\n b.onRemoveAtmosphereResource(this, r);\n } catch (Exception ex) {\n logger.warn(\"\", ex);\n }\n }\n }\n\n protected void notifyOnMessage(Deliver deliver) {\n for (BroadcasterListener b : broadcasterListeners) {\n try {\n b.onMessage(this, deliver);\n } catch (Exception ex) {\n logger.warn(\"\", ex);\n }\n }\n }\n\n @Override\n public Broadcaster removeAtmosphereResource(AtmosphereResource r) {\n return removeAtmosphereResource(r, true);\n }\n\n protected Broadcaster removeAtmosphereResource(AtmosphereResource r, boolean executeDone) {\n if (destroyed.get()) {\n logger.debug(DESTROYED, getID(), \"removeAtmosphereResource(AtmosphereResource r)\");\n return this;\n }\n\n boolean removed = resources.remove(r);\n if (removed) {\n if (r.isSuspended()) {\n logger.trace(\"Excluded from {} : {}\", getID(), r.uuid());\n bc.getBroadcasterCache().excludeFromCache(getID(), r);\n }\n notifyOnRemoveAtmosphereResourceListener(r);\n } else {\n logger.trace(\"Unable to remove {} from {}\", r.uuid(), getID());\n }\n r.removeBroadcaster(this);\n\n if (!removed) return this;\n\n logger.trace(\"Removing AtmosphereResource {} for Broadcaster {}\", r.uuid(), name);\n writeQueues.remove(r.uuid());\n\n // Here we need to make sure we aren't in the process of broadcasting and unlock the Future.\n if (executeDone) {\n AtmosphereResourceImpl aImpl = (AtmosphereResourceImpl) r;\n BroadcasterFuture f = (BroadcasterFuture) aImpl.getRequest(false).getAttribute(getID());\n if (f != null && !f.isDone() && !f.isCancelled()) {\n aImpl.getRequest(false).removeAttribute(getID());\n entryDone(f);\n }\n }\n\n return this;\n }\n\n @Override\n public void setBroadcasterConfig(BroadcasterConfig bc) {\n this.bc = bc;\n }\n\n @Override\n public BroadcasterConfig getBroadcasterConfig() {\n return bc;\n }\n\n @Override\n public Future delayBroadcast(Object o) {\n return delayBroadcast(o, 0, null);\n }\n\n @Override\n public Future delayBroadcast(final Object o, long delay, TimeUnit t) {\n\n if (destroyed.get()) {\n logger.debug(DESTROYED, getID(), \"delayBroadcast(final T o, long delay, TimeUnit t)\");\n return null;\n }\n\n start();\n final Object msg = filter(o);\n if (msg == null) return null;\n\n final BroadcasterFuture future = new BroadcasterFuture<>(msg);\n final Deliver e = new Deliver(msg, future, o);\n Future f;\n if (delay > 0) {\n f = bc.getScheduledExecutorService().schedule(() -> {\n delayedBroadcast.remove(e);\n if (Callable.class.isAssignableFrom(o.getClass())) {\n try {\n Object r = ((Callable) o).call();\n final Object msg1 = filter(r);\n if (msg1 != null) {\n Deliver deliver = new Deliver(msg1, future, r);\n push(deliver);\n }\n return msg1;\n } catch (Exception e1) {\n logger.error(\"delayBroadcast\", e);\n }\n }\n\n final Object msg1 = filter(o);\n final Deliver e12 = new Deliver(msg1, future, o);\n push(e12);\n return msg1;\n }, delay, t);\n\n e.future = new BroadcasterFuture<>(f, msg);\n }\n delayedBroadcast.offer(e);\n return future;\n }\n\n @Override\n public Future scheduleFixedBroadcast(final Object o, long period, TimeUnit t) {\n return scheduleFixedBroadcast(o, 0, period, t);\n }\n\n @Override\n public Future scheduleFixedBroadcast(final Object o, long waitFor, long period, TimeUnit t) {\n\n if (destroyed.get()) {\n logger.debug(DESTROYED, getID(), \"scheduleFixedBroadcast(final Object o, long waitFor, long period, TimeUnit t)\");\n return null;\n }\n\n start();\n if (period == 0 || t == null) {\n return null;\n }\n\n final Object msg = filter(o);\n if (msg == null) return null;\n\n final BroadcasterFuture f = new BroadcasterFuture(msg);\n\n return (Future) bc.getScheduledExecutorService().scheduleWithFixedDelay(() -> {\n if (Callable.class.isAssignableFrom(o.getClass())) {\n try {\n Object r = Callable.class.cast(o).call();\n final Object msg1 = filter(r);\n if (msg1 != null) {\n Deliver deliver = new Deliver(msg1, f, r);\n push(deliver);\n }\n return;\n } catch (Exception e) {\n logger.error(\"\", e);\n }\n }\n final Object msg1 = filter(o);\n final Deliver e = new Deliver(msg1, f, o);\n push(e);\n }, waitFor, period, t);\n }\n\n @Override\n public String toString() {\n return \"\\n\\tName: \" + name +\n \"\\n\\tAtmosphereResource: \" + resources.size() +\n \"\\n\\tBroadcasterCache \" + bc.getBroadcasterCache();\n }\n\n protected final static class AsyncWriteToken {\n\n AtmosphereResource resource;\n Object msg;\n BroadcasterFuture future;\n Object originalMessage;\n CacheMessage cache;\n AtomicInteger count;\n\n public AsyncWriteToken(AtmosphereResource resource, Object msg, BroadcasterFuture future, Object originalMessage, AtomicInteger count) {\n this.resource = resource;\n this.msg = msg;\n this.future = future;\n this.originalMessage = originalMessage;\n this.count = count;\n }\n\n public AsyncWriteToken(AtmosphereResource resource, Object msg, BroadcasterFuture future, Object originalMessage, CacheMessage cache, AtomicInteger count) {\n this.resource = resource;\n this.msg = msg;\n this.future = future;\n this.originalMessage = originalMessage;\n this.cache = cache;\n this.count = count;\n }\n\n public void destroy() {\n this.resource = null;\n this.msg = null;\n this.future = null;\n this.originalMessage = null;\n }\n\n public boolean lastBroadcasted() {\n return count.decrementAndGet() == 0;\n }\n\n @Override\n public String toString() {\n return \"AsyncWriteToken{\" +\n \"resource=\" + resource +\n \", msg=\" + msg +\n \", future=\" + future +\n '}';\n }\n }\n\n private long translateTimeUnit(long period, TimeUnit tu) {\n if (period == -1) return period;\n\n switch (tu) {\n case SECONDS:\n return TimeUnit.MILLISECONDS.convert(period, TimeUnit.SECONDS);\n case MINUTES:\n return TimeUnit.MILLISECONDS.convert(period, TimeUnit.MINUTES);\n case HOURS:\n return TimeUnit.MILLISECONDS.convert(period, TimeUnit.HOURS);\n case DAYS:\n return TimeUnit.MILLISECONDS.convert(period, TimeUnit.DAYS);\n case MILLISECONDS:\n return period;\n case MICROSECONDS:\n return TimeUnit.MILLISECONDS.convert(period, TimeUnit.MICROSECONDS);\n case NANOSECONDS:\n return TimeUnit.MILLISECONDS.convert(period, TimeUnit.NANOSECONDS);\n }\n return period;\n }\n\n boolean notifyOnPreDestroy() {\n for (BroadcasterListener b : broadcasterListeners) {\n try {\n b.onPreDestroy(this);\n } catch (RuntimeException ex) {\n if (BroadcasterListener.BroadcastListenerException.class.isAssignableFrom(ex.getClass())) {\n logger.trace(\"onPreDestroy\", ex);\n return true;\n }\n logger.warn(\"onPreDestroy\", ex);\n }\n }\n return false;\n }\n\n public Collection broadcasterListeners() {\n return broadcasterListeners;\n }\n\n public BroadcasterLifeCyclePolicy lifeCyclePolicy() {\n return lifeCyclePolicy;\n }\n\n public ConcurrentLinkedQueue lifeCycleListeners() {\n return lifeCycleListeners;\n }\n\n public BlockingQueue messages() {\n return messages;\n }\n\n public ConcurrentHashMap writeQueues() {\n return writeQueues;\n }\n\n public POLICY policy() {\n return policy;\n }\n\n public boolean outOfOrderBroadcastSupported() {\n return outOfOrderBroadcastSupported.get();\n }\n\n public AtomicBoolean recentActivity() {\n return recentActivity;\n }\n\n public LifecycleHandler lifecycleHandler() {\n return lifecycleHandler;\n }\n\n public DefaultBroadcaster lifecycleHandler(LifecycleHandler lifecycleHandler) {\n this.lifecycleHandler = lifecycleHandler;\n return this;\n }\n\n public Future currentLifecycleTask() {\n return currentLifecycleTask;\n }\n\n public DefaultBroadcaster currentLifecycleTask(Future currentLifecycleTask) {\n this.currentLifecycleTask = currentLifecycleTask;\n return this;\n }\n}\n", "file_name": "DefaultBroadcaster.java", "human_label": "Filter and return null for the null and abort message in BroadcastAction, return the action message otherwise. ", "level": "project_runnable", "lineno": "1232", "name": "filter", "oracle_context": "{ \"apis\" : \"[action, message]\", \"classes\" : \"[BroadcastAction, BroadcastAction.ACTION]\", \"vars\" : \"[ABORT, ACTION, bc]\" }", "package": "org.atmosphere.cpr", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767e01a6d9265ec018764", "all_context": "{ \"class_level\" : \"import com.google.gson.JsonObject;\\nimport io.grpc.stub.StreamObserver;\\nimport io.vavr.Tuple;\\nimport io.vavr.Tuple2;\\nimport org.apache.skywalking.apm.network.common.v3.Commands;\\nimport org.apache.skywalking.apm.network.common.v3.KeyStringValuePair;\\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFHostProcessDownstream;\\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFHostProcessMetadata;\\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFKubernetesProcessDownstream;\\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFKubernetesProcessMetadata;\\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFProcessDownstream;\\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFProcessEntityMetadata;\\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFProcessPingPkgList;\\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFProcessProperties;\\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFProcessReportList;\\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFProcessServiceGrpc;\\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFReportProcessDownstream;\\nimport org.apache.skywalking.oap.server.core.CoreModule;\\nimport org.apache.skywalking.oap.server.core.analysis.DownSampling;\\nimport org.apache.skywalking.oap.server.core.analysis.IDManager;\\nimport org.apache.skywalking.oap.server.core.analysis.Layer;\\nimport org.apache.skywalking.oap.server.core.analysis.TimeBucket;\\nimport org.apache.skywalking.oap.server.core.analysis.manual.process.ProcessDetectType;\\nimport org.apache.skywalking.oap.server.core.config.NamingControl;\\nimport org.apache.skywalking.oap.server.core.query.enumeration.ProfilingSupportStatus;\\nimport org.apache.skywalking.oap.server.core.source.Process;\\nimport org.apache.skywalking.oap.server.core.source.ServiceLabel;\\nimport org.apache.skywalking.oap.server.core.source.ServiceInstanceUpdate;\\nimport org.apache.skywalking.oap.server.core.source.ServiceMeta;\\nimport org.apache.skywalking.oap.server.core.source.SourceReceiver;\\nimport org.apache.skywalking.oap.server.library.module.ModuleManager;\\nimport org.apache.skywalking.oap.server.library.server.grpc.GRPCHandler;\\nimport org.apache.skywalking.oap.server.library.util.CollectionUtils;\\nimport java.util.ArrayList;\\nimport java.util.List;\\nimport java.util.Objects;\\nSourceReceiver sourceReceiver;\\nNamingControl namingControl;\\nEBPFProcessServiceHandler(ModuleManager moduleManager);\\nreportProcesses(EBPFProcessReportList request,StreamObserver responseObserver);\\nkeepAlive(EBPFProcessPingPkgList request,StreamObserver responseObserver);\\nprepareReportHostProcess(EBPFHostProcessMetadata hostProcess,String agentId);\\nprepareReportKubernetesProcess(EBPFKubernetesProcessMetadata kubernetesProcessMetadata,String agentId);\\ngetProfilingSupportStatus(List properties);\\nconvertProperties(List properties);\\nhandleServiceLabels(String serviceName,boolean isServiceNormal,List labels,long timeBucket);\\n\", \"repo_level\" : \"public interface CoreModule {public Class[] services();\\n }\\npublic interface IDManager {static String buildId(String name,boolean isNormal);\\nstatic ServiceIDDefinition analysisId(String id);\\nstatic String buildRelationId(ServiceRelationDefine define);\\nstatic ServiceRelationDefine analysisRelationId(String entityId);\\nstatic String buildId(String serviceId,String instanceName);\\nstatic ServiceInstanceID.InstanceIDDefinition analysisId(String id);\\nstatic String buildRelationId(ServiceInstanceRelationDefine define);\\nstatic ServiceInstanceID.ServiceInstanceRelationDefine analysisRelationId(String entityId);\\nstatic String buildId(String serviceId,String endpointName);\\nstatic EndpointIDDefinition analysisId(String id);\\nstatic String buildRelationId(EndpointRelationDefine define);\\nstatic EndpointRelationDefine analysisRelationId(String entityId);\\nstatic String buildId(String instanceId,String name);\\nstatic String buildRelationId(ProcessRelationDefine define);\\nstatic ProcessRelationDefine analysisRelationId(String entityId);\\nstatic String buildId(String name);\\nstatic String analysisId(String id);\\n }\\npublic interface TimeBucket {static long getRecordTimeBucket(long time);\\nstatic long getMinuteTimeBucket(long time);\\nstatic long getTimestamp(long timeBucket);\\nstatic boolean isSecondBucket(long timeBucket);\\nstatic boolean isMinuteBucket(long timeBucket);\\nstatic boolean isHourBucket(long timeBucket);\\nstatic boolean isDayBucket(long timeBucket);\\nstatic long getTimestamp(long timeBucket,DownSampling downsampling);\\nstatic long getTimeBucket(long timestamp,DownSampling downsampling);\\n }\\npublic interface NamingControl {public String formatServiceName(String serviceName);\\npublic String formatInstanceName(String instanceName);\\npublic String formatEndpointName(String serviceName,String endpointName);\\n }\\npublic interface Process {public int scope();\\npublic String getEntityId();\\npublic void prepare();\\n }\\npublic interface ServiceLabel {public int scope();\\npublic String getEntityId();\\npublic void prepare();\\n }\\npublic interface ServiceInstanceUpdate {public int scope();\\npublic String getEntityId();\\n }\\npublic interface ServiceMeta {public int scope();\\npublic String getEntityId();\\n }\\npublic interface SourceReceiver { void receive(ISource source);\\n DispatcherDetectorListener getDispatcherDetectorListener();\\n }\\npublic interface ModuleManager {public void init(ApplicationConfiguration applicationConfiguration);\\npublic boolean has(String moduleName);\\npublic ModuleProviderHolder find(String moduleName);\\n }\\npublic interface GRPCHandler { }\\npublic interface CollectionUtils {static boolean isEmpty(Map map);\\nstatic boolean isEmpty(List list);\\nstatic boolean isEmpty(Set set);\\nstatic boolean isNotEmpty(List list);\\nstatic boolean isNotEmpty(Set set);\\nstatic boolean isNotEmpty(Map map);\\nstatic boolean isNotEmpty(T[] array);\\nstatic boolean isEmpty(byte[] array);\\nstatic boolean isNotEmpty(byte[] array);\\n }\\n\" }", "class_name": "EBPFProcessServiceHandler", "code": "private JsonObject convertProperties(List properties){\n final JsonObject result=new JsonObject();\n for ( KeyStringValuePair kv : properties) {\n result.addProperty(kv.getKey(),kv.getValue());\n }\n return result;\n}\n", "docstring": "/** \n * Convert process properties to source data\n */\n", "end_lineno": "252", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.receiver.ebpf.provider.handler;\n\nimport com.google.gson.JsonObject;\nimport io.grpc.stub.StreamObserver;\nimport io.vavr.Tuple;\nimport io.vavr.Tuple2;\nimport org.apache.skywalking.apm.network.common.v3.Commands;\nimport org.apache.skywalking.apm.network.common.v3.KeyStringValuePair;\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFHostProcessDownstream;\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFHostProcessMetadata;\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFKubernetesProcessDownstream;\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFKubernetesProcessMetadata;\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFProcessDownstream;\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFProcessEntityMetadata;\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFProcessPingPkgList;\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFProcessProperties;\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFProcessReportList;\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFProcessServiceGrpc;\nimport org.apache.skywalking.apm.network.ebpf.profiling.process.v3.EBPFReportProcessDownstream;\nimport org.apache.skywalking.oap.server.core.CoreModule;\nimport org.apache.skywalking.oap.server.core.analysis.DownSampling;\nimport org.apache.skywalking.oap.server.core.analysis.IDManager;\nimport org.apache.skywalking.oap.server.core.analysis.Layer;\nimport org.apache.skywalking.oap.server.core.analysis.TimeBucket;\nimport org.apache.skywalking.oap.server.core.analysis.manual.process.ProcessDetectType;\nimport org.apache.skywalking.oap.server.core.config.NamingControl;\nimport org.apache.skywalking.oap.server.core.query.enumeration.ProfilingSupportStatus;\nimport org.apache.skywalking.oap.server.core.source.Process;\nimport org.apache.skywalking.oap.server.core.source.ServiceLabel;\nimport org.apache.skywalking.oap.server.core.source.ServiceInstanceUpdate;\nimport org.apache.skywalking.oap.server.core.source.ServiceMeta;\nimport org.apache.skywalking.oap.server.core.source.SourceReceiver;\nimport org.apache.skywalking.oap.server.library.module.ModuleManager;\nimport org.apache.skywalking.oap.server.library.server.grpc.GRPCHandler;\nimport org.apache.skywalking.oap.server.library.util.CollectionUtils;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;\n\npublic class EBPFProcessServiceHandler extends EBPFProcessServiceGrpc.EBPFProcessServiceImplBase implements GRPCHandler {\n\n private final SourceReceiver sourceReceiver;\n private final NamingControl namingControl;\n\n public EBPFProcessServiceHandler(ModuleManager moduleManager) {\n this.sourceReceiver = moduleManager.find(CoreModule.NAME).provider().getService(SourceReceiver.class);\n this.namingControl = moduleManager.find(CoreModule.NAME)\n .provider()\n .getService(NamingControl.class);\n }\n\n @Override\n public void reportProcesses(EBPFProcessReportList request, StreamObserver responseObserver) {\n final String agentId = request.getEbpfAgentID();\n\n // build per process data\n final ArrayList> processes = new ArrayList<>();\n for (EBPFProcessProperties ebpfProcessProperties : request.getProcessesList()) {\n Tuple2 processData = null;\n if (ebpfProcessProperties.hasHostProcess()) {\n processData = prepareReportHostProcess(ebpfProcessProperties.getHostProcess(), agentId);\n } else if (ebpfProcessProperties.hasK8SProcess()) {\n processData = prepareReportKubernetesProcess(ebpfProcessProperties.getK8SProcess(), agentId);\n }\n\n if (processData != null) {\n processes.add(processData);\n }\n }\n\n // report process and downstream the process id data\n final EBPFReportProcessDownstream.Builder builder = EBPFReportProcessDownstream.newBuilder();\n processes.stream().forEach(e -> {\n sourceReceiver.receive(e._1);\n builder.addProcesses(e._2);\n handleServiceLabels(e._1.getServiceName(), e._1.isServiceNormal(), e._1.getLabels(), e._1.getTimeBucket());\n });\n\n responseObserver.onNext(builder.build());\n responseObserver.onCompleted();\n }\n\n @Override\n public void keepAlive(EBPFProcessPingPkgList request, StreamObserver responseObserver) {\n final long timeBucket = TimeBucket.getTimeBucket(System.currentTimeMillis(), DownSampling.Minute);\n final String agentID = request.getEbpfAgentID();\n\n request.getProcessesList().forEach(p -> {\n final EBPFProcessEntityMetadata entity = p.getEntityMetadata();\n final String serviceName = namingControl.formatServiceName(entity.getServiceName());\n final String instanceName = namingControl.formatInstanceName(entity.getInstanceName());\n final Layer layer = Layer.valueOf(entity.getLayer());\n\n // process\n final Process processUpdate = new Process();\n processUpdate.setServiceName(serviceName);\n processUpdate.setInstanceName(instanceName);\n processUpdate.setServiceNormal(true);\n processUpdate.setName(entity.getProcessName());\n processUpdate.setLabels(entity.getLabelsList());\n processUpdate.setProperties(convertProperties(p.getPropertiesList()));\n processUpdate.setProfilingSupportStatus(getProfilingSupportStatus(p.getPropertiesList()));\n processUpdate.setTimeBucket(timeBucket);\n processUpdate.setAgentId(agentID);\n sourceReceiver.receive(processUpdate);\n\n // instance\n final ServiceInstanceUpdate serviceInstanceUpdate = new ServiceInstanceUpdate();\n serviceInstanceUpdate.setServiceId(IDManager.ServiceID.buildId(serviceName, true));\n serviceInstanceUpdate.setName(instanceName);\n serviceInstanceUpdate.setTimeBucket(timeBucket);\n sourceReceiver.receive(serviceInstanceUpdate);\n\n // service\n final ServiceMeta serviceMeta = new ServiceMeta();\n serviceMeta.setName(serviceName);\n serviceMeta.setTimeBucket(timeBucket);\n serviceMeta.setLayer(layer);\n sourceReceiver.receive(serviceMeta);\n\n // service label\n handleServiceLabels(serviceName, true, processUpdate.getLabels(), timeBucket);\n });\n\n responseObserver.onNext(Commands.newBuilder().build());\n responseObserver.onCompleted();\n }\n\n private Tuple2 prepareReportHostProcess(EBPFHostProcessMetadata hostProcess, String agentId) {\n final Process process = new Process();\n\n // entity\n process.setServiceName(namingControl.formatServiceName(hostProcess.getEntity().getServiceName()));\n process.setServiceNormal(true);\n process.setInstanceName(namingControl.formatInstanceName(hostProcess.getEntity().getInstanceName()));\n process.setName(hostProcess.getEntity().getProcessName());\n\n // metadata\n process.setDetectType(ProcessDetectType.VM);\n process.setAgentId(agentId);\n process.setProperties(convertProperties(hostProcess.getPropertiesList()));\n process.setLabels(hostProcess.getEntity().getLabelsList());\n process.setProfilingSupportStatus(getProfilingSupportStatus(hostProcess.getPropertiesList()));\n\n // timestamp\n process.setTimeBucket(\n TimeBucket.getTimeBucket(System.currentTimeMillis(), DownSampling.Minute));\n\n process.prepare();\n final String processId = process.getEntityId();\n final EBPFProcessDownstream downstream = EBPFProcessDownstream.newBuilder()\n .setProcessId(processId)\n .setHostProcess(EBPFHostProcessDownstream.newBuilder()\n .setPid(hostProcess.getPid())\n .setEntityMetadata(hostProcess.getEntity())\n .build())\n .build();\n return Tuple.of(process, downstream);\n }\n\n private Tuple2 prepareReportKubernetesProcess(EBPFKubernetesProcessMetadata kubernetesProcessMetadata, String agentId) {\n final Process process = new Process();\n\n // entity\n process.setServiceName(namingControl.formatServiceName(kubernetesProcessMetadata.getEntity().getServiceName()));\n process.setServiceNormal(true);\n process.setInstanceName(namingControl.formatInstanceName(kubernetesProcessMetadata.getEntity().getInstanceName()));\n process.setName(kubernetesProcessMetadata.getEntity().getProcessName());\n\n // metadata\n process.setDetectType(ProcessDetectType.KUBERNETES);\n process.setAgentId(agentId);\n process.setProperties(convertProperties(kubernetesProcessMetadata.getPropertiesList()));\n process.setLabels(kubernetesProcessMetadata.getEntity().getLabelsList());\n process.setProfilingSupportStatus(getProfilingSupportStatus(kubernetesProcessMetadata.getPropertiesList()));\n\n // timestamp\n process.setTimeBucket(\n TimeBucket.getTimeBucket(System.currentTimeMillis(), DownSampling.Minute));\n\n process.prepare();\n final String processId = process.getEntityId();\n final EBPFProcessDownstream downstream = EBPFProcessDownstream.newBuilder()\n .setProcessId(processId)\n .setK8SProcess(EBPFKubernetesProcessDownstream.newBuilder()\n .setPid(kubernetesProcessMetadata.getPid())\n .setEntityMetadata(kubernetesProcessMetadata.getEntity())\n .build())\n .build();\n return Tuple.of(process, downstream);\n }\n\n /**\n * Append service label\n */\n private void handleServiceLabels(String serviceName, boolean isServiceNormal, List labels, long timeBucket) {\n if (CollectionUtils.isEmpty(labels)) {\n return;\n }\n for (String label : labels) {\n final ServiceLabel serviceLabel = new ServiceLabel();\n serviceLabel.setServiceName(serviceName);\n serviceLabel.setServiceNormal(isServiceNormal);\n serviceLabel.setLabel(label);\n serviceLabel.setTimeBucket(timeBucket);\n\n sourceReceiver.receive(serviceLabel);\n }\n }\n\n /**\n * Validate the process is support the eBPF profiling\n */\n private ProfilingSupportStatus getProfilingSupportStatus(List properties) {\n for (KeyStringValuePair property : properties) {\n if (Objects.equals(property.getKey(), \"support_ebpf_profiling\")\n && Objects.equals(property.getValue(), \"true\")) {\n return ProfilingSupportStatus.SUPPORT_EBPF_PROFILING;\n }\n }\n return ProfilingSupportStatus.NOT_SUPPORT;\n }\n\n /**\n * Convert process properties to source data\n */\n private JsonObject convertProperties(List properties) {\n final JsonObject result = new JsonObject();\n for (KeyStringValuePair kv : properties) {\n result.addProperty(kv.getKey(), kv.getValue());\n }\n return result;\n }\n}\n", "file_name": "EBPFProcessServiceHandler.java", "human_label": "Convert process properties to the JsonObject.", "level": "project_runnable", "lineno": "243", "name": "convertProperties", "oracle_context": "{ \"apis\" : \"[addProperty, getKey, getValue]\", \"classes\" : \"[JsonObject]\", \"vars\" : \"[]\" }", "package": "org.apache.skywalking.oap.server.receiver.ebpf.provider.handler", "project": "skywalking-master" }, { "_id": "6367677e1a6d9265ec018314", "all_context": "{ \"class_level\" : \"import java.awt.Component;\\nimport java.awt.event.ActionEvent;\\nimport java.awt.event.ActionListener;\\nimport java.awt.event.MouseAdapter;\\nimport java.awt.event.MouseEvent;\\nimport java.util.ArrayList;\\nimport java.util.Enumeration;\\nimport javax.swing.JCheckBox;\\nimport javax.swing.JMenuItem;\\nimport javax.swing.JOptionPane;\\nimport javax.swing.JPopupMenu;\\nimport javax.swing.JTree;\\nimport javax.swing.tree.TreePath;\\nCategoryNodeEditorRenderer _renderer;\\nCategoryNode _lastEditedNode;\\nJCheckBox _checkBox;\\nCategoryExplorerModel _categoryModel;\\nJTree _tree;\\nCategoryNodeEditor(CategoryExplorerModel model);\\nactionPerformed(ActionEvent e);\\nmousePressed(MouseEvent e);\\ngetTreeCellEditorComponent(JTree tree,Object value,boolean selected,boolean expanded,boolean leaf,int row);\\ngetCellEditorValue();\\ncreatePropertiesMenuItem(CategoryNode node);\\nshowPropertiesDialog(CategoryNode node);\\ngetDisplayedProperties(CategoryNode node);\\nshowPopup(CategoryNode node,int x,int y);\\ncreateSelectDescendantsMenuItem(CategoryNode node);\\ncreateUnselectDescendantsMenuItem(CategoryNode node);\\ncreateExpandMenuItem(CategoryNode node);\\ncreateCollapseMenuItem(CategoryNode node);\\nexpandDescendants(CategoryNode node);\\ncollapseDescendants(CategoryNode node);\\nremoveUnusedNodes();\\nexpand(CategoryNode node);\\ngetTreePath(CategoryNode node);\\ncollapse(CategoryNode node);\\ncreateRemoveMenuItem();\\n\", \"repo_level\" : \"\" }", "class_name": "CategoryNodeEditor", "code": "protected int removeUnusedNodes(){\n int count=0;\n CategoryNode root=_categoryModel.getRootCategoryNode();\n Enumeration enumeration=root.depthFirstEnumeration();\n while (enumeration.hasMoreElements()) {\n CategoryNode node=(CategoryNode)enumeration.nextElement();\n if (node.isLeaf() && node.getNumberOfContainedRecords() == 0 && node.getParent() != null) {\n _categoryModel.removeNodeFromParent(node);\n count++;\n }\n }\n return count;\n}\n", "docstring": "/** \n * Removes any inactive nodes from the Category tree.\n */\n", "end_lineno": "269", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.log4j.lf5.viewer.categoryexplorer;\n\nimport java.awt.Component;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.util.ArrayList;\nimport java.util.Enumeration;\n\nimport javax.swing.JCheckBox;\nimport javax.swing.JMenuItem;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPopupMenu;\nimport javax.swing.JTree;\nimport javax.swing.tree.TreePath;\n\n/**\n * CategoryNodeEditor\n *\n * @author Michael J. Sikorsky\n * @author Robert Shaw\n */\n\n// Contributed by ThoughtWorks Inc.\n\npublic class CategoryNodeEditor extends CategoryAbstractCellEditor {\n //--------------------------------------------------------------------------\n // Constants:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Protected Variables:\n //--------------------------------------------------------------------------\n protected CategoryNodeEditorRenderer _renderer;\n protected CategoryNode _lastEditedNode;\n protected JCheckBox _checkBox;\n protected CategoryExplorerModel _categoryModel;\n protected JTree _tree;\n\n //--------------------------------------------------------------------------\n // Private Variables:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Constructors:\n //--------------------------------------------------------------------------\n\n public CategoryNodeEditor(CategoryExplorerModel model) {\n _renderer = new CategoryNodeEditorRenderer();\n _checkBox = _renderer.getCheckBox();\n _categoryModel = model;\n\n _checkBox.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n _categoryModel.update(_lastEditedNode, _checkBox.isSelected());\n stopCellEditing();\n }\n });\n\n _renderer.addMouseListener(new MouseAdapter() {\n public void mousePressed(MouseEvent e) {\n if ((e.getModifiers() & MouseEvent.BUTTON3_MASK) != 0) {\n showPopup(_lastEditedNode, e.getX(), e.getY());\n }\n stopCellEditing();\n }\n });\n }\n\n //--------------------------------------------------------------------------\n // Public Methods:\n //--------------------------------------------------------------------------\n\n public Component getTreeCellEditorComponent(JTree tree, Object value,\n boolean selected, boolean expanded,\n boolean leaf, int row) {\n _lastEditedNode = (CategoryNode) value;\n _tree = tree;\n\n return _renderer.getTreeCellRendererComponent(tree,\n value, selected, expanded,\n leaf, row, true);\n // hasFocus ignored\n }\n\n public Object getCellEditorValue() {\n return _lastEditedNode.getUserObject();\n }\n //--------------------------------------------------------------------------\n // Protected Methods:\n //--------------------------------------------------------------------------\n\n protected JMenuItem createPropertiesMenuItem(final CategoryNode node) {\n JMenuItem result = new JMenuItem(\"Properties\");\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n showPropertiesDialog(node);\n }\n });\n return result;\n }\n\n protected void showPropertiesDialog(CategoryNode node) {\n JOptionPane.showMessageDialog(\n _tree,\n getDisplayedProperties(node),\n \"Category Properties: \" + node.getTitle(),\n JOptionPane.PLAIN_MESSAGE\n );\n }\n\n protected Object getDisplayedProperties(CategoryNode node) {\n ArrayList result = new ArrayList();\n result.add(\"Category: \" + node.getTitle());\n if (node.hasFatalRecords()) {\n result.add(\"Contains at least one fatal LogRecord.\");\n }\n if (node.hasFatalChildren()) {\n result.add(\"Contains descendants with a fatal LogRecord.\");\n }\n result.add(\"LogRecords in this category alone: \" +\n node.getNumberOfContainedRecords());\n result.add(\"LogRecords in descendant categories: \" +\n node.getNumberOfRecordsFromChildren());\n result.add(\"LogRecords in this category including descendants: \" +\n node.getTotalNumberOfRecords());\n return result.toArray();\n }\n\n protected void showPopup(CategoryNode node, int x, int y) {\n JPopupMenu popup = new JPopupMenu();\n popup.setSize(150, 400);\n //\n // Configure the Popup\n //\n if (node.getParent() == null) {\n popup.add(createRemoveMenuItem());\n popup.addSeparator();\n }\n popup.add(createSelectDescendantsMenuItem(node));\n popup.add(createUnselectDescendantsMenuItem(node));\n popup.addSeparator();\n popup.add(createExpandMenuItem(node));\n popup.add(createCollapseMenuItem(node));\n popup.addSeparator();\n popup.add(createPropertiesMenuItem(node));\n popup.show(_renderer, x, y);\n }\n\n protected JMenuItem createSelectDescendantsMenuItem(final CategoryNode node) {\n JMenuItem selectDescendants =\n new JMenuItem(\"Select All Descendant Categories\");\n selectDescendants.addActionListener(\n new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n _categoryModel.setDescendantSelection(node, true);\n }\n }\n );\n return selectDescendants;\n }\n\n protected JMenuItem createUnselectDescendantsMenuItem(final CategoryNode node) {\n JMenuItem unselectDescendants =\n new JMenuItem(\"Deselect All Descendant Categories\");\n unselectDescendants.addActionListener(\n\n new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n _categoryModel.setDescendantSelection(node, false);\n }\n }\n\n );\n return unselectDescendants;\n }\n\n protected JMenuItem createExpandMenuItem(final CategoryNode node) {\n JMenuItem result = new JMenuItem(\"Expand All Descendant Categories\");\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n expandDescendants(node);\n }\n });\n return result;\n }\n\n protected JMenuItem createCollapseMenuItem(final CategoryNode node) {\n JMenuItem result = new JMenuItem(\"Collapse All Descendant Categories\");\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n collapseDescendants(node);\n }\n });\n return result;\n }\n\n /**\n * This featured was moved from the LogBrokerMonitor class\n * to the CategoryNodeExplorer so that the Category tree\n * could be pruned from the Category Explorer popup menu.\n * This menu option only appears when a user right clicks on\n * the Category parent node.\n *\n * See removeUnusedNodes()\n */\n protected JMenuItem createRemoveMenuItem() {\n JMenuItem result = new JMenuItem(\"Remove All Empty Categories\");\n result.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n while (removeUnusedNodes() > 0) ;\n }\n });\n return result;\n }\n\n protected void expandDescendants(CategoryNode node) {\n Enumeration descendants = node.depthFirstEnumeration();\n CategoryNode current;\n while (descendants.hasMoreElements()) {\n current = (CategoryNode) descendants.nextElement();\n expand(current);\n }\n }\n\n protected void collapseDescendants(CategoryNode node) {\n Enumeration descendants = node.depthFirstEnumeration();\n CategoryNode current;\n while (descendants.hasMoreElements()) {\n current = (CategoryNode) descendants.nextElement();\n collapse(current);\n }\n }\n\n /**\n * Removes any inactive nodes from the Category tree.\n */\n protected int removeUnusedNodes() {\n int count = 0;\n CategoryNode root = _categoryModel.getRootCategoryNode();\n Enumeration enumeration = root.depthFirstEnumeration();\n while (enumeration.hasMoreElements()) {\n CategoryNode node = (CategoryNode) enumeration.nextElement();\n if (node.isLeaf() && node.getNumberOfContainedRecords() == 0\n && node.getParent() != null) {\n _categoryModel.removeNodeFromParent(node);\n count++;\n }\n }\n\n return count;\n }\n\n protected void expand(CategoryNode node) {\n _tree.expandPath(getTreePath(node));\n }\n\n protected TreePath getTreePath(CategoryNode node) {\n return new TreePath(node.getPath());\n }\n\n protected void collapse(CategoryNode node) {\n _tree.collapsePath(getTreePath(node));\n }\n\n //-----------------------------------------------------------------------\n // Private Methods:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Nested Top-Level Classes or Interfaces:\n //--------------------------------------------------------------------------\n\n}\n", "file_name": "CategoryNodeEditor.java", "human_label": "Remove any inactive nodes from the Category tree and return the number of removed nodes.", "level": "project_runnable", "lineno": "252", "name": "removeUnusedNodes", "oracle_context": "{ \"apis\" : \"[getRootCategoryNode, depthFirstEnumeration, hasMoreElements, nextElement, isLeaf, getNumberOfContainedRecords, getParent, removeNodeFromParent]\", \"classes\" : \"[CategoryNode, Enumeration]\", \"vars\" : \"[_categoryModel]\" }", "package": "org.apache.log4j.lf5.viewer.categoryexplorer", "project": "logging-log4j1-main" }, { "_id": "636766ff1a6d9265ec017853", "all_context": "{ \"class_level\" : \"import java.io.ByteArrayOutputStream;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nint SKIP_CODE;\\nint SKIP_DEBUG;\\nint SKIP_FRAMES;\\nint EXPAND_FRAMES;\\nint EXPAND_ASM_INSNS;\\nint INPUT_STREAM_DATA_CHUNK_SIZE;\\nbyte[] b;\\nbyte[] classFileBuffer;\\nint[] cpInfoOffsets;\\nString[] constantUtf8Values;\\nConstantDynamic[] constantDynamicValues;\\nint[] bootstrapMethodOffsets;\\nint maxStringLength;\\nint header;\\nClassReader(byte[] classFile);\\nClassReader(byte[] classFileBuffer,int classFileOffset,int classFileLength);\\nClassReader(byte[] classFileBuffer,int classFileOffset,boolean checkClassVersion);\\nClassReader(InputStream inputStream);\\nClassReader(String className);\\ngetAccess();\\ngetClassName();\\ngetSuperName();\\ngetInterfaces();\\naccept(ClassVisitor classVisitor,int parsingOptions);\\naccept(ClassVisitor classVisitor,Attribute[] attributePrototypes,int parsingOptions);\\nreadModuleAttributes(ClassVisitor classVisitor,Context context,int moduleOffset,int modulePackagesOffset,String moduleMainClass);\\nreadRecordComponent(ClassVisitor classVisitor,Context context,int recordComponentOffset);\\nreadField(ClassVisitor classVisitor,Context context,int fieldInfoOffset);\\nreadMethod(ClassVisitor classVisitor,Context context,int methodInfoOffset);\\nreadCode(MethodVisitor methodVisitor,Context context,int codeOffset);\\nreadLabel(int bytecodeOffset,Label[] labels);\\ncreateLabel(int bytecodeOffset,Label[] labels);\\ncreateDebugLabel(int bytecodeOffset,Label[] labels);\\nreadTypeAnnotations(MethodVisitor methodVisitor,Context context,int runtimeTypeAnnotationsOffset,boolean visible);\\ngetTypeAnnotationBytecodeOffset(int[] typeAnnotationOffsets,int typeAnnotationIndex);\\nreadTypeAnnotationTarget(Context context,int typeAnnotationOffset);\\nreadParameterAnnotations(MethodVisitor methodVisitor,Context context,int runtimeParameterAnnotationsOffset,boolean visible);\\nreadElementValues(AnnotationVisitor annotationVisitor,int annotationOffset,boolean named,char[] charBuffer);\\nreadElementValue(AnnotationVisitor annotationVisitor,int elementValueOffset,String elementName,char[] charBuffer);\\ncomputeImplicitFrame(Context context);\\nreadStackMapFrame(int stackMapFrameOffset,boolean compressed,boolean expand,Context context);\\nreadVerificationTypeInfo(int verificationTypeInfoOffset,Object[] frame,int index,char[] charBuffer,Label[] labels);\\ngetFirstAttributeOffset();\\nreadBootstrapMethodsAttribute(int maxStringLength);\\nreadAttribute(Attribute[] attributePrototypes,String type,int offset,int length,char[] charBuffer,int codeAttributeOffset,Label[] labels);\\ngetItemCount();\\ngetItem(int constantPoolEntryIndex);\\ngetMaxStringLength();\\nreadByte(int offset);\\nreadUnsignedShort(int offset);\\nreadShort(int offset);\\nreadInt(int offset);\\nreadLong(int offset);\\nreadUTF8(int offset,char[] charBuffer);\\nreadUtf(int constantPoolEntryIndex,char[] charBuffer);\\nreadUtf(int utfOffset,int utfLength,char[] charBuffer);\\nreadStringish(int offset,char[] charBuffer);\\nreadClass(int offset,char[] charBuffer);\\nreadModule(int offset,char[] charBuffer);\\nreadPackage(int offset,char[] charBuffer);\\nreadConstantDynamic(int constantPoolEntryIndex,char[] charBuffer);\\nreadConst(int constantPoolEntryIndex,char[] charBuffer);\\nreadStream(InputStream inputStream,boolean close);\\n\", \"repo_level\" : \"\" }", "class_name": "ClassReader", "code": "protected Label readLabel(final int bytecodeOffset,final Label[] labels){\n if (labels[bytecodeOffset] == null) {\n labels[bytecodeOffset]=new Label();\n }\n return labels[bytecodeOffset];\n}\n", "docstring": "/** \n * Returns the label corresponding to the given bytecode offset. The default implementation of this method creates a label for the given offset if it has not been already created.\n * @param bytecodeOffset a bytecode offset in a method.\n * @param labels the already created labels, indexed by their offset. If a label already existsfor bytecodeOffset this method must not create a new one. Otherwise it must store the new label in this array.\n * @return a non null Label, which must be equal to labels[bytecodeOffset].\n */\n", "end_lineno": "2283", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage net.hasor.utils.asm;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/**\n * A parser to make a {@link ClassVisitor} visit a ClassFile structure, as defined in the Java\n * Virtual Machine Specification (JVMS). This class parses the ClassFile content and calls the\n * appropriate visit methods of a given {@link ClassVisitor} for each field, method and bytecode\n * instruction encountered.\n *\n * @see JVMS 4\n * @author Eric Bruneton\n * @author Eugene Kuleshov\n */\npublic class ClassReader {\n /**\n * A flag to skip the Code attributes. If this flag is set the Code attributes are neither parsed\n * nor visited.\n */\n public static final int SKIP_CODE = 1;\n /**\n * A flag to skip the SourceFile, SourceDebugExtension, LocalVariableTable,\n * LocalVariableTypeTable, LineNumberTable and MethodParameters attributes. If this flag is set\n * these attributes are neither parsed nor visited (i.e. {@link ClassVisitor#visitSource}, {@link\n * MethodVisitor#visitLocalVariable}, {@link MethodVisitor#visitLineNumber} and {@link\n * MethodVisitor#visitParameter} are not called).\n */\n public static final int SKIP_DEBUG = 2;\n /**\n * A flag to skip the StackMap and StackMapTable attributes. If this flag is set these attributes\n * are neither parsed nor visited (i.e. {@link MethodVisitor#visitFrame} is not called). This flag\n * is useful when the {@link ClassWriter#COMPUTE_FRAMES} option is used: it avoids visiting frames\n * that will be ignored and recomputed from scratch.\n */\n public static final int SKIP_FRAMES = 4;\n /**\n * A flag to expand the stack map frames. By default stack map frames are visited in their\n * original format (i.e. \"expanded\" for classes whose version is less than V1_6, and \"compressed\"\n * for the other classes). If this flag is set, stack map frames are always visited in expanded\n * format (this option adds a decompression/compression step in ClassReader and ClassWriter which\n * degrades performance quite a lot).\n */\n public static final int EXPAND_FRAMES = 8;\n /**\n * A flag to expand the ASM specific instructions into an equivalent sequence of standard bytecode\n * instructions. When resolving a forward jump it may happen that the signed 2 bytes offset\n * reserved for it is not sufficient to store the bytecode offset. In this case the jump\n * instruction is replaced with a temporary ASM specific instruction using an unsigned 2 bytes\n * offset (see {@link Label#resolve}). This internal flag is used to re-read classes containing\n * such instructions, in order to replace them with standard instructions. In addition, when this\n * flag is used, goto_w and jsr_w are not converted into goto and jsr, to make sure that\n * infinite loops where a goto_w is replaced with a goto in ClassReader and converted back to a\n * goto_w in ClassWriter cannot occur.\n */\n static final int EXPAND_ASM_INSNS = 256;\n /** The size of the temporary byte array used to read class input streams chunk by chunk. */\n private static final int INPUT_STREAM_DATA_CHUNK_SIZE = 4096;\n /**\n * A byte array containing the JVMS ClassFile structure to be parsed.\n *\n * @deprecated Use {@link #readByte(int)} and the other read methods instead. This field will\n * eventually be deleted.\n */\n @Deprecated\n // DontCheck(MemberName): can't be renamed (for backward binary compatibility).\n public final byte[] b;\n /**\n * A byte array containing the JVMS ClassFile structure to be parsed. The content of this array\n * must not be modified. This field is intended for {@link Attribute} sub classes, and is normally\n * not needed by class visitors.\n *\n *

NOTE: the ClassFile structure can start at any offset within this array, i.e. it does not\n * necessarily start at offset 0. Use {@link #getItem} and {@link #header} to get correct\n * ClassFile element offsets within this byte array.\n */\n final byte[] classFileBuffer;\n /**\n * The offset in bytes, in {@link #classFileBuffer}, of each cp_info entry of the ClassFile's\n * constant_pool array, plus one. In other words, the offset of constant pool entry i is\n * given by cpInfoOffsets[i] - 1, i.e. its cp_info's tag field is given by b[cpInfoOffsets[i] -\n * 1].\n */\n private final int[] cpInfoOffsets;\n /**\n * The String objects corresponding to the CONSTANT_Utf8 constant pool items. This cache avoids\n * multiple parsing of a given CONSTANT_Utf8 constant pool item.\n */\n private final String[] constantUtf8Values;\n /**\n * The ConstantDynamic objects corresponding to the CONSTANT_Dynamic constant pool items. This\n * cache avoids multiple parsing of a given CONSTANT_Dynamic constant pool item.\n */\n private final ConstantDynamic[] constantDynamicValues;\n /**\n * The start offsets in {@link #classFileBuffer} of each element of the bootstrap_methods array\n * (in the BootstrapMethods attribute).\n *\n * @see JVMS\n * 4.7.23\n */\n private final int[] bootstrapMethodOffsets;\n /**\n * A conservative estimate of the maximum length of the strings contained in the constant pool of\n * the class.\n */\n private final int maxStringLength;\n /** The offset in bytes of the ClassFile's access_flags field. */\n public final int header;\n // -----------------------------------------------------------------------------------------------\n // Constructors\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param classFile the JVMS ClassFile structure to be read.\n */\n public ClassReader(final byte[] classFile) {\n this(classFile, 0, classFile.length);\n }\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read.\n * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read.\n * @param classFileLength the length in bytes of the ClassFile to be read.\n */\n public ClassReader(final byte[] classFileBuffer, final int classFileOffset, final int classFileLength) { // NOPMD(UnusedFormalParameter) used for backward compatibility.\n this(classFileBuffer, classFileOffset, /* checkClassVersion = */ true);\n }\n\n /**\n * Constructs a new {@link ClassReader} object. This internal constructor must not be exposed\n * as a public API.\n *\n * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read.\n * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read.\n * @param checkClassVersion whether to check the class version or not.\n */\n ClassReader(final byte[] classFileBuffer, final int classFileOffset, final boolean checkClassVersion) {\n this.classFileBuffer = classFileBuffer;\n this.b = classFileBuffer;\n // Check the class' major_version. This field is after the magic and minor_version fields, which\n // use 4 and 2 bytes respectively.\n if (checkClassVersion && readShort(classFileOffset + 6) > Opcodes.V15) {\n throw new IllegalArgumentException(\"Unsupported class file major version \" + readShort(classFileOffset + 6));\n }\n // Create the constant pool arrays. The constant_pool_count field is after the magic,\n // minor_version and major_version fields, which use 4, 2 and 2 bytes respectively.\n int constantPoolCount = readUnsignedShort(classFileOffset + 8);\n cpInfoOffsets = new int[constantPoolCount];\n constantUtf8Values = new String[constantPoolCount];\n // Compute the offset of each constant pool entry, as well as a conservative estimate of the\n // maximum length of the constant pool strings. The first constant pool entry is after the\n // magic, minor_version, major_version and constant_pool_count fields, which use 4, 2, 2 and 2\n // bytes respectively.\n int currentCpInfoIndex = 1;\n int currentCpInfoOffset = classFileOffset + 10;\n int currentMaxStringLength = 0;\n boolean hasBootstrapMethods = false;\n boolean hasConstantDynamic = false;\n // The offset of the other entries depend on the total size of all the previous entries.\n while (currentCpInfoIndex < constantPoolCount) {\n cpInfoOffsets[currentCpInfoIndex++] = currentCpInfoOffset + 1;\n int cpInfoSize;\n switch (classFileBuffer[currentCpInfoOffset]) {\n case Symbol.CONSTANT_FIELDREF_TAG:\n case Symbol.CONSTANT_METHODREF_TAG:\n case Symbol.CONSTANT_INTERFACE_METHODREF_TAG:\n case Symbol.CONSTANT_INTEGER_TAG:\n case Symbol.CONSTANT_FLOAT_TAG:\n case Symbol.CONSTANT_NAME_AND_TYPE_TAG:\n cpInfoSize = 5;\n break;\n case Symbol.CONSTANT_DYNAMIC_TAG:\n cpInfoSize = 5;\n hasBootstrapMethods = true;\n hasConstantDynamic = true;\n break;\n case Symbol.CONSTANT_INVOKE_DYNAMIC_TAG:\n cpInfoSize = 5;\n hasBootstrapMethods = true;\n break;\n case Symbol.CONSTANT_LONG_TAG:\n case Symbol.CONSTANT_DOUBLE_TAG:\n cpInfoSize = 9;\n currentCpInfoIndex++;\n break;\n case Symbol.CONSTANT_UTF8_TAG:\n cpInfoSize = 3 + readUnsignedShort(currentCpInfoOffset + 1);\n if (cpInfoSize > currentMaxStringLength) {\n // The size in bytes of this CONSTANT_Utf8 structure provides a conservative estimate\n // of the length in characters of the corresponding string, and is much cheaper to\n // compute than this exact length.\n currentMaxStringLength = cpInfoSize;\n }\n break;\n case Symbol.CONSTANT_METHOD_HANDLE_TAG:\n cpInfoSize = 4;\n break;\n case Symbol.CONSTANT_CLASS_TAG:\n case Symbol.CONSTANT_STRING_TAG:\n case Symbol.CONSTANT_METHOD_TYPE_TAG:\n case Symbol.CONSTANT_PACKAGE_TAG:\n case Symbol.CONSTANT_MODULE_TAG:\n cpInfoSize = 3;\n break;\n default:\n throw new IllegalArgumentException();\n }\n currentCpInfoOffset += cpInfoSize;\n }\n maxStringLength = currentMaxStringLength;\n // The Classfile's access_flags field is just after the last constant pool entry.\n header = currentCpInfoOffset;\n // Allocate the cache of ConstantDynamic values, if there is at least one.\n constantDynamicValues = hasConstantDynamic ? new ConstantDynamic[constantPoolCount] : null;\n // Read the BootstrapMethods attribute, if any (only get the offset of each method).\n bootstrapMethodOffsets = hasBootstrapMethods ? readBootstrapMethodsAttribute(currentMaxStringLength) : null;\n }\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param inputStream an input stream of the JVMS ClassFile structure to be read. This input\n * stream must contain nothing more than the ClassFile structure itself. It is read from its\n * current position to its end.\n * @throws IOException if a problem occurs during reading.\n */\n public ClassReader(final InputStream inputStream) throws IOException {\n this(readStream(inputStream, false));\n }\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param className the fully qualified name of the class to be read. The ClassFile structure is\n * retrieved with the current class loader's {@link ClassLoader#getSystemResourceAsStream}.\n * @throws IOException if an exception occurs during reading.\n */\n public ClassReader(final String className) throws IOException {\n this(readStream(ClassLoader.getSystemResourceAsStream(className.replace('.', '/') + \".class\"), true));\n }\n\n /**\n * Reads the given input stream and returns its content as a byte array.\n *\n * @param inputStream an input stream.\n * @param close true to close the input stream after reading.\n * @return the content of the given input stream.\n * @throws IOException if a problem occurs during reading.\n */\n private static byte[] readStream(final InputStream inputStream, final boolean close) throws IOException {\n if (inputStream == null) {\n throw new IOException(\"Class not found\");\n }\n try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {\n byte[] data = new byte[INPUT_STREAM_DATA_CHUNK_SIZE];\n int bytesRead;\n while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {\n outputStream.write(data, 0, bytesRead);\n }\n outputStream.flush();\n return outputStream.toByteArray();\n } finally {\n if (close) {\n inputStream.close();\n }\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Accessors\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the class's access flags (see {@link Opcodes}). This value may not reflect Deprecated\n * and Synthetic flags when bytecode is before 1.5 and those flags are represented by attributes.\n *\n * @return the class access flags.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public int getAccess() {\n return readUnsignedShort(header);\n }\n\n /**\n * Returns the internal name of the class (see {@link Type#getInternalName()}).\n *\n * @return the internal class name.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public String getClassName() {\n // this_class is just after the access_flags field (using 2 bytes).\n return readClass(header + 2, new char[maxStringLength]);\n }\n\n /**\n * Returns the internal of name of the super class (see {@link Type#getInternalName()}). For\n * interfaces, the super class is {@link Object}.\n *\n * @return the internal name of the super class, or {@literal null} for {@link Object} class.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public String getSuperName() {\n // super_class is after the access_flags and this_class fields (2 bytes each).\n return readClass(header + 4, new char[maxStringLength]);\n }\n\n /**\n * Returns the internal names of the implemented interfaces (see {@link Type#getInternalName()}).\n *\n * @return the internal names of the directly implemented interfaces. Inherited implemented\n * interfaces are not returned.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public String[] getInterfaces() {\n // interfaces_count is after the access_flags, this_class and super_class fields (2 bytes each).\n int currentOffset = header + 6;\n int interfacesCount = readUnsignedShort(currentOffset);\n String[] interfaces = new String[interfacesCount];\n if (interfacesCount > 0) {\n char[] charBuffer = new char[maxStringLength];\n for (int i = 0; i < interfacesCount; ++i) {\n currentOffset += 2;\n interfaces[i] = readClass(currentOffset, charBuffer);\n }\n }\n return interfaces;\n }\n // -----------------------------------------------------------------------------------------------\n // Public methods\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this\n * {@link ClassReader}.\n *\n * @param classVisitor the visitor that must visit this class.\n * @param parsingOptions the options to use to parse this class. One or more of {@link\n * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}.\n */\n public void accept(final ClassVisitor classVisitor, final int parsingOptions) {\n accept(classVisitor, new Attribute[0], parsingOptions);\n }\n\n /**\n * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this\n * {@link ClassReader}.\n *\n * @param classVisitor the visitor that must visit this class.\n * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of\n * the class. Any attribute whose type is not equal to the type of one the prototypes will not\n * be parsed: its byte array value will be passed unchanged to the ClassWriter. This may\n * corrupt it if this value contains references to the constant pool, or has syntactic or\n * semantic links with a class element that has been transformed by a class adapter between\n * the reader and the writer.\n * @param parsingOptions the options to use to parse this class. One or more of {@link\n * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}.\n */\n public void accept(final ClassVisitor classVisitor, final Attribute[] attributePrototypes, final int parsingOptions) {\n Context context = new Context();\n context.attributePrototypes = attributePrototypes;\n context.parsingOptions = parsingOptions;\n context.charBuffer = new char[maxStringLength];\n // Read the access_flags, this_class, super_class, interface_count and interfaces fields.\n char[] charBuffer = context.charBuffer;\n int currentOffset = header;\n int accessFlags = readUnsignedShort(currentOffset);\n String thisClass = readClass(currentOffset + 2, charBuffer);\n String superClass = readClass(currentOffset + 4, charBuffer);\n String[] interfaces = new String[readUnsignedShort(currentOffset + 6)];\n currentOffset += 8;\n for (int i = 0; i < interfaces.length; ++i) {\n interfaces[i] = readClass(currentOffset, charBuffer);\n currentOffset += 2;\n }\n // Read the class attributes (the variables are ordered as in Section 4.7 of the JVMS).\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The offset of the InnerClasses attribute, or 0.\n int innerClassesOffset = 0;\n // - The offset of the EnclosingMethod attribute, or 0.\n int enclosingMethodOffset = 0;\n // - The string corresponding to the Signature attribute, or null.\n String signature = null;\n // - The string corresponding to the SourceFile attribute, or null.\n String sourceFile = null;\n // - The string corresponding to the SourceDebugExtension attribute, or null.\n String sourceDebugExtension = null;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The offset of the Module attribute, or 0.\n int moduleOffset = 0;\n // - The offset of the ModulePackages attribute, or 0.\n int modulePackagesOffset = 0;\n // - The string corresponding to the ModuleMainClass attribute, or null.\n String moduleMainClass = null;\n // - The string corresponding to the NestHost attribute, or null.\n String nestHostClass = null;\n // - The offset of the NestMembers attribute, or 0.\n int nestMembersOffset = 0;\n // - The offset of the PermittedSubtypes attribute, or 0\n int permittedSubtypesOffset = 0;\n // - The offset of the Record attribute, or 0.\n int recordOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int currentAttributeOffset = getFirstAttributeOffset();\n for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentAttributeOffset, charBuffer);\n int attributeLength = readInt(currentAttributeOffset + 2);\n currentAttributeOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.SOURCE_FILE.equals(attributeName)) {\n sourceFile = readUTF8(currentAttributeOffset, charBuffer);\n } else if (Constants.INNER_CLASSES.equals(attributeName)) {\n innerClassesOffset = currentAttributeOffset;\n } else if (Constants.ENCLOSING_METHOD.equals(attributeName)) {\n enclosingMethodOffset = currentAttributeOffset;\n } else if (Constants.NEST_HOST.equals(attributeName)) {\n nestHostClass = readClass(currentAttributeOffset, charBuffer);\n } else if (Constants.NEST_MEMBERS.equals(attributeName)) {\n nestMembersOffset = currentAttributeOffset;\n } else if (Constants.PERMITTED_SUBTYPES.equals(attributeName)) {\n permittedSubtypesOffset = currentAttributeOffset;\n } else if (Constants.SIGNATURE.equals(attributeName)) {\n signature = readUTF8(currentAttributeOffset, charBuffer);\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.SYNTHETIC.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_SYNTHETIC;\n } else if (Constants.SOURCE_DEBUG_EXTENSION.equals(attributeName)) {\n sourceDebugExtension = readUtf(currentAttributeOffset, attributeLength, new char[attributeLength]);\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.RECORD.equals(attributeName)) {\n recordOffset = currentAttributeOffset;\n } else if (Constants.MODULE.equals(attributeName)) {\n moduleOffset = currentAttributeOffset;\n } else if (Constants.MODULE_MAIN_CLASS.equals(attributeName)) {\n moduleMainClass = readClass(currentAttributeOffset, charBuffer);\n } else if (Constants.MODULE_PACKAGES.equals(attributeName)) {\n modulePackagesOffset = currentAttributeOffset;\n } else if (!Constants.BOOTSTRAP_METHODS.equals(attributeName)) {\n // The BootstrapMethods attribute is read in the constructor.\n Attribute attribute = readAttribute(attributePrototypes, attributeName, currentAttributeOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentAttributeOffset += attributeLength;\n }\n // Visit the class declaration. The minor_version and major_version fields start 6 bytes before\n // the first constant pool entry, which itself starts at cpInfoOffsets[1] - 1 (by definition).\n classVisitor.visit(readInt(cpInfoOffsets[1] - 7), accessFlags, thisClass, signature, superClass, interfaces);\n // Visit the SourceFile and SourceDebugExtenstion attributes.\n if ((parsingOptions & SKIP_DEBUG) == 0 && (sourceFile != null || sourceDebugExtension != null)) {\n classVisitor.visitSource(sourceFile, sourceDebugExtension);\n }\n // Visit the Module, ModulePackages and ModuleMainClass attributes.\n if (moduleOffset != 0) {\n readModuleAttributes(classVisitor, context, moduleOffset, modulePackagesOffset, moduleMainClass);\n }\n // Visit the NestHost attribute.\n if (nestHostClass != null) {\n classVisitor.visitNestHost(nestHostClass);\n }\n // Visit the EnclosingMethod attribute.\n if (enclosingMethodOffset != 0) {\n String className = readClass(enclosingMethodOffset, charBuffer);\n int methodIndex = readUnsignedShort(enclosingMethodOffset + 2);\n String name = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex], charBuffer);\n String type = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex] + 2, charBuffer);\n classVisitor.visitOuterClass(className, name, type);\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in ClassWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n classVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the NestedMembers attribute.\n if (nestMembersOffset != 0) {\n int numberOfNestMembers = readUnsignedShort(nestMembersOffset);\n int currentNestMemberOffset = nestMembersOffset + 2;\n while (numberOfNestMembers-- > 0) {\n classVisitor.visitNestMember(readClass(currentNestMemberOffset, charBuffer));\n currentNestMemberOffset += 2;\n }\n }\n // Visit the PermittedSubtypes attribute.\n if (permittedSubtypesOffset != 0) {\n int numberOfPermittedSubtypes = readUnsignedShort(permittedSubtypesOffset);\n int currentPermittedSubtypeOffset = permittedSubtypesOffset + 2;\n while (numberOfPermittedSubtypes-- > 0) {\n classVisitor.visitPermittedSubtypeExperimental(readClass(currentPermittedSubtypeOffset, charBuffer));\n currentPermittedSubtypeOffset += 2;\n }\n }\n // Visit the InnerClasses attribute.\n if (innerClassesOffset != 0) {\n int numberOfClasses = readUnsignedShort(innerClassesOffset);\n int currentClassesOffset = innerClassesOffset + 2;\n while (numberOfClasses-- > 0) {\n classVisitor.visitInnerClass(readClass(currentClassesOffset, charBuffer), readClass(currentClassesOffset + 2, charBuffer), readUTF8(currentClassesOffset + 4, charBuffer), readUnsignedShort(currentClassesOffset + 6));\n currentClassesOffset += 8;\n }\n }\n // Visit Record components.\n if (recordOffset != 0) {\n int recordComponentsCount = readUnsignedShort(recordOffset);\n recordOffset += 2;\n while (recordComponentsCount-- > 0) {\n recordOffset = readRecordComponent(classVisitor, context, recordOffset);\n }\n }\n // Visit the fields and methods.\n int fieldsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (fieldsCount-- > 0) {\n currentOffset = readField(classVisitor, context, currentOffset);\n }\n int methodsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (methodsCount-- > 0) {\n currentOffset = readMethod(classVisitor, context, currentOffset);\n }\n // Visit the end of the class.\n classVisitor.visitEnd();\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse modules, fields and methods\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Reads the Module, ModulePackages and ModuleMainClass attributes and visit them.\n *\n * @param classVisitor the current class visitor\n * @param context information about the class being parsed.\n * @param moduleOffset the offset of the Module attribute (excluding the attribute_info's\n * attribute_name_index and attribute_length fields).\n * @param modulePackagesOffset the offset of the ModulePackages attribute (excluding the\n * attribute_info's attribute_name_index and attribute_length fields), or 0.\n * @param moduleMainClass the string corresponding to the ModuleMainClass attribute, or {@literal\n * null}.\n */\n private void readModuleAttributes(final ClassVisitor classVisitor, final Context context, final int moduleOffset, final int modulePackagesOffset, final String moduleMainClass) {\n char[] buffer = context.charBuffer;\n // Read the module_name_index, module_flags and module_version_index fields and visit them.\n int currentOffset = moduleOffset;\n String moduleName = readModule(currentOffset, buffer);\n int moduleFlags = readUnsignedShort(currentOffset + 2);\n String moduleVersion = readUTF8(currentOffset + 4, buffer);\n currentOffset += 6;\n ModuleVisitor moduleVisitor = classVisitor.visitModule(moduleName, moduleFlags, moduleVersion);\n if (moduleVisitor == null) {\n return;\n }\n // Visit the ModuleMainClass attribute.\n if (moduleMainClass != null) {\n moduleVisitor.visitMainClass(moduleMainClass);\n }\n // Visit the ModulePackages attribute.\n if (modulePackagesOffset != 0) {\n int packageCount = readUnsignedShort(modulePackagesOffset);\n int currentPackageOffset = modulePackagesOffset + 2;\n while (packageCount-- > 0) {\n moduleVisitor.visitPackage(readPackage(currentPackageOffset, buffer));\n currentPackageOffset += 2;\n }\n }\n // Read the 'requires_count' and 'requires' fields.\n int requiresCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (requiresCount-- > 0) {\n // Read the requires_index, requires_flags and requires_version fields and visit them.\n String requires = readModule(currentOffset, buffer);\n int requiresFlags = readUnsignedShort(currentOffset + 2);\n String requiresVersion = readUTF8(currentOffset + 4, buffer);\n currentOffset += 6;\n moduleVisitor.visitRequire(requires, requiresFlags, requiresVersion);\n }\n // Read the 'exports_count' and 'exports' fields.\n int exportsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (exportsCount-- > 0) {\n // Read the exports_index, exports_flags, exports_to_count and exports_to_index fields\n // and visit them.\n String exports = readPackage(currentOffset, buffer);\n int exportsFlags = readUnsignedShort(currentOffset + 2);\n int exportsToCount = readUnsignedShort(currentOffset + 4);\n currentOffset += 6;\n String[] exportsTo = null;\n if (exportsToCount != 0) {\n exportsTo = new String[exportsToCount];\n for (int i = 0; i < exportsToCount; ++i) {\n exportsTo[i] = readModule(currentOffset, buffer);\n currentOffset += 2;\n }\n }\n moduleVisitor.visitExport(exports, exportsFlags, exportsTo);\n }\n // Reads the 'opens_count' and 'opens' fields.\n int opensCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (opensCount-- > 0) {\n // Read the opens_index, opens_flags, opens_to_count and opens_to_index fields and visit them.\n String opens = readPackage(currentOffset, buffer);\n int opensFlags = readUnsignedShort(currentOffset + 2);\n int opensToCount = readUnsignedShort(currentOffset + 4);\n currentOffset += 6;\n String[] opensTo = null;\n if (opensToCount != 0) {\n opensTo = new String[opensToCount];\n for (int i = 0; i < opensToCount; ++i) {\n opensTo[i] = readModule(currentOffset, buffer);\n currentOffset += 2;\n }\n }\n moduleVisitor.visitOpen(opens, opensFlags, opensTo);\n }\n // Read the 'uses_count' and 'uses' fields.\n int usesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (usesCount-- > 0) {\n moduleVisitor.visitUse(readClass(currentOffset, buffer));\n currentOffset += 2;\n }\n // Read the 'provides_count' and 'provides' fields.\n int providesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (providesCount-- > 0) {\n // Read the provides_index, provides_with_count and provides_with_index fields and visit them.\n String provides = readClass(currentOffset, buffer);\n int providesWithCount = readUnsignedShort(currentOffset + 2);\n currentOffset += 4;\n String[] providesWith = new String[providesWithCount];\n for (int i = 0; i < providesWithCount; ++i) {\n providesWith[i] = readClass(currentOffset, buffer);\n currentOffset += 2;\n }\n moduleVisitor.visitProvide(provides, providesWith);\n }\n // Visit the end of the module attributes.\n moduleVisitor.visitEnd();\n }\n\n /**\n * Reads a record component and visit it.\n *\n * @param classVisitor the current class visitor\n * @param context information about the class being parsed.\n * @param recordComponentOffset the offset of the current record component.\n * @return the offset of the first byte following the record component.\n */\n private int readRecordComponent(final ClassVisitor classVisitor, final Context context, final int recordComponentOffset) {\n char[] charBuffer = context.charBuffer;\n int currentOffset = recordComponentOffset;\n String name = readUTF8(currentOffset, charBuffer);\n String descriptor = readUTF8(currentOffset + 2, charBuffer);\n currentOffset += 4;\n // Read the record component attributes (the variables are ordered as in Section 4.7 of the\n // JVMS).\n int accessFlags = 0;\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The string corresponding to the Signature attribute, or null.\n String signature = null;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.SIGNATURE.equals(attributeName)) {\n signature = readUTF8(currentOffset, charBuffer);\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentOffset;\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n RecordComponentVisitor recordComponentVisitor = classVisitor.visitRecordComponentExperimental(accessFlags, name, descriptor, signature);\n if (recordComponentVisitor == null) {\n return currentOffset;\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitAnnotationExperimental(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitAnnotationExperimental(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitTypeAnnotationExperimental(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitTypeAnnotationExperimental(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in FieldWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n recordComponentVisitor.visitAttributeExperimental(attributes);\n attributes = nextAttribute;\n }\n // Visit the end of the field.\n recordComponentVisitor.visitEndExperimental();\n return currentOffset;\n }\n\n /**\n * Reads a JVMS field_info structure and makes the given visitor visit it.\n *\n * @param classVisitor the visitor that must visit the field.\n * @param context information about the class being parsed.\n * @param fieldInfoOffset the start offset of the field_info structure.\n * @return the offset of the first byte following the field_info structure.\n */\n private int readField(final ClassVisitor classVisitor, final Context context, final int fieldInfoOffset) {\n char[] charBuffer = context.charBuffer;\n // Read the access_flags, name_index and descriptor_index fields.\n int currentOffset = fieldInfoOffset;\n int accessFlags = readUnsignedShort(currentOffset);\n String name = readUTF8(currentOffset + 2, charBuffer);\n String descriptor = readUTF8(currentOffset + 4, charBuffer);\n currentOffset += 6;\n // Read the field attributes (the variables are ordered as in Section 4.7 of the JVMS).\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The value corresponding to the ConstantValue attribute, or null.\n Object constantValue = null;\n // - The string corresponding to the Signature attribute, or null.\n String signature = null;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.CONSTANT_VALUE.equals(attributeName)) {\n int constantvalueIndex = readUnsignedShort(currentOffset);\n constantValue = constantvalueIndex == 0 ? null : readConst(constantvalueIndex, charBuffer);\n } else if (Constants.SIGNATURE.equals(attributeName)) {\n signature = readUTF8(currentOffset, charBuffer);\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.SYNTHETIC.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_SYNTHETIC;\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentOffset;\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n // Visit the field declaration.\n FieldVisitor fieldVisitor = classVisitor.visitField(accessFlags, name, descriptor, signature, constantValue);\n if (fieldVisitor == null) {\n return currentOffset;\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in FieldWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n fieldVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the end of the field.\n fieldVisitor.visitEnd();\n return currentOffset;\n }\n\n /**\n * Reads a JVMS method_info structure and makes the given visitor visit it.\n *\n * @param classVisitor the visitor that must visit the method.\n * @param context information about the class being parsed.\n * @param methodInfoOffset the start offset of the method_info structure.\n * @return the offset of the first byte following the method_info structure.\n */\n private int readMethod(final ClassVisitor classVisitor, final Context context, final int methodInfoOffset) {\n char[] charBuffer = context.charBuffer;\n // Read the access_flags, name_index and descriptor_index fields.\n int currentOffset = methodInfoOffset;\n context.currentMethodAccessFlags = readUnsignedShort(currentOffset);\n context.currentMethodName = readUTF8(currentOffset + 2, charBuffer);\n context.currentMethodDescriptor = readUTF8(currentOffset + 4, charBuffer);\n currentOffset += 6;\n // Read the method attributes (the variables are ordered as in Section 4.7 of the JVMS).\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The offset of the Code attribute, or 0.\n int codeOffset = 0;\n // - The offset of the Exceptions attribute, or 0.\n int exceptionsOffset = 0;\n // - The strings corresponding to the Exceptions attribute, or null.\n String[] exceptions = null;\n // - Whether the method has a Synthetic attribute.\n boolean synthetic = false;\n // - The constant pool index contained in the Signature attribute, or 0.\n int signatureIndex = 0;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleParameterAnnotations attribute, or 0.\n int runtimeVisibleParameterAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleParameterAnnotations attribute, or 0.\n int runtimeInvisibleParameterAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The offset of the AnnotationDefault attribute, or 0.\n int annotationDefaultOffset = 0;\n // - The offset of the MethodParameters attribute, or 0.\n int methodParametersOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.CODE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_CODE) == 0) {\n codeOffset = currentOffset;\n }\n } else if (Constants.EXCEPTIONS.equals(attributeName)) {\n exceptionsOffset = currentOffset;\n exceptions = new String[readUnsignedShort(exceptionsOffset)];\n int currentExceptionOffset = exceptionsOffset + 2;\n for (int i = 0; i < exceptions.length; ++i) {\n exceptions[i] = readClass(currentExceptionOffset, charBuffer);\n currentExceptionOffset += 2;\n }\n } else if (Constants.SIGNATURE.equals(attributeName)) {\n signatureIndex = readUnsignedShort(currentOffset);\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n context.currentMethodAccessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.ANNOTATION_DEFAULT.equals(attributeName)) {\n annotationDefaultOffset = currentOffset;\n } else if (Constants.SYNTHETIC.equals(attributeName)) {\n synthetic = true;\n context.currentMethodAccessFlags |= Opcodes.ACC_SYNTHETIC;\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleParameterAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleParameterAnnotationsOffset = currentOffset;\n } else if (Constants.METHOD_PARAMETERS.equals(attributeName)) {\n methodParametersOffset = currentOffset;\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n // Visit the method declaration.\n MethodVisitor methodVisitor = classVisitor.visitMethod(context.currentMethodAccessFlags, context.currentMethodName, context.currentMethodDescriptor, signatureIndex == 0 ? null : readUtf(signatureIndex, charBuffer), exceptions);\n if (methodVisitor == null) {\n return currentOffset;\n }\n // If the returned MethodVisitor is in fact a MethodWriter, it means there is no method\n // adapter between the reader and the writer. In this case, it might be possible to copy\n // the method attributes directly into the writer. If so, return early without visiting\n // the content of these attributes.\n if (methodVisitor instanceof MethodWriter) {\n MethodWriter methodWriter = (MethodWriter) methodVisitor;\n if (methodWriter.canCopyMethodAttributes(this, synthetic, (context.currentMethodAccessFlags & Opcodes.ACC_DEPRECATED) != 0, readUnsignedShort(methodInfoOffset + 4), signatureIndex, exceptionsOffset)) {\n methodWriter.setMethodAttributesSource(methodInfoOffset, currentOffset - methodInfoOffset);\n return currentOffset;\n }\n }\n // Visit the MethodParameters attribute.\n if (methodParametersOffset != 0 && (context.parsingOptions & SKIP_DEBUG) == 0) {\n int parametersCount = readByte(methodParametersOffset);\n int currentParameterOffset = methodParametersOffset + 1;\n while (parametersCount-- > 0) {\n // Read the name_index and access_flags fields and visit them.\n methodVisitor.visitParameter(readUTF8(currentParameterOffset, charBuffer), readUnsignedShort(currentParameterOffset + 2));\n currentParameterOffset += 4;\n }\n }\n // Visit the AnnotationDefault attribute.\n if (annotationDefaultOffset != 0) {\n AnnotationVisitor annotationVisitor = methodVisitor.visitAnnotationDefault();\n readElementValue(annotationVisitor, annotationDefaultOffset, null, charBuffer);\n if (annotationVisitor != null) {\n annotationVisitor.visitEnd();\n }\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleParameterAnnotations attribute.\n if (runtimeVisibleParameterAnnotationsOffset != 0) {\n readParameterAnnotations(methodVisitor, context, runtimeVisibleParameterAnnotationsOffset, /* visible = */ true);\n }\n // Visit the RuntimeInvisibleParameterAnnotations attribute.\n if (runtimeInvisibleParameterAnnotationsOffset != 0) {\n readParameterAnnotations(methodVisitor, context, runtimeInvisibleParameterAnnotationsOffset,\n /* visible = */ false);\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in MethodWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n methodVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the Code attribute.\n if (codeOffset != 0) {\n methodVisitor.visitCode();\n readCode(methodVisitor, context, codeOffset);\n }\n // Visit the end of the method.\n methodVisitor.visitEnd();\n return currentOffset;\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse a Code attribute\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Reads a JVMS 'Code' attribute and makes the given visitor visit it.\n *\n * @param methodVisitor the visitor that must visit the Code attribute.\n * @param context information about the class being parsed.\n * @param codeOffset the start offset in {@link #classFileBuffer} of the Code attribute, excluding\n * its attribute_name_index and attribute_length fields.\n */\n private void readCode(final MethodVisitor methodVisitor, final Context context, final int codeOffset) {\n int currentOffset = codeOffset;\n // Read the max_stack, max_locals and code_length fields.\n final byte[] classBuffer = classFileBuffer;\n final char[] charBuffer = context.charBuffer;\n final int maxStack = readUnsignedShort(currentOffset);\n final int maxLocals = readUnsignedShort(currentOffset + 2);\n final int codeLength = readInt(currentOffset + 4);\n currentOffset += 8;\n // Read the bytecode 'code' array to create a label for each referenced instruction.\n final int bytecodeStartOffset = currentOffset;\n final int bytecodeEndOffset = currentOffset + codeLength;\n final Label[] labels = context.currentMethodLabels = new Label[codeLength + 1];\n while (currentOffset < bytecodeEndOffset) {\n final int bytecodeOffset = currentOffset - bytecodeStartOffset;\n final int opcode = classBuffer[currentOffset] & 0xFF;\n switch (opcode) {\n case Constants.NOP:\n case Constants.ACONST_NULL:\n case Constants.ICONST_M1:\n case Constants.ICONST_0:\n case Constants.ICONST_1:\n case Constants.ICONST_2:\n case Constants.ICONST_3:\n case Constants.ICONST_4:\n case Constants.ICONST_5:\n case Constants.LCONST_0:\n case Constants.LCONST_1:\n case Constants.FCONST_0:\n case Constants.FCONST_1:\n case Constants.FCONST_2:\n case Constants.DCONST_0:\n case Constants.DCONST_1:\n case Constants.IALOAD:\n case Constants.LALOAD:\n case Constants.FALOAD:\n case Constants.DALOAD:\n case Constants.AALOAD:\n case Constants.BALOAD:\n case Constants.CALOAD:\n case Constants.SALOAD:\n case Constants.IASTORE:\n case Constants.LASTORE:\n case Constants.FASTORE:\n case Constants.DASTORE:\n case Constants.AASTORE:\n case Constants.BASTORE:\n case Constants.CASTORE:\n case Constants.SASTORE:\n case Constants.POP:\n case Constants.POP2:\n case Constants.DUP:\n case Constants.DUP_X1:\n case Constants.DUP_X2:\n case Constants.DUP2:\n case Constants.DUP2_X1:\n case Constants.DUP2_X2:\n case Constants.SWAP:\n case Constants.IADD:\n case Constants.LADD:\n case Constants.FADD:\n case Constants.DADD:\n case Constants.ISUB:\n case Constants.LSUB:\n case Constants.FSUB:\n case Constants.DSUB:\n case Constants.IMUL:\n case Constants.LMUL:\n case Constants.FMUL:\n case Constants.DMUL:\n case Constants.IDIV:\n case Constants.LDIV:\n case Constants.FDIV:\n case Constants.DDIV:\n case Constants.IREM:\n case Constants.LREM:\n case Constants.FREM:\n case Constants.DREM:\n case Constants.INEG:\n case Constants.LNEG:\n case Constants.FNEG:\n case Constants.DNEG:\n case Constants.ISHL:\n case Constants.LSHL:\n case Constants.ISHR:\n case Constants.LSHR:\n case Constants.IUSHR:\n case Constants.LUSHR:\n case Constants.IAND:\n case Constants.LAND:\n case Constants.IOR:\n case Constants.LOR:\n case Constants.IXOR:\n case Constants.LXOR:\n case Constants.I2L:\n case Constants.I2F:\n case Constants.I2D:\n case Constants.L2I:\n case Constants.L2F:\n case Constants.L2D:\n case Constants.F2I:\n case Constants.F2L:\n case Constants.F2D:\n case Constants.D2I:\n case Constants.D2L:\n case Constants.D2F:\n case Constants.I2B:\n case Constants.I2C:\n case Constants.I2S:\n case Constants.LCMP:\n case Constants.FCMPL:\n case Constants.FCMPG:\n case Constants.DCMPL:\n case Constants.DCMPG:\n case Constants.IRETURN:\n case Constants.LRETURN:\n case Constants.FRETURN:\n case Constants.DRETURN:\n case Constants.ARETURN:\n case Constants.RETURN:\n case Constants.ARRAYLENGTH:\n case Constants.ATHROW:\n case Constants.MONITORENTER:\n case Constants.MONITOREXIT:\n case Constants.ILOAD_0:\n case Constants.ILOAD_1:\n case Constants.ILOAD_2:\n case Constants.ILOAD_3:\n case Constants.LLOAD_0:\n case Constants.LLOAD_1:\n case Constants.LLOAD_2:\n case Constants.LLOAD_3:\n case Constants.FLOAD_0:\n case Constants.FLOAD_1:\n case Constants.FLOAD_2:\n case Constants.FLOAD_3:\n case Constants.DLOAD_0:\n case Constants.DLOAD_1:\n case Constants.DLOAD_2:\n case Constants.DLOAD_3:\n case Constants.ALOAD_0:\n case Constants.ALOAD_1:\n case Constants.ALOAD_2:\n case Constants.ALOAD_3:\n case Constants.ISTORE_0:\n case Constants.ISTORE_1:\n case Constants.ISTORE_2:\n case Constants.ISTORE_3:\n case Constants.LSTORE_0:\n case Constants.LSTORE_1:\n case Constants.LSTORE_2:\n case Constants.LSTORE_3:\n case Constants.FSTORE_0:\n case Constants.FSTORE_1:\n case Constants.FSTORE_2:\n case Constants.FSTORE_3:\n case Constants.DSTORE_0:\n case Constants.DSTORE_1:\n case Constants.DSTORE_2:\n case Constants.DSTORE_3:\n case Constants.ASTORE_0:\n case Constants.ASTORE_1:\n case Constants.ASTORE_2:\n case Constants.ASTORE_3:\n currentOffset += 1;\n break;\n case Constants.IFEQ:\n case Constants.IFNE:\n case Constants.IFLT:\n case Constants.IFGE:\n case Constants.IFGT:\n case Constants.IFLE:\n case Constants.IF_ICMPEQ:\n case Constants.IF_ICMPNE:\n case Constants.IF_ICMPLT:\n case Constants.IF_ICMPGE:\n case Constants.IF_ICMPGT:\n case Constants.IF_ICMPLE:\n case Constants.IF_ACMPEQ:\n case Constants.IF_ACMPNE:\n case Constants.GOTO:\n case Constants.JSR:\n case Constants.IFNULL:\n case Constants.IFNONNULL:\n createLabel(bytecodeOffset + readShort(currentOffset + 1), labels);\n currentOffset += 3;\n break;\n case Constants.ASM_IFEQ:\n case Constants.ASM_IFNE:\n case Constants.ASM_IFLT:\n case Constants.ASM_IFGE:\n case Constants.ASM_IFGT:\n case Constants.ASM_IFLE:\n case Constants.ASM_IF_ICMPEQ:\n case Constants.ASM_IF_ICMPNE:\n case Constants.ASM_IF_ICMPLT:\n case Constants.ASM_IF_ICMPGE:\n case Constants.ASM_IF_ICMPGT:\n case Constants.ASM_IF_ICMPLE:\n case Constants.ASM_IF_ACMPEQ:\n case Constants.ASM_IF_ACMPNE:\n case Constants.ASM_GOTO:\n case Constants.ASM_JSR:\n case Constants.ASM_IFNULL:\n case Constants.ASM_IFNONNULL:\n createLabel(bytecodeOffset + readUnsignedShort(currentOffset + 1), labels);\n currentOffset += 3;\n break;\n case Constants.GOTO_W:\n case Constants.JSR_W:\n case Constants.ASM_GOTO_W:\n createLabel(bytecodeOffset + readInt(currentOffset + 1), labels);\n currentOffset += 5;\n break;\n case Constants.WIDE:\n switch (classBuffer[currentOffset + 1] & 0xFF) {\n case Constants.ILOAD:\n case Constants.FLOAD:\n case Constants.ALOAD:\n case Constants.LLOAD:\n case Constants.DLOAD:\n case Constants.ISTORE:\n case Constants.FSTORE:\n case Constants.ASTORE:\n case Constants.LSTORE:\n case Constants.DSTORE:\n case Constants.RET:\n currentOffset += 4;\n break;\n case Constants.IINC:\n currentOffset += 6;\n break;\n default:\n throw new IllegalArgumentException();\n }\n break;\n case Constants.TABLESWITCH:\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (bytecodeOffset & 3);\n // Read the default label and the number of table entries.\n createLabel(bytecodeOffset + readInt(currentOffset), labels);\n int numTableEntries = readInt(currentOffset + 8) - readInt(currentOffset + 4) + 1;\n currentOffset += 12;\n // Read the table labels.\n while (numTableEntries-- > 0) {\n createLabel(bytecodeOffset + readInt(currentOffset), labels);\n currentOffset += 4;\n }\n break;\n case Constants.LOOKUPSWITCH:\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (bytecodeOffset & 3);\n // Read the default label and the number of switch cases.\n createLabel(bytecodeOffset + readInt(currentOffset), labels);\n int numSwitchCases = readInt(currentOffset + 4);\n currentOffset += 8;\n // Read the switch labels.\n while (numSwitchCases-- > 0) {\n createLabel(bytecodeOffset + readInt(currentOffset + 4), labels);\n currentOffset += 8;\n }\n break;\n case Constants.ILOAD:\n case Constants.LLOAD:\n case Constants.FLOAD:\n case Constants.DLOAD:\n case Constants.ALOAD:\n case Constants.ISTORE:\n case Constants.LSTORE:\n case Constants.FSTORE:\n case Constants.DSTORE:\n case Constants.ASTORE:\n case Constants.RET:\n case Constants.BIPUSH:\n case Constants.NEWARRAY:\n case Constants.LDC:\n currentOffset += 2;\n break;\n case Constants.SIPUSH:\n case Constants.LDC_W:\n case Constants.LDC2_W:\n case Constants.GETSTATIC:\n case Constants.PUTSTATIC:\n case Constants.GETFIELD:\n case Constants.PUTFIELD:\n case Constants.INVOKEVIRTUAL:\n case Constants.INVOKESPECIAL:\n case Constants.INVOKESTATIC:\n case Constants.NEW:\n case Constants.ANEWARRAY:\n case Constants.CHECKCAST:\n case Constants.INSTANCEOF:\n case Constants.IINC:\n currentOffset += 3;\n break;\n case Constants.INVOKEINTERFACE:\n case Constants.INVOKEDYNAMIC:\n currentOffset += 5;\n break;\n case Constants.MULTIANEWARRAY:\n currentOffset += 4;\n break;\n default:\n throw new IllegalArgumentException();\n }\n }\n // Read the 'exception_table_length' and 'exception_table' field to create a label for each\n // referenced instruction, and to make methodVisitor visit the corresponding try catch blocks.\n int exceptionTableLength = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (exceptionTableLength-- > 0) {\n Label start = createLabel(readUnsignedShort(currentOffset), labels);\n Label end = createLabel(readUnsignedShort(currentOffset + 2), labels);\n Label handler = createLabel(readUnsignedShort(currentOffset + 4), labels);\n String catchType = readUTF8(cpInfoOffsets[readUnsignedShort(currentOffset + 6)], charBuffer);\n currentOffset += 8;\n methodVisitor.visitTryCatchBlock(start, end, handler, catchType);\n }\n // Read the Code attributes to create a label for each referenced instruction (the variables\n // are ordered as in Section 4.7 of the JVMS). Attribute offsets exclude the\n // attribute_name_index and attribute_length fields.\n // - The offset of the current 'stack_map_frame' in the StackMap[Table] attribute, or 0.\n // Initially, this is the offset of the first 'stack_map_frame' entry. Then this offset is\n // updated after each stack_map_frame is read.\n int stackMapFrameOffset = 0;\n // - The end offset of the StackMap[Table] attribute, or 0.\n int stackMapTableEndOffset = 0;\n // - Whether the stack map frames are compressed (i.e. in a StackMapTable) or not.\n boolean compressedFrames = true;\n // - The offset of the LocalVariableTable attribute, or 0.\n int localVariableTableOffset = 0;\n // - The offset of the LocalVariableTypeTable attribute, or 0.\n int localVariableTypeTableOffset = 0;\n // - The offset of each 'type_annotation' entry in the RuntimeVisibleTypeAnnotations\n // attribute, or null.\n int[] visibleTypeAnnotationOffsets = null;\n // - The offset of each 'type_annotation' entry in the RuntimeInvisibleTypeAnnotations\n // attribute, or null.\n int[] invisibleTypeAnnotationOffsets = null;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n if (Constants.LOCAL_VARIABLE_TABLE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_DEBUG) == 0) {\n localVariableTableOffset = currentOffset;\n // Parse the attribute to find the corresponding (debug only) labels.\n int currentLocalVariableTableOffset = currentOffset;\n int localVariableTableLength = readUnsignedShort(currentLocalVariableTableOffset);\n currentLocalVariableTableOffset += 2;\n while (localVariableTableLength-- > 0) {\n int startPc = readUnsignedShort(currentLocalVariableTableOffset);\n createDebugLabel(startPc, labels);\n int length = readUnsignedShort(currentLocalVariableTableOffset + 2);\n createDebugLabel(startPc + length, labels);\n // Skip the name_index, descriptor_index and index fields (2 bytes each).\n currentLocalVariableTableOffset += 10;\n }\n }\n } else if (Constants.LOCAL_VARIABLE_TYPE_TABLE.equals(attributeName)) {\n localVariableTypeTableOffset = currentOffset;\n // Here we do not extract the labels corresponding to the attribute content. We assume they\n // are the same or a subset of those of the LocalVariableTable attribute.\n } else if (Constants.LINE_NUMBER_TABLE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_DEBUG) == 0) {\n // Parse the attribute to find the corresponding (debug only) labels.\n int currentLineNumberTableOffset = currentOffset;\n int lineNumberTableLength = readUnsignedShort(currentLineNumberTableOffset);\n currentLineNumberTableOffset += 2;\n while (lineNumberTableLength-- > 0) {\n int startPc = readUnsignedShort(currentLineNumberTableOffset);\n int lineNumber = readUnsignedShort(currentLineNumberTableOffset + 2);\n currentLineNumberTableOffset += 4;\n createDebugLabel(startPc, labels);\n labels[startPc].addLineNumber(lineNumber);\n }\n }\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n visibleTypeAnnotationOffsets = readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ true);\n // Here we do not extract the labels corresponding to the attribute content. This would\n // require a full parsing of the attribute, which would need to be repeated when parsing\n // the bytecode instructions (see below). Instead, the content of the attribute is read one\n // type annotation at a time (i.e. after a type annotation has been visited, the next type\n // annotation is read), and the labels it contains are also extracted one annotation at a\n // time. This assumes that type annotations are ordered by increasing bytecode offset.\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n invisibleTypeAnnotationOffsets = readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ false);\n // Same comment as above for the RuntimeVisibleTypeAnnotations attribute.\n } else if (Constants.STACK_MAP_TABLE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_FRAMES) == 0) {\n stackMapFrameOffset = currentOffset + 2;\n stackMapTableEndOffset = currentOffset + attributeLength;\n }\n // Here we do not extract the labels corresponding to the attribute content. This would\n // require a full parsing of the attribute, which would need to be repeated when parsing\n // the bytecode instructions (see below). Instead, the content of the attribute is read one\n // frame at a time (i.e. after a frame has been visited, the next frame is read), and the\n // labels it contains are also extracted one frame at a time. Thanks to the ordering of\n // frames, having only a \"one frame lookahead\" is not a problem, i.e. it is not possible to\n // see an offset smaller than the offset of the current instruction and for which no Label\n // exist. Except for UNINITIALIZED type offsets. We solve this by parsing the stack map\n // table without a full decoding (see below).\n } else if (\"StackMap\".equals(attributeName)) {\n if ((context.parsingOptions & SKIP_FRAMES) == 0) {\n stackMapFrameOffset = currentOffset + 2;\n stackMapTableEndOffset = currentOffset + attributeLength;\n compressedFrames = false;\n }\n // IMPORTANT! Here we assume that the frames are ordered, as in the StackMapTable attribute,\n // although this is not guaranteed by the attribute format. This allows an incremental\n // extraction of the labels corresponding to this attribute (see the comment above for the\n // StackMapTable attribute).\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, codeOffset, labels);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n // Initialize the context fields related to stack map frames, and generate the first\n // (implicit) stack map frame, if needed.\n final boolean expandFrames = (context.parsingOptions & EXPAND_FRAMES) != 0;\n if (stackMapFrameOffset != 0) {\n // The bytecode offset of the first explicit frame is not offset_delta + 1 but only\n // offset_delta. Setting the implicit frame offset to -1 allows us to use of the\n // \"offset_delta + 1\" rule in all cases.\n context.currentFrameOffset = -1;\n context.currentFrameType = 0;\n context.currentFrameLocalCount = 0;\n context.currentFrameLocalCountDelta = 0;\n context.currentFrameLocalTypes = new Object[maxLocals];\n context.currentFrameStackCount = 0;\n context.currentFrameStackTypes = new Object[maxStack];\n if (expandFrames) {\n computeImplicitFrame(context);\n }\n // Find the labels for UNINITIALIZED frame types. Instead of decoding each element of the\n // stack map table, we look for 3 consecutive bytes that \"look like\" an UNINITIALIZED type\n // (tag ITEM_Uninitialized, offset within bytecode bounds, NEW instruction at this offset).\n // We may find false positives (i.e. not real UNINITIALIZED types), but this should be rare,\n // and the only consequence will be the creation of an unneeded label. This is better than\n // creating a label for each NEW instruction, and faster than fully decoding the whole stack\n // map table.\n for (int offset = stackMapFrameOffset; offset < stackMapTableEndOffset - 2; ++offset) {\n if (classBuffer[offset] == Frame.ITEM_UNINITIALIZED) {\n int potentialBytecodeOffset = readUnsignedShort(offset + 1);\n if (potentialBytecodeOffset >= 0 && potentialBytecodeOffset < codeLength && (classBuffer[bytecodeStartOffset + potentialBytecodeOffset] & 0xFF) == Opcodes.NEW) {\n createLabel(potentialBytecodeOffset, labels);\n }\n }\n }\n }\n if (expandFrames && (context.parsingOptions & EXPAND_ASM_INSNS) != 0) {\n // Expanding the ASM specific instructions can introduce F_INSERT frames, even if the method\n // does not currently have any frame. These inserted frames must be computed by simulating the\n // effect of the bytecode instructions, one by one, starting from the implicit first frame.\n // For this, MethodWriter needs to know maxLocals before the first instruction is visited. To\n // ensure this, we visit the implicit first frame here (passing only maxLocals - the rest is\n // computed in MethodWriter).\n methodVisitor.visitFrame(Opcodes.F_NEW, maxLocals, null, 0, null);\n }\n // Visit the bytecode instructions. First, introduce state variables for the incremental parsing\n // of the type annotations.\n // Index of the next runtime visible type annotation to read (in the\n // visibleTypeAnnotationOffsets array).\n int currentVisibleTypeAnnotationIndex = 0;\n // The bytecode offset of the next runtime visible type annotation to read, or -1.\n int currentVisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(visibleTypeAnnotationOffsets, 0);\n // Index of the next runtime invisible type annotation to read (in the\n // invisibleTypeAnnotationOffsets array).\n int currentInvisibleTypeAnnotationIndex = 0;\n // The bytecode offset of the next runtime invisible type annotation to read, or -1.\n int currentInvisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(invisibleTypeAnnotationOffsets, 0);\n // Whether a F_INSERT stack map frame must be inserted before the current instruction.\n boolean insertFrame = false;\n // The delta to subtract from a goto_w or jsr_w opcode to get the corresponding goto or jsr\n // opcode, or 0 if goto_w and jsr_w must be left unchanged (i.e. when expanding ASM specific\n // instructions).\n final int wideJumpOpcodeDelta = (context.parsingOptions & EXPAND_ASM_INSNS) == 0 ? Constants.WIDE_JUMP_OPCODE_DELTA : 0;\n currentOffset = bytecodeStartOffset;\n while (currentOffset < bytecodeEndOffset) {\n final int currentBytecodeOffset = currentOffset - bytecodeStartOffset;\n // Visit the label and the line number(s) for this bytecode offset, if any.\n Label currentLabel = labels[currentBytecodeOffset];\n if (currentLabel != null) {\n currentLabel.accept(methodVisitor, (context.parsingOptions & SKIP_DEBUG) == 0);\n }\n // Visit the stack map frame for this bytecode offset, if any.\n while (stackMapFrameOffset != 0 && (context.currentFrameOffset == currentBytecodeOffset || context.currentFrameOffset == -1)) {\n // If there is a stack map frame for this offset, make methodVisitor visit it, and read the\n // next stack map frame if there is one.\n if (context.currentFrameOffset != -1) {\n if (!compressedFrames || expandFrames) {\n methodVisitor.visitFrame(Opcodes.F_NEW, context.currentFrameLocalCount, context.currentFrameLocalTypes, context.currentFrameStackCount, context.currentFrameStackTypes);\n } else {\n methodVisitor.visitFrame(context.currentFrameType, context.currentFrameLocalCountDelta, context.currentFrameLocalTypes, context.currentFrameStackCount, context.currentFrameStackTypes);\n }\n // Since there is already a stack map frame for this bytecode offset, there is no need to\n // insert a new one.\n insertFrame = false;\n }\n if (stackMapFrameOffset < stackMapTableEndOffset) {\n stackMapFrameOffset = readStackMapFrame(stackMapFrameOffset, compressedFrames, expandFrames, context);\n } else {\n stackMapFrameOffset = 0;\n }\n }\n // Insert a stack map frame for this bytecode offset, if requested by setting insertFrame to\n // true during the previous iteration. The actual frame content is computed in MethodWriter.\n if (insertFrame) {\n if ((context.parsingOptions & EXPAND_FRAMES) != 0) {\n methodVisitor.visitFrame(Constants.F_INSERT, 0, null, 0, null);\n }\n insertFrame = false;\n }\n // Visit the instruction at this bytecode offset.\n int opcode = classBuffer[currentOffset] & 0xFF;\n switch (opcode) {\n case Constants.NOP:\n case Constants.ACONST_NULL:\n case Constants.ICONST_M1:\n case Constants.ICONST_0:\n case Constants.ICONST_1:\n case Constants.ICONST_2:\n case Constants.ICONST_3:\n case Constants.ICONST_4:\n case Constants.ICONST_5:\n case Constants.LCONST_0:\n case Constants.LCONST_1:\n case Constants.FCONST_0:\n case Constants.FCONST_1:\n case Constants.FCONST_2:\n case Constants.DCONST_0:\n case Constants.DCONST_1:\n case Constants.IALOAD:\n case Constants.LALOAD:\n case Constants.FALOAD:\n case Constants.DALOAD:\n case Constants.AALOAD:\n case Constants.BALOAD:\n case Constants.CALOAD:\n case Constants.SALOAD:\n case Constants.IASTORE:\n case Constants.LASTORE:\n case Constants.FASTORE:\n case Constants.DASTORE:\n case Constants.AASTORE:\n case Constants.BASTORE:\n case Constants.CASTORE:\n case Constants.SASTORE:\n case Constants.POP:\n case Constants.POP2:\n case Constants.DUP:\n case Constants.DUP_X1:\n case Constants.DUP_X2:\n case Constants.DUP2:\n case Constants.DUP2_X1:\n case Constants.DUP2_X2:\n case Constants.SWAP:\n case Constants.IADD:\n case Constants.LADD:\n case Constants.FADD:\n case Constants.DADD:\n case Constants.ISUB:\n case Constants.LSUB:\n case Constants.FSUB:\n case Constants.DSUB:\n case Constants.IMUL:\n case Constants.LMUL:\n case Constants.FMUL:\n case Constants.DMUL:\n case Constants.IDIV:\n case Constants.LDIV:\n case Constants.FDIV:\n case Constants.DDIV:\n case Constants.IREM:\n case Constants.LREM:\n case Constants.FREM:\n case Constants.DREM:\n case Constants.INEG:\n case Constants.LNEG:\n case Constants.FNEG:\n case Constants.DNEG:\n case Constants.ISHL:\n case Constants.LSHL:\n case Constants.ISHR:\n case Constants.LSHR:\n case Constants.IUSHR:\n case Constants.LUSHR:\n case Constants.IAND:\n case Constants.LAND:\n case Constants.IOR:\n case Constants.LOR:\n case Constants.IXOR:\n case Constants.LXOR:\n case Constants.I2L:\n case Constants.I2F:\n case Constants.I2D:\n case Constants.L2I:\n case Constants.L2F:\n case Constants.L2D:\n case Constants.F2I:\n case Constants.F2L:\n case Constants.F2D:\n case Constants.D2I:\n case Constants.D2L:\n case Constants.D2F:\n case Constants.I2B:\n case Constants.I2C:\n case Constants.I2S:\n case Constants.LCMP:\n case Constants.FCMPL:\n case Constants.FCMPG:\n case Constants.DCMPL:\n case Constants.DCMPG:\n case Constants.IRETURN:\n case Constants.LRETURN:\n case Constants.FRETURN:\n case Constants.DRETURN:\n case Constants.ARETURN:\n case Constants.RETURN:\n case Constants.ARRAYLENGTH:\n case Constants.ATHROW:\n case Constants.MONITORENTER:\n case Constants.MONITOREXIT:\n methodVisitor.visitInsn(opcode);\n currentOffset += 1;\n break;\n case Constants.ILOAD_0:\n case Constants.ILOAD_1:\n case Constants.ILOAD_2:\n case Constants.ILOAD_3:\n case Constants.LLOAD_0:\n case Constants.LLOAD_1:\n case Constants.LLOAD_2:\n case Constants.LLOAD_3:\n case Constants.FLOAD_0:\n case Constants.FLOAD_1:\n case Constants.FLOAD_2:\n case Constants.FLOAD_3:\n case Constants.DLOAD_0:\n case Constants.DLOAD_1:\n case Constants.DLOAD_2:\n case Constants.DLOAD_3:\n case Constants.ALOAD_0:\n case Constants.ALOAD_1:\n case Constants.ALOAD_2:\n case Constants.ALOAD_3:\n opcode -= Constants.ILOAD_0;\n methodVisitor.visitVarInsn(Opcodes.ILOAD + (opcode >> 2), opcode & 0x3);\n currentOffset += 1;\n break;\n case Constants.ISTORE_0:\n case Constants.ISTORE_1:\n case Constants.ISTORE_2:\n case Constants.ISTORE_3:\n case Constants.LSTORE_0:\n case Constants.LSTORE_1:\n case Constants.LSTORE_2:\n case Constants.LSTORE_3:\n case Constants.FSTORE_0:\n case Constants.FSTORE_1:\n case Constants.FSTORE_2:\n case Constants.FSTORE_3:\n case Constants.DSTORE_0:\n case Constants.DSTORE_1:\n case Constants.DSTORE_2:\n case Constants.DSTORE_3:\n case Constants.ASTORE_0:\n case Constants.ASTORE_1:\n case Constants.ASTORE_2:\n case Constants.ASTORE_3:\n opcode -= Constants.ISTORE_0;\n methodVisitor.visitVarInsn(Opcodes.ISTORE + (opcode >> 2), opcode & 0x3);\n currentOffset += 1;\n break;\n case Constants.IFEQ:\n case Constants.IFNE:\n case Constants.IFLT:\n case Constants.IFGE:\n case Constants.IFGT:\n case Constants.IFLE:\n case Constants.IF_ICMPEQ:\n case Constants.IF_ICMPNE:\n case Constants.IF_ICMPLT:\n case Constants.IF_ICMPGE:\n case Constants.IF_ICMPGT:\n case Constants.IF_ICMPLE:\n case Constants.IF_ACMPEQ:\n case Constants.IF_ACMPNE:\n case Constants.GOTO:\n case Constants.JSR:\n case Constants.IFNULL:\n case Constants.IFNONNULL:\n methodVisitor.visitJumpInsn(opcode, labels[currentBytecodeOffset + readShort(currentOffset + 1)]);\n currentOffset += 3;\n break;\n case Constants.GOTO_W:\n case Constants.JSR_W:\n methodVisitor.visitJumpInsn(opcode - wideJumpOpcodeDelta, labels[currentBytecodeOffset + readInt(currentOffset + 1)]);\n currentOffset += 5;\n break;\n case Constants.ASM_IFEQ:\n case Constants.ASM_IFNE:\n case Constants.ASM_IFLT:\n case Constants.ASM_IFGE:\n case Constants.ASM_IFGT:\n case Constants.ASM_IFLE:\n case Constants.ASM_IF_ICMPEQ:\n case Constants.ASM_IF_ICMPNE:\n case Constants.ASM_IF_ICMPLT:\n case Constants.ASM_IF_ICMPGE:\n case Constants.ASM_IF_ICMPGT:\n case Constants.ASM_IF_ICMPLE:\n case Constants.ASM_IF_ACMPEQ:\n case Constants.ASM_IF_ACMPNE:\n case Constants.ASM_GOTO:\n case Constants.ASM_JSR:\n case Constants.ASM_IFNULL:\n case Constants.ASM_IFNONNULL: {\n // A forward jump with an offset > 32767. In this case we automatically replace ASM_GOTO\n // with GOTO_W, ASM_JSR with JSR_W and ASM_IFxxx with IFNOTxxx GOTO_W L:...,\n // where IFNOTxxx is the \"opposite\" opcode of ASMS_IFxxx (e.g. IFNE for ASM_IFEQ) and\n // where designates the instruction just after the GOTO_W.\n // First, change the ASM specific opcodes ASM_IFEQ ... ASM_JSR, ASM_IFNULL and\n // ASM_IFNONNULL to IFEQ ... JSR, IFNULL and IFNONNULL.\n opcode = opcode < Constants.ASM_IFNULL ? opcode - Constants.ASM_OPCODE_DELTA : opcode - Constants.ASM_IFNULL_OPCODE_DELTA;\n Label target = labels[currentBytecodeOffset + readUnsignedShort(currentOffset + 1)];\n if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) {\n // Replace GOTO with GOTO_W and JSR with JSR_W.\n methodVisitor.visitJumpInsn(opcode + Constants.WIDE_JUMP_OPCODE_DELTA, target);\n } else {\n // Compute the \"opposite\" of opcode. This can be done by flipping the least\n // significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ\n // (with a pre and post offset by 1).\n opcode = opcode < Opcodes.GOTO ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1;\n Label endif = createLabel(currentBytecodeOffset + 3, labels);\n methodVisitor.visitJumpInsn(opcode, endif);\n methodVisitor.visitJumpInsn(Constants.GOTO_W, target);\n // endif designates the instruction just after GOTO_W, and is visited as part of the\n // next instruction. Since it is a jump target, we need to insert a frame here.\n insertFrame = true;\n }\n currentOffset += 3;\n break;\n }\n case Constants.ASM_GOTO_W:\n // Replace ASM_GOTO_W with GOTO_W.\n methodVisitor.visitJumpInsn(Constants.GOTO_W, labels[currentBytecodeOffset + readInt(currentOffset + 1)]);\n // The instruction just after is a jump target (because ASM_GOTO_W is used in patterns\n // IFNOTxxx ASM_GOTO_W L:..., see MethodWriter), so we need to insert a frame\n // here.\n insertFrame = true;\n currentOffset += 5;\n break;\n case Constants.WIDE:\n opcode = classBuffer[currentOffset + 1] & 0xFF;\n if (opcode == Opcodes.IINC) {\n methodVisitor.visitIincInsn(readUnsignedShort(currentOffset + 2), readShort(currentOffset + 4));\n currentOffset += 6;\n } else {\n methodVisitor.visitVarInsn(opcode, readUnsignedShort(currentOffset + 2));\n currentOffset += 4;\n }\n break;\n case Constants.TABLESWITCH: {\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (currentBytecodeOffset & 3);\n // Read the instruction.\n Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)];\n int low = readInt(currentOffset + 4);\n int high = readInt(currentOffset + 8);\n currentOffset += 12;\n Label[] table = new Label[high - low + 1];\n for (int i = 0; i < table.length; ++i) {\n table[i] = labels[currentBytecodeOffset + readInt(currentOffset)];\n currentOffset += 4;\n }\n methodVisitor.visitTableSwitchInsn(low, high, defaultLabel, table);\n break;\n }\n case Constants.LOOKUPSWITCH: {\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (currentBytecodeOffset & 3);\n // Read the instruction.\n Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)];\n int numPairs = readInt(currentOffset + 4);\n currentOffset += 8;\n int[] keys = new int[numPairs];\n Label[] values = new Label[numPairs];\n for (int i = 0; i < numPairs; ++i) {\n keys[i] = readInt(currentOffset);\n values[i] = labels[currentBytecodeOffset + readInt(currentOffset + 4)];\n currentOffset += 8;\n }\n methodVisitor.visitLookupSwitchInsn(defaultLabel, keys, values);\n break;\n }\n case Constants.ILOAD:\n case Constants.LLOAD:\n case Constants.FLOAD:\n case Constants.DLOAD:\n case Constants.ALOAD:\n case Constants.ISTORE:\n case Constants.LSTORE:\n case Constants.FSTORE:\n case Constants.DSTORE:\n case Constants.ASTORE:\n case Constants.RET:\n methodVisitor.visitVarInsn(opcode, classBuffer[currentOffset + 1] & 0xFF);\n currentOffset += 2;\n break;\n case Constants.BIPUSH:\n case Constants.NEWARRAY:\n methodVisitor.visitIntInsn(opcode, classBuffer[currentOffset + 1]);\n currentOffset += 2;\n break;\n case Constants.SIPUSH:\n methodVisitor.visitIntInsn(opcode, readShort(currentOffset + 1));\n currentOffset += 3;\n break;\n case Constants.LDC:\n methodVisitor.visitLdcInsn(readConst(classBuffer[currentOffset + 1] & 0xFF, charBuffer));\n currentOffset += 2;\n break;\n case Constants.LDC_W:\n case Constants.LDC2_W:\n methodVisitor.visitLdcInsn(readConst(readUnsignedShort(currentOffset + 1), charBuffer));\n currentOffset += 3;\n break;\n case Constants.GETSTATIC:\n case Constants.PUTSTATIC:\n case Constants.GETFIELD:\n case Constants.PUTFIELD:\n case Constants.INVOKEVIRTUAL:\n case Constants.INVOKESPECIAL:\n case Constants.INVOKESTATIC:\n case Constants.INVOKEINTERFACE: {\n int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)];\n String owner = readClass(cpInfoOffset, charBuffer);\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n if (opcode < Opcodes.INVOKEVIRTUAL) {\n methodVisitor.visitFieldInsn(opcode, owner, name, descriptor);\n } else {\n boolean isInterface = classBuffer[cpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG;\n methodVisitor.visitMethodInsn(opcode, owner, name, descriptor, isInterface);\n }\n if (opcode == Opcodes.INVOKEINTERFACE) {\n currentOffset += 5;\n } else {\n currentOffset += 3;\n }\n break;\n }\n case Constants.INVOKEDYNAMIC: {\n int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)];\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)];\n Handle handle = (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n Object[] bootstrapMethodArguments = new Object[readUnsignedShort(bootstrapMethodOffset + 2)];\n bootstrapMethodOffset += 4;\n for (int i = 0; i < bootstrapMethodArguments.length; i++) {\n bootstrapMethodArguments[i] = readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n bootstrapMethodOffset += 2;\n }\n methodVisitor.visitInvokeDynamicInsn(name, descriptor, handle, bootstrapMethodArguments);\n currentOffset += 5;\n break;\n }\n case Constants.NEW:\n case Constants.ANEWARRAY:\n case Constants.CHECKCAST:\n case Constants.INSTANCEOF:\n methodVisitor.visitTypeInsn(opcode, readClass(currentOffset + 1, charBuffer));\n currentOffset += 3;\n break;\n case Constants.IINC:\n methodVisitor.visitIincInsn(classBuffer[currentOffset + 1] & 0xFF, classBuffer[currentOffset + 2]);\n currentOffset += 3;\n break;\n case Constants.MULTIANEWARRAY:\n methodVisitor.visitMultiANewArrayInsn(readClass(currentOffset + 1, charBuffer), classBuffer[currentOffset + 3] & 0xFF);\n currentOffset += 4;\n break;\n default:\n throw new AssertionError();\n }\n // Visit the runtime visible instruction annotations, if any.\n while (visibleTypeAnnotationOffsets != null && currentVisibleTypeAnnotationIndex < visibleTypeAnnotationOffsets.length && currentVisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) {\n if (currentVisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) {\n // Parse the target_type, target_info and target_path fields.\n int currentAnnotationOffset = readTypeAnnotationTarget(context, visibleTypeAnnotationOffsets[currentVisibleTypeAnnotationIndex]);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitInsnAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n currentVisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(visibleTypeAnnotationOffsets, ++currentVisibleTypeAnnotationIndex);\n }\n // Visit the runtime invisible instruction annotations, if any.\n while (invisibleTypeAnnotationOffsets != null && currentInvisibleTypeAnnotationIndex < invisibleTypeAnnotationOffsets.length && currentInvisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) {\n if (currentInvisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) {\n // Parse the target_type, target_info and target_path fields.\n int currentAnnotationOffset = readTypeAnnotationTarget(context, invisibleTypeAnnotationOffsets[currentInvisibleTypeAnnotationIndex]);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitInsnAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n currentInvisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(invisibleTypeAnnotationOffsets, ++currentInvisibleTypeAnnotationIndex);\n }\n }\n if (labels[codeLength] != null) {\n methodVisitor.visitLabel(labels[codeLength]);\n }\n // Visit LocalVariableTable and LocalVariableTypeTable attributes.\n if (localVariableTableOffset != 0 && (context.parsingOptions & SKIP_DEBUG) == 0) {\n // The (start_pc, index, signature_index) fields of each entry of the LocalVariableTypeTable.\n int[] typeTable = null;\n if (localVariableTypeTableOffset != 0) {\n typeTable = new int[readUnsignedShort(localVariableTypeTableOffset) * 3];\n currentOffset = localVariableTypeTableOffset + 2;\n int typeTableIndex = typeTable.length;\n while (typeTableIndex > 0) {\n // Store the offset of 'signature_index', and the value of 'index' and 'start_pc'.\n typeTable[--typeTableIndex] = currentOffset + 6;\n typeTable[--typeTableIndex] = readUnsignedShort(currentOffset + 8);\n typeTable[--typeTableIndex] = readUnsignedShort(currentOffset);\n currentOffset += 10;\n }\n }\n int localVariableTableLength = readUnsignedShort(localVariableTableOffset);\n currentOffset = localVariableTableOffset + 2;\n while (localVariableTableLength-- > 0) {\n int startPc = readUnsignedShort(currentOffset);\n int length = readUnsignedShort(currentOffset + 2);\n String name = readUTF8(currentOffset + 4, charBuffer);\n String descriptor = readUTF8(currentOffset + 6, charBuffer);\n int index = readUnsignedShort(currentOffset + 8);\n currentOffset += 10;\n String signature = null;\n if (typeTable != null) {\n for (int i = 0; i < typeTable.length; i += 3) {\n if (typeTable[i] == startPc && typeTable[i + 1] == index) {\n signature = readUTF8(typeTable[i + 2], charBuffer);\n break;\n }\n }\n }\n methodVisitor.visitLocalVariable(name, descriptor, signature, labels[startPc], labels[startPc + length], index);\n }\n }\n // Visit the local variable type annotations of the RuntimeVisibleTypeAnnotations attribute.\n if (visibleTypeAnnotationOffsets != null) {\n for (int typeAnnotationOffset : visibleTypeAnnotationOffsets) {\n int targetType = readByte(typeAnnotationOffset);\n if (targetType == TypeReference.LOCAL_VARIABLE || targetType == TypeReference.RESOURCE_VARIABLE) {\n // Parse the target_type, target_info and target_path fields.\n currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitLocalVariableAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, context.currentLocalVariableAnnotationRangeStarts, context.currentLocalVariableAnnotationRangeEnds, context.currentLocalVariableAnnotationRangeIndices, annotationDescriptor,\n /* visible = */ true), currentOffset,\n /* named = */ true, charBuffer);\n }\n }\n }\n // Visit the local variable type annotations of the RuntimeInvisibleTypeAnnotations attribute.\n if (invisibleTypeAnnotationOffsets != null) {\n for (int typeAnnotationOffset : invisibleTypeAnnotationOffsets) {\n int targetType = readByte(typeAnnotationOffset);\n if (targetType == TypeReference.LOCAL_VARIABLE || targetType == TypeReference.RESOURCE_VARIABLE) {\n // Parse the target_type, target_info and target_path fields.\n currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitLocalVariableAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, context.currentLocalVariableAnnotationRangeStarts, context.currentLocalVariableAnnotationRangeEnds, context.currentLocalVariableAnnotationRangeIndices, annotationDescriptor,\n /* visible = */ false), currentOffset,\n /* named = */ true, charBuffer);\n }\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in MethodWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n methodVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the max stack and max locals values.\n methodVisitor.visitMaxs(maxStack, maxLocals);\n }\n\n /**\n * Returns the label corresponding to the given bytecode offset. The default implementation of\n * this method creates a label for the given offset if it has not been already created.\n *\n * @param bytecodeOffset a bytecode offset in a method.\n * @param labels the already created labels, indexed by their offset. If a label already exists\n * for bytecodeOffset this method must not create a new one. Otherwise it must store the new\n * label in this array.\n * @return a non null Label, which must be equal to labels[bytecodeOffset].\n */\n protected Label readLabel(final int bytecodeOffset, final Label[] labels) {\n if (labels[bytecodeOffset] == null) {\n labels[bytecodeOffset] = new Label();\n }\n return labels[bytecodeOffset];\n }\n\n /**\n * Creates a label without the {@link Label#FLAG_DEBUG_ONLY} flag set, for the given bytecode\n * offset. The label is created with a call to {@link #readLabel} and its {@link\n * Label#FLAG_DEBUG_ONLY} flag is cleared.\n *\n * @param bytecodeOffset a bytecode offset in a method.\n * @param labels the already created labels, indexed by their offset.\n * @return a Label without the {@link Label#FLAG_DEBUG_ONLY} flag set.\n */\n private Label createLabel(final int bytecodeOffset, final Label[] labels) {\n Label label = readLabel(bytecodeOffset, labels);\n label.flags &= ~Label.FLAG_DEBUG_ONLY;\n return label;\n }\n\n /**\n * Creates a label with the {@link Label#FLAG_DEBUG_ONLY} flag set, if there is no already\n * existing label for the given bytecode offset (otherwise does nothing). The label is created\n * with a call to {@link #readLabel}.\n *\n * @param bytecodeOffset a bytecode offset in a method.\n * @param labels the already created labels, indexed by their offset.\n */\n private void createDebugLabel(final int bytecodeOffset, final Label[] labels) {\n if (labels[bytecodeOffset] == null) {\n readLabel(bytecodeOffset, labels).flags |= Label.FLAG_DEBUG_ONLY;\n }\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse annotations, type annotations and parameter annotations\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Parses a Runtime[In]VisibleTypeAnnotations attribute to find the offset of each type_annotation\n * entry it contains, to find the corresponding labels, and to visit the try catch block\n * annotations.\n *\n * @param methodVisitor the method visitor to be used to visit the try catch block annotations.\n * @param context information about the class being parsed.\n * @param runtimeTypeAnnotationsOffset the start offset of a Runtime[In]VisibleTypeAnnotations\n * attribute, excluding the attribute_info's attribute_name_index and attribute_length fields.\n * @param visible true if the attribute to parse is a RuntimeVisibleTypeAnnotations attribute,\n * false it is a RuntimeInvisibleTypeAnnotations attribute.\n * @return the start offset of each entry of the Runtime[In]VisibleTypeAnnotations_attribute's\n * 'annotations' array field.\n */\n private int[] readTypeAnnotations(final MethodVisitor methodVisitor, final Context context, final int runtimeTypeAnnotationsOffset, final boolean visible) {\n char[] charBuffer = context.charBuffer;\n int currentOffset = runtimeTypeAnnotationsOffset;\n // Read the num_annotations field and create an array to store the type_annotation offsets.\n int[] typeAnnotationsOffsets = new int[readUnsignedShort(currentOffset)];\n currentOffset += 2;\n // Parse the 'annotations' array field.\n for (int i = 0; i < typeAnnotationsOffsets.length; ++i) {\n typeAnnotationsOffsets[i] = currentOffset;\n // Parse the type_annotation's target_type and the target_info fields. The size of the\n // target_info field depends on the value of target_type.\n int targetType = readInt(currentOffset);\n switch (targetType >>> 24) {\n case TypeReference.LOCAL_VARIABLE:\n case TypeReference.RESOURCE_VARIABLE:\n // A localvar_target has a variable size, which depends on the value of their table_length\n // field. It also references bytecode offsets, for which we need labels.\n int tableLength = readUnsignedShort(currentOffset + 1);\n currentOffset += 3;\n while (tableLength-- > 0) {\n int startPc = readUnsignedShort(currentOffset);\n int length = readUnsignedShort(currentOffset + 2);\n // Skip the index field (2 bytes).\n currentOffset += 6;\n createLabel(startPc, context.currentMethodLabels);\n createLabel(startPc + length, context.currentMethodLabels);\n }\n break;\n case TypeReference.CAST:\n case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:\n case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT:\n currentOffset += 4;\n break;\n case TypeReference.CLASS_EXTENDS:\n case TypeReference.CLASS_TYPE_PARAMETER_BOUND:\n case TypeReference.METHOD_TYPE_PARAMETER_BOUND:\n case TypeReference.THROWS:\n case TypeReference.EXCEPTION_PARAMETER:\n case TypeReference.INSTANCEOF:\n case TypeReference.NEW:\n case TypeReference.CONSTRUCTOR_REFERENCE:\n case TypeReference.METHOD_REFERENCE:\n currentOffset += 3;\n break;\n case TypeReference.CLASS_TYPE_PARAMETER:\n case TypeReference.METHOD_TYPE_PARAMETER:\n case TypeReference.METHOD_FORMAL_PARAMETER:\n case TypeReference.FIELD:\n case TypeReference.METHOD_RETURN:\n case TypeReference.METHOD_RECEIVER:\n default:\n // TypeReference type which can't be used in Code attribute, or which is unknown.\n throw new IllegalArgumentException();\n }\n // Parse the rest of the type_annotation structure, starting with the target_path structure\n // (whose size depends on its path_length field).\n int pathLength = readByte(currentOffset);\n if ((targetType >>> 24) == TypeReference.EXCEPTION_PARAMETER) {\n // Parse the target_path structure and create a corresponding TypePath.\n TypePath path = pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset);\n currentOffset += 1 + 2 * pathLength;\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentOffset = readElementValues(methodVisitor.visitTryCatchAnnotation(targetType & 0xFFFFFF00, path, annotationDescriptor, visible), currentOffset,\n /* named = */ true, charBuffer);\n } else {\n // We don't want to visit the other target_type annotations, so we just skip them (which\n // requires some parsing because the element_value_pairs array has a variable size). First,\n // skip the target_path structure:\n currentOffset += 3 + 2 * pathLength;\n // Then skip the num_element_value_pairs and element_value_pairs fields (by reading them\n // with a null AnnotationVisitor).\n currentOffset = readElementValues(\n /* annotationVisitor = */ null, currentOffset, /* named = */ true, charBuffer);\n }\n }\n return typeAnnotationsOffsets;\n }\n\n /**\n * Returns the bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or\n * -1 if there is no such type_annotation of if it does not have a bytecode offset.\n *\n * @param typeAnnotationOffsets the offset of each 'type_annotation' entry in a\n * Runtime[In]VisibleTypeAnnotations attribute, or {@literal null}.\n * @param typeAnnotationIndex the index a 'type_annotation' entry in typeAnnotationOffsets.\n * @return bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or -1\n * if there is no such type_annotation of if it does not have a bytecode offset.\n */\n private int getTypeAnnotationBytecodeOffset(final int[] typeAnnotationOffsets, final int typeAnnotationIndex) {\n if (typeAnnotationOffsets == null || typeAnnotationIndex >= typeAnnotationOffsets.length || readByte(typeAnnotationOffsets[typeAnnotationIndex]) < TypeReference.INSTANCEOF) {\n return -1;\n }\n return readUnsignedShort(typeAnnotationOffsets[typeAnnotationIndex] + 1);\n }\n\n /**\n * Parses the header of a JVMS type_annotation structure to extract its target_type, target_info\n * and target_path (the result is stored in the given context), and returns the start offset of\n * the rest of the type_annotation structure.\n *\n * @param context information about the class being parsed. This is where the extracted\n * target_type and target_path must be stored.\n * @param typeAnnotationOffset the start offset of a type_annotation structure.\n * @return the start offset of the rest of the type_annotation structure.\n */\n private int readTypeAnnotationTarget(final Context context, final int typeAnnotationOffset) {\n int currentOffset = typeAnnotationOffset;\n // Parse and store the target_type structure.\n int targetType = readInt(typeAnnotationOffset);\n switch (targetType >>> 24) {\n case TypeReference.CLASS_TYPE_PARAMETER:\n case TypeReference.METHOD_TYPE_PARAMETER:\n case TypeReference.METHOD_FORMAL_PARAMETER:\n targetType &= 0xFFFF0000;\n currentOffset += 2;\n break;\n case TypeReference.FIELD:\n case TypeReference.METHOD_RETURN:\n case TypeReference.METHOD_RECEIVER:\n targetType &= 0xFF000000;\n currentOffset += 1;\n break;\n case TypeReference.LOCAL_VARIABLE:\n case TypeReference.RESOURCE_VARIABLE:\n targetType &= 0xFF000000;\n int tableLength = readUnsignedShort(currentOffset + 1);\n currentOffset += 3;\n context.currentLocalVariableAnnotationRangeStarts = new Label[tableLength];\n context.currentLocalVariableAnnotationRangeEnds = new Label[tableLength];\n context.currentLocalVariableAnnotationRangeIndices = new int[tableLength];\n for (int i = 0; i < tableLength; ++i) {\n int startPc = readUnsignedShort(currentOffset);\n int length = readUnsignedShort(currentOffset + 2);\n int index = readUnsignedShort(currentOffset + 4);\n currentOffset += 6;\n context.currentLocalVariableAnnotationRangeStarts[i] = createLabel(startPc, context.currentMethodLabels);\n context.currentLocalVariableAnnotationRangeEnds[i] = createLabel(startPc + length, context.currentMethodLabels);\n context.currentLocalVariableAnnotationRangeIndices[i] = index;\n }\n break;\n case TypeReference.CAST:\n case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:\n case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT:\n targetType &= 0xFF0000FF;\n currentOffset += 4;\n break;\n case TypeReference.CLASS_EXTENDS:\n case TypeReference.CLASS_TYPE_PARAMETER_BOUND:\n case TypeReference.METHOD_TYPE_PARAMETER_BOUND:\n case TypeReference.THROWS:\n case TypeReference.EXCEPTION_PARAMETER:\n targetType &= 0xFFFFFF00;\n currentOffset += 3;\n break;\n case TypeReference.INSTANCEOF:\n case TypeReference.NEW:\n case TypeReference.CONSTRUCTOR_REFERENCE:\n case TypeReference.METHOD_REFERENCE:\n targetType &= 0xFF000000;\n currentOffset += 3;\n break;\n default:\n throw new IllegalArgumentException();\n }\n context.currentTypeAnnotationTarget = targetType;\n // Parse and store the target_path structure.\n int pathLength = readByte(currentOffset);\n context.currentTypeAnnotationTargetPath = pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset);\n // Return the start offset of the rest of the type_annotation structure.\n return currentOffset + 1 + 2 * pathLength;\n }\n\n /**\n * Reads a Runtime[In]VisibleParameterAnnotations attribute and makes the given visitor visit it.\n *\n * @param methodVisitor the visitor that must visit the parameter annotations.\n * @param context information about the class being parsed.\n * @param runtimeParameterAnnotationsOffset the start offset of a\n * Runtime[In]VisibleParameterAnnotations attribute, excluding the attribute_info's\n * attribute_name_index and attribute_length fields.\n * @param visible true if the attribute to parse is a RuntimeVisibleParameterAnnotations\n * attribute, false it is a RuntimeInvisibleParameterAnnotations attribute.\n */\n private void readParameterAnnotations(final MethodVisitor methodVisitor, final Context context, final int runtimeParameterAnnotationsOffset, final boolean visible) {\n int currentOffset = runtimeParameterAnnotationsOffset;\n int numParameters = classFileBuffer[currentOffset++] & 0xFF;\n methodVisitor.visitAnnotableParameterCount(numParameters, visible);\n char[] charBuffer = context.charBuffer;\n for (int i = 0; i < numParameters; ++i) {\n int numAnnotations = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentOffset = readElementValues(methodVisitor.visitParameterAnnotation(i, annotationDescriptor, visible), currentOffset,\n /* named = */ true, charBuffer);\n }\n }\n }\n\n /**\n * Reads the element values of a JVMS 'annotation' structure and makes the given visitor visit\n * them. This method can also be used to read the values of the JVMS 'array_value' field of an\n * annotation's 'element_value'.\n *\n * @param annotationVisitor the visitor that must visit the values.\n * @param annotationOffset the start offset of an 'annotation' structure (excluding its type_index\n * field) or of an 'array_value' structure.\n * @param named if the annotation values are named or not. This should be true to parse the values\n * of a JVMS 'annotation' structure, and false to parse the JVMS 'array_value' of an\n * annotation's element_value.\n * @param charBuffer the buffer used to read strings in the constant pool.\n * @return the end offset of the JVMS 'annotation' or 'array_value' structure.\n */\n private int readElementValues(final AnnotationVisitor annotationVisitor, final int annotationOffset, final boolean named, final char[] charBuffer) {\n int currentOffset = annotationOffset;\n // Read the num_element_value_pairs field (or num_values field for an array_value).\n int numElementValuePairs = readUnsignedShort(currentOffset);\n currentOffset += 2;\n if (named) {\n // Parse the element_value_pairs array.\n while (numElementValuePairs-- > 0) {\n String elementName = readUTF8(currentOffset, charBuffer);\n currentOffset = readElementValue(annotationVisitor, currentOffset + 2, elementName, charBuffer);\n }\n } else {\n // Parse the array_value array.\n while (numElementValuePairs-- > 0) {\n currentOffset = readElementValue(annotationVisitor, currentOffset, /* named = */ null, charBuffer);\n }\n }\n if (annotationVisitor != null) {\n annotationVisitor.visitEnd();\n }\n return currentOffset;\n }\n\n /**\n * Reads a JVMS 'element_value' structure and makes the given visitor visit it.\n *\n * @param annotationVisitor the visitor that must visit the element_value structure.\n * @param elementValueOffset the start offset in {@link #classFileBuffer} of the element_value\n * structure to be read.\n * @param elementName the name of the element_value structure to be read, or {@literal null}.\n * @param charBuffer the buffer used to read strings in the constant pool.\n * @return the end offset of the JVMS 'element_value' structure.\n */\n private int readElementValue(final AnnotationVisitor annotationVisitor, final int elementValueOffset, final String elementName, final char[] charBuffer) {\n int currentOffset = elementValueOffset;\n if (annotationVisitor == null) {\n switch (classFileBuffer[currentOffset] & 0xFF) {\n case 'e': // enum_const_value\n return currentOffset + 5;\n case '@': // annotation_value\n return readElementValues(null, currentOffset + 3, /* named = */ true, charBuffer);\n case '[': // array_value\n return readElementValues(null, currentOffset + 1, /* named = */ false, charBuffer);\n default:\n return currentOffset + 3;\n }\n }\n switch (classFileBuffer[currentOffset++] & 0xFF) {\n case 'B': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]));\n currentOffset += 2;\n break;\n case 'C': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]));\n currentOffset += 2;\n break;\n case 'D': // const_value_index, CONSTANT_Double\n case 'F': // const_value_index, CONSTANT_Float\n case 'I': // const_value_index, CONSTANT_Integer\n case 'J': // const_value_index, CONSTANT_Long\n annotationVisitor.visit(elementName, readConst(readUnsignedShort(currentOffset), charBuffer));\n currentOffset += 2;\n break;\n case 'S': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]));\n currentOffset += 2;\n break;\n case 'Z': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]) == 0 ? Boolean.FALSE : Boolean.TRUE);\n currentOffset += 2;\n break;\n case 's': // const_value_index, CONSTANT_Utf8\n annotationVisitor.visit(elementName, readUTF8(currentOffset, charBuffer));\n currentOffset += 2;\n break;\n case 'e': // enum_const_value\n annotationVisitor.visitEnum(elementName, readUTF8(currentOffset, charBuffer), readUTF8(currentOffset + 2, charBuffer));\n currentOffset += 4;\n break;\n case 'c': // class_info\n annotationVisitor.visit(elementName, Type.getType(readUTF8(currentOffset, charBuffer)));\n currentOffset += 2;\n break;\n case '@': // annotation_value\n currentOffset = readElementValues(annotationVisitor.visitAnnotation(elementName, readUTF8(currentOffset, charBuffer)), currentOffset + 2, true, charBuffer);\n break;\n case '[': // array_value\n int numValues = readUnsignedShort(currentOffset);\n currentOffset += 2;\n if (numValues == 0) {\n return readElementValues(annotationVisitor.visitArray(elementName), currentOffset - 2,\n /* named = */ false, charBuffer);\n }\n switch (classFileBuffer[currentOffset] & 0xFF) {\n case 'B':\n byte[] byteValues = new byte[numValues];\n for (int i = 0; i < numValues; i++) {\n byteValues[i] = (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, byteValues);\n break;\n case 'Z':\n boolean[] booleanValues = new boolean[numValues];\n for (int i = 0; i < numValues; i++) {\n booleanValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]) != 0;\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, booleanValues);\n break;\n case 'S':\n short[] shortValues = new short[numValues];\n for (int i = 0; i < numValues; i++) {\n shortValues[i] = (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, shortValues);\n break;\n case 'C':\n char[] charValues = new char[numValues];\n for (int i = 0; i < numValues; i++) {\n charValues[i] = (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, charValues);\n break;\n case 'I':\n int[] intValues = new int[numValues];\n for (int i = 0; i < numValues; i++) {\n intValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, intValues);\n break;\n case 'J':\n long[] longValues = new long[numValues];\n for (int i = 0; i < numValues; i++) {\n longValues[i] = readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, longValues);\n break;\n case 'F':\n float[] floatValues = new float[numValues];\n for (int i = 0; i < numValues; i++) {\n floatValues[i] = Float.intBitsToFloat(readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]));\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, floatValues);\n break;\n case 'D':\n double[] doubleValues = new double[numValues];\n for (int i = 0; i < numValues; i++) {\n doubleValues[i] = Double.longBitsToDouble(readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]));\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, doubleValues);\n break;\n default:\n currentOffset = readElementValues(annotationVisitor.visitArray(elementName), currentOffset - 2,\n /* named = */ false, charBuffer);\n break;\n }\n break;\n default:\n throw new IllegalArgumentException();\n }\n return currentOffset;\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse stack map frames\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Computes the implicit frame of the method currently being parsed (as defined in the given\n * {@link Context}) and stores it in the given context.\n *\n * @param context information about the class being parsed.\n */\n private void computeImplicitFrame(final Context context) {\n String methodDescriptor = context.currentMethodDescriptor;\n Object[] locals = context.currentFrameLocalTypes;\n int numLocal = 0;\n if ((context.currentMethodAccessFlags & Opcodes.ACC_STATIC) == 0) {\n if (\"\".equals(context.currentMethodName)) {\n locals[numLocal++] = Opcodes.UNINITIALIZED_THIS;\n } else {\n locals[numLocal++] = readClass(header + 2, context.charBuffer);\n }\n }\n // Parse the method descriptor, one argument type descriptor at each iteration. Start by\n // skipping the first method descriptor character, which is always '('.\n int currentMethodDescritorOffset = 1;\n while (true) {\n int currentArgumentDescriptorStartOffset = currentMethodDescritorOffset;\n switch (methodDescriptor.charAt(currentMethodDescritorOffset++)) {\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n locals[numLocal++] = Opcodes.INTEGER;\n break;\n case 'F':\n locals[numLocal++] = Opcodes.FLOAT;\n break;\n case 'J':\n locals[numLocal++] = Opcodes.LONG;\n break;\n case 'D':\n locals[numLocal++] = Opcodes.DOUBLE;\n break;\n case '[':\n while (methodDescriptor.charAt(currentMethodDescritorOffset) == '[') {\n ++currentMethodDescritorOffset;\n }\n if (methodDescriptor.charAt(currentMethodDescritorOffset) == 'L') {\n ++currentMethodDescritorOffset;\n while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') {\n ++currentMethodDescritorOffset;\n }\n }\n locals[numLocal++] = methodDescriptor.substring(currentArgumentDescriptorStartOffset, ++currentMethodDescritorOffset);\n break;\n case 'L':\n while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') {\n ++currentMethodDescritorOffset;\n }\n locals[numLocal++] = methodDescriptor.substring(currentArgumentDescriptorStartOffset + 1, currentMethodDescritorOffset++);\n break;\n default:\n context.currentFrameLocalCount = numLocal;\n return;\n }\n }\n }\n\n /**\n * Reads a JVMS 'stack_map_frame' structure and stores the result in the given {@link Context}\n * object. This method can also be used to read a full_frame structure, excluding its frame_type\n * field (this is used to parse the legacy StackMap attributes).\n *\n * @param stackMapFrameOffset the start offset in {@link #classFileBuffer} of the\n * stack_map_frame_value structure to be read, or the start offset of a full_frame structure\n * (excluding its frame_type field).\n * @param compressed true to read a 'stack_map_frame' structure, false to read a 'full_frame'\n * structure without its frame_type field.\n * @param expand if the stack map frame must be expanded. See {@link #EXPAND_FRAMES}.\n * @param context where the parsed stack map frame must be stored.\n * @return the end offset of the JVMS 'stack_map_frame' or 'full_frame' structure.\n */\n private int readStackMapFrame(final int stackMapFrameOffset, final boolean compressed, final boolean expand, final Context context) {\n int currentOffset = stackMapFrameOffset;\n final char[] charBuffer = context.charBuffer;\n final Label[] labels = context.currentMethodLabels;\n int frameType;\n if (compressed) {\n // Read the frame_type field.\n frameType = classFileBuffer[currentOffset++] & 0xFF;\n } else {\n frameType = Frame.FULL_FRAME;\n context.currentFrameOffset = -1;\n }\n int offsetDelta;\n context.currentFrameLocalCountDelta = 0;\n if (frameType < Frame.SAME_LOCALS_1_STACK_ITEM_FRAME) {\n offsetDelta = frameType;\n context.currentFrameType = Opcodes.F_SAME;\n context.currentFrameStackCount = 0;\n } else if (frameType < Frame.RESERVED) {\n offsetDelta = frameType - Frame.SAME_LOCALS_1_STACK_ITEM_FRAME;\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels);\n context.currentFrameType = Opcodes.F_SAME1;\n context.currentFrameStackCount = 1;\n } else if (frameType >= Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {\n offsetDelta = readUnsignedShort(currentOffset);\n currentOffset += 2;\n if (frameType == Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels);\n context.currentFrameType = Opcodes.F_SAME1;\n context.currentFrameStackCount = 1;\n } else if (frameType >= Frame.CHOP_FRAME && frameType < Frame.SAME_FRAME_EXTENDED) {\n context.currentFrameType = Opcodes.F_CHOP;\n context.currentFrameLocalCountDelta = Frame.SAME_FRAME_EXTENDED - frameType;\n context.currentFrameLocalCount -= context.currentFrameLocalCountDelta;\n context.currentFrameStackCount = 0;\n } else if (frameType == Frame.SAME_FRAME_EXTENDED) {\n context.currentFrameType = Opcodes.F_SAME;\n context.currentFrameStackCount = 0;\n } else if (frameType < Frame.FULL_FRAME) {\n int local = expand ? context.currentFrameLocalCount : 0;\n for (int k = frameType - Frame.SAME_FRAME_EXTENDED; k > 0; k--) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameLocalTypes, local++, charBuffer, labels);\n }\n context.currentFrameType = Opcodes.F_APPEND;\n context.currentFrameLocalCountDelta = frameType - Frame.SAME_FRAME_EXTENDED;\n context.currentFrameLocalCount += context.currentFrameLocalCountDelta;\n context.currentFrameStackCount = 0;\n } else {\n final int numberOfLocals = readUnsignedShort(currentOffset);\n currentOffset += 2;\n context.currentFrameType = Opcodes.F_FULL;\n context.currentFrameLocalCountDelta = numberOfLocals;\n context.currentFrameLocalCount = numberOfLocals;\n for (int local = 0; local < numberOfLocals; ++local) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameLocalTypes, local, charBuffer, labels);\n }\n final int numberOfStackItems = readUnsignedShort(currentOffset);\n currentOffset += 2;\n context.currentFrameStackCount = numberOfStackItems;\n for (int stack = 0; stack < numberOfStackItems; ++stack) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameStackTypes, stack, charBuffer, labels);\n }\n }\n } else {\n throw new IllegalArgumentException();\n }\n context.currentFrameOffset += offsetDelta + 1;\n createLabel(context.currentFrameOffset, labels);\n return currentOffset;\n }\n\n /**\n * Reads a JVMS 'verification_type_info' structure and stores it at the given index in the given\n * array.\n *\n * @param verificationTypeInfoOffset the start offset of the 'verification_type_info' structure to\n * read.\n * @param frame the array where the parsed type must be stored.\n * @param index the index in 'frame' where the parsed type must be stored.\n * @param charBuffer the buffer used to read strings in the constant pool.\n * @param labels the labels of the method currently being parsed, indexed by their offset. If the\n * parsed type is an ITEM_Uninitialized, a new label for the corresponding NEW instruction is\n * stored in this array if it does not already exist.\n * @return the end offset of the JVMS 'verification_type_info' structure.\n */\n private int readVerificationTypeInfo(final int verificationTypeInfoOffset, final Object[] frame, final int index, final char[] charBuffer, final Label[] labels) {\n int currentOffset = verificationTypeInfoOffset;\n int tag = classFileBuffer[currentOffset++] & 0xFF;\n switch (tag) {\n case Frame.ITEM_TOP:\n frame[index] = Opcodes.TOP;\n break;\n case Frame.ITEM_INTEGER:\n frame[index] = Opcodes.INTEGER;\n break;\n case Frame.ITEM_FLOAT:\n frame[index] = Opcodes.FLOAT;\n break;\n case Frame.ITEM_DOUBLE:\n frame[index] = Opcodes.DOUBLE;\n break;\n case Frame.ITEM_LONG:\n frame[index] = Opcodes.LONG;\n break;\n case Frame.ITEM_NULL:\n frame[index] = Opcodes.NULL;\n break;\n case Frame.ITEM_UNINITIALIZED_THIS:\n frame[index] = Opcodes.UNINITIALIZED_THIS;\n break;\n case Frame.ITEM_OBJECT:\n frame[index] = readClass(currentOffset, charBuffer);\n currentOffset += 2;\n break;\n case Frame.ITEM_UNINITIALIZED:\n frame[index] = createLabel(readUnsignedShort(currentOffset), labels);\n currentOffset += 2;\n break;\n default:\n throw new IllegalArgumentException();\n }\n return currentOffset;\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse attributes\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Returns the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array\n * field entry.\n *\n * @return the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array\n * field entry.\n */\n final int getFirstAttributeOffset() {\n // Skip the access_flags, this_class, super_class, and interfaces_count fields (using 2 bytes\n // each), as well as the interfaces array field (2 bytes per interface).\n int currentOffset = header + 8 + readUnsignedShort(header + 6) * 2;\n // Read the fields_count field.\n int fieldsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n // Skip the 'fields' array field.\n while (fieldsCount-- > 0) {\n // Invariant: currentOffset is the offset of a field_info structure.\n // Skip the access_flags, name_index and descriptor_index fields (2 bytes each), and read the\n // attributes_count field.\n int attributesCount = readUnsignedShort(currentOffset + 6);\n currentOffset += 8;\n // Skip the 'attributes' array field.\n while (attributesCount-- > 0) {\n // Invariant: currentOffset is the offset of an attribute_info structure.\n // Read the attribute_length field (2 bytes after the start of the attribute_info) and skip\n // this many bytes, plus 6 for the attribute_name_index and attribute_length fields\n // (yielding the total size of the attribute_info structure).\n currentOffset += 6 + readInt(currentOffset + 2);\n }\n }\n // Skip the methods_count and 'methods' fields, using the same method as above.\n int methodsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (methodsCount-- > 0) {\n int attributesCount = readUnsignedShort(currentOffset + 6);\n currentOffset += 8;\n while (attributesCount-- > 0) {\n currentOffset += 6 + readInt(currentOffset + 2);\n }\n }\n // Skip the ClassFile's attributes_count field.\n return currentOffset + 2;\n }\n\n /**\n * Reads the BootstrapMethods attribute to compute the offset of each bootstrap method.\n *\n * @param maxStringLength a conservative estimate of the maximum length of the strings contained\n * in the constant pool of the class.\n * @return the offsets of the bootstrap methods.\n */\n private int[] readBootstrapMethodsAttribute(final int maxStringLength) {\n char[] charBuffer = new char[maxStringLength];\n int currentAttributeOffset = getFirstAttributeOffset();\n int[] currentBootstrapMethodOffsets = null;\n for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentAttributeOffset, charBuffer);\n int attributeLength = readInt(currentAttributeOffset + 2);\n currentAttributeOffset += 6;\n if (Constants.BOOTSTRAP_METHODS.equals(attributeName)) {\n // Read the num_bootstrap_methods field and create an array of this size.\n currentBootstrapMethodOffsets = new int[readUnsignedShort(currentAttributeOffset)];\n // Compute and store the offset of each 'bootstrap_methods' array field entry.\n int currentBootstrapMethodOffset = currentAttributeOffset + 2;\n for (int j = 0; j < currentBootstrapMethodOffsets.length; ++j) {\n currentBootstrapMethodOffsets[j] = currentBootstrapMethodOffset;\n // Skip the bootstrap_method_ref and num_bootstrap_arguments fields (2 bytes each),\n // as well as the bootstrap_arguments array field (of size num_bootstrap_arguments * 2).\n currentBootstrapMethodOffset += 4 + readUnsignedShort(currentBootstrapMethodOffset + 2) * 2;\n }\n return currentBootstrapMethodOffsets;\n }\n currentAttributeOffset += attributeLength;\n }\n throw new IllegalArgumentException();\n }\n\n /**\n * Reads a non standard JVMS 'attribute' structure in {@link #classFileBuffer}.\n *\n * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of\n * the class. Any attribute whose type is not equal to the type of one the prototypes will not\n * be parsed: its byte array value will be passed unchanged to the ClassWriter.\n * @param type the type of the attribute.\n * @param offset the start offset of the JVMS 'attribute' structure in {@link #classFileBuffer}.\n * The 6 attribute header bytes (attribute_name_index and attribute_length) are not taken into\n * account here.\n * @param length the length of the attribute's content (excluding the 6 attribute header bytes).\n * @param charBuffer the buffer to be used to read strings in the constant pool.\n * @param codeAttributeOffset the start offset of the enclosing Code attribute in {@link\n * #classFileBuffer}, or -1 if the attribute to be read is not a code attribute. The 6\n * attribute header bytes (attribute_name_index and attribute_length) are not taken into\n * account here.\n * @param labels the labels of the method's code, or {@literal null} if the attribute to be read\n * is not a code attribute.\n * @return the attribute that has been read.\n */\n private Attribute readAttribute(final Attribute[] attributePrototypes, final String type, final int offset, final int length, final char[] charBuffer, final int codeAttributeOffset, final Label[] labels) {\n for (Attribute attributePrototype : attributePrototypes) {\n if (attributePrototype.type.equals(type)) {\n return attributePrototype.read(this, offset, length, charBuffer, codeAttributeOffset, labels);\n }\n }\n return new Attribute(type).read(this, offset, length, null, -1, null);\n }\n // -----------------------------------------------------------------------------------------------\n // Utility methods: low level parsing\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the number of entries in the class's constant pool table.\n *\n * @return the number of entries in the class's constant pool table.\n */\n public int getItemCount() {\n return cpInfoOffsets.length;\n }\n\n /**\n * Returns the start offset in this {@link ClassReader} of a JVMS 'cp_info' structure (i.e. a\n * constant pool entry), plus one. This method is intended for {@link Attribute} sub classes,\n * and is normally not needed by class generators or adapters.\n *\n * @param constantPoolEntryIndex the index a constant pool entry in the class's constant pool\n * table.\n * @return the start offset in this {@link ClassReader} of the corresponding JVMS 'cp_info'\n * structure, plus one.\n */\n public int getItem(final int constantPoolEntryIndex) {\n return cpInfoOffsets[constantPoolEntryIndex];\n }\n\n /**\n * Returns a conservative estimate of the maximum length of the strings contained in the class's\n * constant pool table.\n *\n * @return a conservative estimate of the maximum length of the strings contained in the class's\n * constant pool table.\n */\n public int getMaxStringLength() {\n return maxStringLength;\n }\n\n /**\n * Reads a byte value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public int readByte(final int offset) {\n return classFileBuffer[offset] & 0xFF;\n }\n\n /**\n * Reads an unsigned short value in this {@link ClassReader}. This method is intended for\n * {@link Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start index of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public int readUnsignedShort(final int offset) {\n byte[] classBuffer = classFileBuffer;\n return ((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF);\n }\n\n /**\n * Reads a signed short value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public short readShort(final int offset) {\n byte[] classBuffer = classFileBuffer;\n return (short) (((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF));\n }\n\n /**\n * Reads a signed int value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public int readInt(final int offset) {\n byte[] classBuffer = classFileBuffer;\n return ((classBuffer[offset] & 0xFF) << 24) | ((classBuffer[offset + 1] & 0xFF) << 16) | ((classBuffer[offset + 2] & 0xFF) << 8) | (classBuffer[offset + 3] & 0xFF);\n }\n\n /**\n * Reads a signed long value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public long readLong(final int offset) {\n long l1 = readInt(offset);\n long l0 = readInt(offset + 4) & 0xFFFFFFFFL;\n return (l1 << 32) | l0;\n }\n\n /**\n * Reads a CONSTANT_Utf8 constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Utf8 entry in the class's constant pool table.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Utf8 entry.\n */\n // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility).\n public String readUTF8(final int offset, final char[] charBuffer) {\n int constantPoolEntryIndex = readUnsignedShort(offset);\n if (offset == 0 || constantPoolEntryIndex == 0) {\n return null;\n }\n return readUtf(constantPoolEntryIndex, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Utf8 constant pool entry in {@link #classFileBuffer}.\n *\n * @param constantPoolEntryIndex the index of a CONSTANT_Utf8 entry in the class's constant pool\n * table.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Utf8 entry.\n */\n final String readUtf(final int constantPoolEntryIndex, final char[] charBuffer) {\n String value = constantUtf8Values[constantPoolEntryIndex];\n if (value != null) {\n return value;\n }\n int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex];\n return constantUtf8Values[constantPoolEntryIndex] = readUtf(cpInfoOffset + 2, readUnsignedShort(cpInfoOffset), charBuffer);\n }\n\n /**\n * Reads an UTF8 string in {@link #classFileBuffer}.\n *\n * @param utfOffset the start offset of the UTF8 string to be read.\n * @param utfLength the length of the UTF8 string to be read.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified UTF8 string.\n */\n private String readUtf(final int utfOffset, final int utfLength, final char[] charBuffer) {\n int currentOffset = utfOffset;\n int endOffset = currentOffset + utfLength;\n int strLength = 0;\n byte[] classBuffer = classFileBuffer;\n while (currentOffset < endOffset) {\n int currentByte = classBuffer[currentOffset++];\n if ((currentByte & 0x80) == 0) {\n charBuffer[strLength++] = (char) (currentByte & 0x7F);\n } else if ((currentByte & 0xE0) == 0xC0) {\n charBuffer[strLength++] = (char) (((currentByte & 0x1F) << 6) + (classBuffer[currentOffset++] & 0x3F));\n } else {\n charBuffer[strLength++] = (char) (((currentByte & 0xF) << 12) + ((classBuffer[currentOffset++] & 0x3F) << 6) + (classBuffer[currentOffset++] & 0x3F));\n }\n }\n return new String(charBuffer, 0, strLength);\n }\n\n /**\n * Reads a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, CONSTANT_Module or\n * CONSTANT_Package constant pool entry in {@link #classFileBuffer}. This method is intended\n * for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in {@link #classFileBuffer}, whose\n * value is the index of a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType,\n * CONSTANT_Module or CONSTANT_Package entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified constant pool entry.\n */\n private String readStringish(final int offset, final char[] charBuffer) {\n // Get the start offset of the cp_info structure (plus one), and read the CONSTANT_Utf8 entry\n // designated by the first two bytes of this cp_info.\n return readUTF8(cpInfoOffsets[readUnsignedShort(offset)], charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Class constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Class entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Class entry.\n */\n public String readClass(final int offset, final char[] charBuffer) {\n return readStringish(offset, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Module constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Module entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Module entry.\n */\n public String readModule(final int offset, final char[] charBuffer) {\n return readStringish(offset, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Package constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Package entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Package entry.\n */\n public String readPackage(final int offset, final char[] charBuffer) {\n return readStringish(offset, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Dynamic constant pool entry in {@link #classFileBuffer}.\n *\n * @param constantPoolEntryIndex the index of a CONSTANT_Dynamic entry in the class's constant\n * pool table.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the ConstantDynamic corresponding to the specified CONSTANT_Dynamic entry.\n */\n private ConstantDynamic readConstantDynamic(final int constantPoolEntryIndex, final char[] charBuffer) {\n ConstantDynamic constantDynamic = constantDynamicValues[constantPoolEntryIndex];\n if (constantDynamic != null) {\n return constantDynamic;\n }\n int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)];\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)];\n Handle handle = (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n Object[] bootstrapMethodArguments = new Object[readUnsignedShort(bootstrapMethodOffset + 2)];\n bootstrapMethodOffset += 4;\n for (int i = 0; i < bootstrapMethodArguments.length; i++) {\n bootstrapMethodArguments[i] = readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n bootstrapMethodOffset += 2;\n }\n return constantDynamicValues[constantPoolEntryIndex] = new ConstantDynamic(name, descriptor, handle, bootstrapMethodArguments);\n }\n\n /**\n * Reads a numeric or string constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param constantPoolEntryIndex the index of a CONSTANT_Integer, CONSTANT_Float, CONSTANT_Long,\n * CONSTANT_Double, CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType,\n * CONSTANT_MethodHandle or CONSTANT_Dynamic entry in the class's constant pool.\n * @param charBuffer the buffer to be used to read strings. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the {@link Integer}, {@link Float}, {@link Long}, {@link Double}, {@link String},\n * {@link Type}, {@link Handle} or {@link ConstantDynamic} corresponding to the specified\n * constant pool entry.\n */\n public Object readConst(final int constantPoolEntryIndex, final char[] charBuffer) {\n int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex];\n switch (classFileBuffer[cpInfoOffset - 1]) {\n case Symbol.CONSTANT_INTEGER_TAG:\n return readInt(cpInfoOffset);\n case Symbol.CONSTANT_FLOAT_TAG:\n return Float.intBitsToFloat(readInt(cpInfoOffset));\n case Symbol.CONSTANT_LONG_TAG:\n return readLong(cpInfoOffset);\n case Symbol.CONSTANT_DOUBLE_TAG:\n return Double.longBitsToDouble(readLong(cpInfoOffset));\n case Symbol.CONSTANT_CLASS_TAG:\n return Type.getObjectType(readUTF8(cpInfoOffset, charBuffer));\n case Symbol.CONSTANT_STRING_TAG:\n return readUTF8(cpInfoOffset, charBuffer);\n case Symbol.CONSTANT_METHOD_TYPE_TAG:\n return Type.getMethodType(readUTF8(cpInfoOffset, charBuffer));\n case Symbol.CONSTANT_METHOD_HANDLE_TAG:\n int referenceKind = readByte(cpInfoOffset);\n int referenceCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 1)];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(referenceCpInfoOffset + 2)];\n String owner = readClass(referenceCpInfoOffset, charBuffer);\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n boolean isInterface = classFileBuffer[referenceCpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG;\n return new Handle(referenceKind, owner, name, descriptor, isInterface);\n case Symbol.CONSTANT_DYNAMIC_TAG:\n return readConstantDynamic(constantPoolEntryIndex, charBuffer);\n default:\n throw new IllegalArgumentException();\n }\n }\n}\n", "file_name": "ClassReader.java", "human_label": "Return the label by the given bytecode offset if it has been created. Otherwise, creat a new label and return it.", "level": "self_contained", "lineno": "2268", "name": "readLabel", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils.asm", "project": "hasor-master" }, { "_id": "6367677d1a6d9265ec0182fd", "all_context": "{ \"class_level\" : \"import java.io.InputStream;\\nimport java.io.InterruptedIOException;\\nimport java.net.URL;\\nimport java.util.Properties;\\nimport org.apache.log4j.Level;\\nimport org.apache.log4j.PropertyConfigurator;\\nimport org.apache.log4j.spi.Configurator;\\nimport org.apache.log4j.spi.LoggerRepository;\\nString DELIM_START;\\nchar DELIM_STOP;\\nint DELIM_START_LEN;\\nint DELIM_STOP_LEN;\\nOptionConverter();\\nconcatanateArrays(String[] l,String[] r);\\nconvertSpecialChars(String s);\\ngetSystemProperty(String key,String def);\\ninstantiateByKey(Properties props,String key,Class superClass,Object defaultValue);\\ntoInt(String value,int dEfault);\\ntoLevel(String value,Level defaultValue);\\ntoFileSize(String value,long dEfault);\\nfindAndSubst(String key,Properties props);\\ninstantiateByClassName(String className,Class superClass,Object defaultValue);\\nsubstVars(String val,Properties props);\\nselectAndConfigure(InputStream inputStream,String clazz,LoggerRepository hierarchy);\\nselectAndConfigure(URL url,String clazz,LoggerRepository hierarchy);\\n\", \"repo_level\" : \"public interface Level {static Level toLevel(String sArg);\\nstatic Level toLevel(int val);\\nstatic Level toLevel(int val,Level defaultLevel);\\nstatic Level toLevel(String sArg,Level defaultLevel);\\n }\\npublic interface PropertyConfigurator {public void doConfigure(String configFileName,LoggerRepository hierarchy);\\npublic void configure(String configFilename);\\nstatic void configure(URL configURL);\\nstatic void configure(InputStream inputStream);\\npublic void configure(Properties properties);\\npublic void configureAndWatch(String configFilename);\\npublic void configureAndWatch(String configFilename,long delay);\\npublic void doConfigure(Properties properties,LoggerRepository hierarchy);\\npublic void doConfigure(InputStream inputStream,LoggerRepository hierarchy);\\npublic void doConfigure(URL configURL,LoggerRepository hierarchy);\\nprotected void configureLoggerFactory(Properties props);\\n void configureRootCategory(Properties props,LoggerRepository hierarchy);\\nprotected void parseCatsAndRenderers(Properties props,LoggerRepository hierarchy);\\n void parseAdditivityForLogger(Properties props,Logger cat,String loggerName);\\n void parseCategory(Properties props,Logger logger,String optionKey,String loggerName,String value);\\n Appender parseAppender(Properties props,String appenderName);\\n void parseAppenderFilters(Properties props,String appenderName,Appender appender);\\n void registryPut(Appender appender);\\n Appender registryGet(String name);\\n }\\npublic interface Configurator { void doConfigure(InputStream inputStream,LoggerRepository repository);\\n void doConfigure(URL url,LoggerRepository repository);\\n }\\npublic interface LoggerRepository {public void addHierarchyEventListener(HierarchyEventListener listener);\\n boolean isDisabled(int level);\\npublic void setThreshold(Level level);\\npublic void setThreshold(String val);\\npublic void emitNoAppenderWarning(Category cat);\\npublic Level getThreshold();\\npublic Logger getLogger(String name);\\npublic Logger getLogger(String name,LoggerFactory factory);\\npublic Logger getRootLogger();\\nabstract Logger exists(String name);\\nabstract void shutdown();\\npublic Enumeration getCurrentLoggers();\\npublic Enumeration getCurrentCategories();\\nabstract void fireAddAppenderEvent(Category logger,Appender appender);\\nabstract void resetConfiguration();\\n }\\n\" }", "class_name": "OptionConverter", "code": "public static boolean toBoolean(String value,boolean dEfault){\n if (value == null) return dEfault;\n String trimmedVal=value.trim();\n if (\"true\".equalsIgnoreCase(trimmedVal)) return true;\n if (\"false\".equalsIgnoreCase(trimmedVal)) return false;\n return dEfault;\n}\n", "docstring": "/** \n * If value is \"true\", then true is returned. If value is \"false\", then true is returned. Otherwise, default is returned.

Case of value is unimportant. \n */\n", "end_lineno": "146", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.log4j.helpers;\n\nimport java.io.InputStream;\nimport java.io.InterruptedIOException;\nimport java.net.URL;\nimport java.util.Properties;\n\nimport org.apache.log4j.Level;\nimport org.apache.log4j.PropertyConfigurator;\nimport org.apache.log4j.spi.Configurator;\nimport org.apache.log4j.spi.LoggerRepository;\n\n// Contributors: Avy Sharell (sharell@online.fr)\n// Matthieu Verbert (mve@zurich.ibm.com)\n// Colin Sampaleanu\n\n/**\n A convenience class to convert property values to specific types.\n\n @author Ceki Gülcü\n @author Simon Kitching;\n @author Anders Kristensen\n*/\npublic class OptionConverter {\n\n static String DELIM_START = \"${\";\n static char DELIM_STOP = '}';\n static int DELIM_START_LEN = 2;\n static int DELIM_STOP_LEN = 1;\n\n /** OptionConverter is a static class. */\n private OptionConverter() {}\n\n public\n static\n String[] concatanateArrays(String[] l, String[] r) {\n int len = l.length + r.length;\n String[] a = new String[len];\n\n System.arraycopy(l, 0, a, 0, l.length);\n System.arraycopy(r, 0, a, l.length, r.length);\n\n return a;\n }\n\n public\n static\n String convertSpecialChars(String s) {\n char c;\n int len = s.length();\n StringBuffer sbuf = new StringBuffer(len);\n\n int i = 0;\n while(i < len) {\n c = s.charAt(i++);\n if (c == '\\\\') {\n\tc = s.charAt(i++);\n\tif(c == 'n') c = '\\n';\n\telse if(c == 'r') c = '\\r';\n\telse if(c == 't') c = '\\t';\n\telse if(c == 'f') c = '\\f';\n\telse if(c == '\\b') c = '\\b';\n\telse if(c == '\\\"') c = '\\\"';\n\telse if(c == '\\'') c = '\\'';\n\telse if(c == '\\\\') c = '\\\\';\n }\n sbuf.append(c);\n }\n return sbuf.toString();\n }\n\n\n /**\n Very similar to System.getProperty except\n that the {@link SecurityException} is hidden.\n\n @param key The key to search for.\n @param def The default value to return.\n @return the string value of the system property, or the default\n value if there is no property with that key.\n\n @since 1.1 */\n public\n static\n String getSystemProperty(String key, String def) {\n try {\n return System.getProperty(key, def);\n } catch(Throwable e) { // MS-Java throws com.ms.security.SecurityExceptionEx\n LogLog.debug(\"Was not allowed to read system property \\\"\"+key+\"\\\".\");\n return def;\n }\n }\n\n\n public\n static\n Object instantiateByKey(Properties props, String key, Class superClass,\n\t\t\t\tObject defaultValue) {\n\n // Get the value of the property in string form\n String className = findAndSubst(key, props);\n if(className == null) {\n LogLog.error(\"Could not find value for key \" + key);\n return defaultValue;\n }\n // Trim className to avoid trailing spaces that cause problems.\n return OptionConverter.instantiateByClassName(className.trim(), superClass,\n\t\t\t\t\t\t defaultValue);\n }\n\n /**\n If value is \"true\", then true is\n returned. If value is \"false\", then\n true is returned. Otherwise, default is\n returned.\n\n

Case of value is unimportant. */\n public\n static\n boolean toBoolean(String value, boolean dEfault) {\n if(value == null)\n return dEfault;\n String trimmedVal = value.trim();\n if(\"true\".equalsIgnoreCase(trimmedVal))\n return true;\n if(\"false\".equalsIgnoreCase(trimmedVal))\n return false;\n return dEfault;\n }\n\n public\n static\n int toInt(String value, int dEfault) {\n if(value != null) {\n String s = value.trim();\n try {\n\treturn Integer.valueOf(s).intValue();\n }\n catch (NumberFormatException e) {\n\t LogLog.error(\"[\" + s + \"] is not in proper int form.\");\n\te.printStackTrace();\n }\n }\n return dEfault;\n }\n\n /**\n Converts a standard or custom priority level to a Level\n object.

If value is of form\n \"level#classname\", then the specified class' toLevel method\n is called to process the specified level string; if no '#'\n character is present, then the default {@link org.apache.log4j.Level}\n class is used to process the level value.\n\n

As a special case, if the value parameter is\n equal to the string \"NULL\", then the value null will\n be returned.\n\n

If any error occurs while converting the value to a level,\n the defaultValue parameter, which may be\n null, is returned.\n\n

Case of value is insignificant for the level level, but is\n significant for the class name part, if present.\n\n @since 1.1 */\n public\n static\n Level toLevel(String value, Level defaultValue) {\n if(value == null)\n return defaultValue;\n \n value = value.trim();\n\n int hashIndex = value.indexOf('#');\n if (hashIndex == -1) {\n if(\"NULL\".equalsIgnoreCase(value)) {\n\treturn null;\n } else {\n\t// no class name specified : use standard Level class\n\treturn(Level) Level.toLevel(value, defaultValue);\n }\n }\n\n Level result = defaultValue;\n\n String clazz = value.substring(hashIndex+1);\n String levelName = value.substring(0, hashIndex);\n\n // This is degenerate case but you never know.\n if(\"NULL\".equalsIgnoreCase(levelName)) {\n\treturn null;\n }\n\n LogLog.debug(\"toLevel\" + \":class=[\" + clazz + \"]\"\n\t\t + \":pri=[\" + levelName + \"]\");\n\n try {\n Class customLevel = Loader.loadClass(clazz);\n\n // get a ref to the specified class' static method\n // toLevel(String, org.apache.log4j.Level)\n Class[] paramTypes = new Class[] { String.class,\n\t\t\t\t\t org.apache.log4j.Level.class\n };\n java.lang.reflect.Method toLevelMethod =\n customLevel.getMethod(\"toLevel\", paramTypes);\n\n // now call the toLevel method, passing level string + default\n Object[] params = new Object[] {levelName, defaultValue};\n Object o = toLevelMethod.invoke(null, params);\n\n result = (Level) o;\n } catch(ClassNotFoundException e) {\n LogLog.warn(\"custom level class [\" + clazz + \"] not found.\");\n } catch(NoSuchMethodException e) {\n LogLog.warn(\"custom level class [\" + clazz + \"]\"\n + \" does not have a class function toLevel(String, Level)\", e);\n } catch(java.lang.reflect.InvocationTargetException e) {\n if (e.getTargetException() instanceof InterruptedException\n || e.getTargetException() instanceof InterruptedIOException) {\n Thread.currentThread().interrupt();\n }\n LogLog.warn(\"custom level class [\" + clazz + \"]\"\n\t\t + \" could not be instantiated\", e);\n } catch(ClassCastException e) {\n LogLog.warn(\"class [\" + clazz\n + \"] is not a subclass of org.apache.log4j.Level\", e);\n } catch(IllegalAccessException e) {\n LogLog.warn(\"class [\"+clazz+\n\t\t \"] cannot be instantiated due to access restrictions\", e);\n } catch(RuntimeException e) {\n LogLog.warn(\"class [\"+clazz+\"], level [\"+levelName+\n\t\t \"] conversion failed.\", e);\n }\n return result;\n }\n\n public\n static\n long toFileSize(String value, long dEfault) {\n if(value == null)\n return dEfault;\n\n String s = value.trim().toUpperCase();\n long multiplier = 1;\n int index;\n\n if((index = s.indexOf(\"KB\")) != -1) {\n multiplier = 1024;\n s = s.substring(0, index);\n }\n else if((index = s.indexOf(\"MB\")) != -1) {\n multiplier = 1024*1024;\n s = s.substring(0, index);\n }\n else if((index = s.indexOf(\"GB\")) != -1) {\n multiplier = 1024*1024*1024;\n s = s.substring(0, index);\n }\n if(s != null) {\n try {\n\treturn Long.valueOf(s).longValue() * multiplier;\n }\n catch (NumberFormatException e) {\n\tLogLog.error(\"[\" + s + \"] is not in proper int form.\");\n\tLogLog.error(\"[\" + value + \"] not in expected format.\", e);\n }\n }\n return dEfault;\n }\n\n /**\n Find the value corresponding to key in\n props. Then perform variable substitution on the\n found value.\n\n */\n public\n static\n String findAndSubst(String key, Properties props) {\n String value = props.getProperty(key);\n if(value == null)\n return null;\n\n try {\n return substVars(value, props);\n } catch(IllegalArgumentException e) {\n LogLog.error(\"Bad option value [\"+value+\"].\", e);\n return value;\n }\n }\n\n /**\n Instantiate an object given a class name. Check that the\n className is a subclass of\n superClass. If that test fails or the object could\n not be instantiated, then defaultValue is returned.\n\n @param className The fully qualified class name of the object to instantiate.\n @param superClass The class to which the new object should belong.\n @param defaultValue The object to return in case of non-fulfillment\n */\n public\n static\n Object instantiateByClassName(String className, Class superClass,\n\t\t\t\tObject defaultValue) {\n if(className != null) {\n try {\n\tClass classObj = Loader.loadClass(className);\n\tif(!superClass.isAssignableFrom(classObj)) {\n\t LogLog.error(\"A \\\"\"+className+\"\\\" object is not assignable to a \\\"\"+\n\t\t superClass.getName() + \"\\\" variable.\");\n\t LogLog.error(\"The class \\\"\"+ superClass.getName()+\"\\\" was loaded by \");\n\t LogLog.error(\"[\"+superClass.getClassLoader()+\"] whereas object of type \");\n\t LogLog.error(\"\\\"\" +classObj.getName()+\"\\\" was loaded by [\"\n\t\t +classObj.getClassLoader()+\"].\");\n\t return defaultValue;\n\t}\n\treturn classObj.newInstance();\n } catch (ClassNotFoundException e) {\n\t LogLog.error(\"Could not instantiate class [\" + className + \"].\", e);\n } catch (IllegalAccessException e) {\n\t LogLog.error(\"Could not instantiate class [\" + className + \"].\", e);\n } catch (InstantiationException e) {\n LogLog.error(\"Could not instantiate class [\" + className + \"].\", e);\n } catch (RuntimeException e) {\n\t LogLog.error(\"Could not instantiate class [\" + className + \"].\", e);\n }\n }\n return defaultValue;\n }\n\n\n /**\n Perform variable substitution in string val from the\n values of keys found in the system propeties.\n\n

The variable substitution delimeters are ${ and }.\n\n

For example, if the System properties contains \"key=value\", then\n the call\n

\n     String s = OptionConverter.substituteVars(\"Value of key is ${key}.\");\n     
\n\n will set the variable s to \"Value of key is value.\".\n\n

If no value could be found for the specified key, then the\n props parameter is searched, if the value could not\n be found there, then substitution defaults to the empty string.\n\n

For example, if system propeties contains no value for the key\n \"inexistentKey\", then the call\n\n

\n     String s = OptionConverter.subsVars(\"Value of inexistentKey is [${inexistentKey}]\");\n     
\n will set s to \"Value of inexistentKey is []\"\n\n

An {@link java.lang.IllegalArgumentException} is thrown if\n val contains a start delimeter \"${\" which is not\n balanced by a stop delimeter \"}\".

\n\n

Author Avy Sharell

\n\n @param val The string on which variable substitution is performed.\n @throws IllegalArgumentException if val is malformed.\n\n */\n public static\n String substVars(String val, Properties props) throws\n IllegalArgumentException {\n\n StringBuffer sbuf = new StringBuffer();\n\n int i = 0;\n int j, k;\n\n while(true) {\n j=val.indexOf(DELIM_START, i);\n if(j == -1) {\n\t// no more variables\n\tif(i==0) { // this is a simple string\n\t return val;\n\t} else { // add the tail string which contails no variables and return the result.\n\t sbuf.append(val.substring(i, val.length()));\n\t return sbuf.toString();\n\t}\n } else {\n\tsbuf.append(val.substring(i, j));\n\tk = val.indexOf(DELIM_STOP, j);\n\tif(k == -1) {\n\t throw new IllegalArgumentException('\"'+val+\n\t\t \"\\\" has no closing brace. Opening brace at position \" + j\n\t\t\t\t\t + '.');\n\t} else {\n\t j += DELIM_START_LEN;\n\t String key = val.substring(j, k);\n\t // first try in System properties\n\t String replacement = getSystemProperty(key, null);\n\t // then try props parameter\n\t if(replacement == null && props != null) {\n\t replacement = props.getProperty(key);\n\t }\n\n\t if(replacement != null) {\n\t // Do variable substitution on the replacement string\n\t // such that we can solve \"Hello ${x2}\" as \"Hello p1\" \n // the where the properties are\n\t // x1=p1\n // x2=${x1}\n\t String recursiveReplacement = substVars(replacement, props);\n\t sbuf.append(recursiveReplacement);\n\t }\n\t i = k + DELIM_STOP_LEN;\n\t}\n }\n }\n }\n\n /**\n * Configure log4j given an {@link InputStream}.\n * \n *

\n * The InputStream will be interpreted by a new instance of a log4j configurator.\n *

\n *

\n * All configurations steps are taken on the hierarchy passed as a parameter.\n *

\n * \n * @param inputStream\n * The configuration input stream.\n * @param clazz\n * The class name, of the log4j configurator which will parse the inputStream. This must be a\n * subclass of {@link Configurator}, or null. If this value is null then a default configurator of\n * {@link PropertyConfigurator} is used.\n * @param hierarchy\n * The {@link org.apache.log4j.Hierarchy} to act on.\n * @since 1.2.17\n */\n\nstatic\npublic\nvoid selectAndConfigure(InputStream inputStream, String clazz, LoggerRepository hierarchy) {\nConfigurator configurator = null;\n\nif(clazz != null) {\n LogLog.debug(\"Preferred configurator class: \" + clazz);\n configurator = (Configurator) instantiateByClassName(clazz,\n Configurator.class,\n null);\n if(configurator == null) {\n LogLog.error(\"Could not instantiate configurator [\"+clazz+\"].\");\n return;\n }\n} else {\n configurator = new PropertyConfigurator();\n}\n\nconfigurator.doConfigure(inputStream, hierarchy);\n}\n\n\n /**\n Configure log4j given a URL.\n\n

The url must point to a file or resource which will be interpreted by\n a new instance of a log4j configurator.\n\n

All configurations steps are taken on the\n hierarchy passed as a parameter.\n\n

\n @param url The location of the configuration file or resource.\n @param clazz The classname, of the log4j configurator which will parse\n the file or resource at url. This must be a subclass of\n {@link Configurator}, or null. If this value is null then a default\n configurator of {@link PropertyConfigurator} is used, unless the\n filename pointed to by url ends in '.xml', in which case\n {@link org.apache.log4j.xml.DOMConfigurator} is used.\n @param hierarchy The {@link org.apache.log4j.Hierarchy} to act on.\n\n @since 1.1.4 */\n\n static\n public\n void selectAndConfigure(URL url, String clazz, LoggerRepository hierarchy) {\n Configurator configurator = null;\n String filename = url.getFile();\n\n if(clazz == null && filename != null && filename.endsWith(\".xml\")) {\n clazz = \"org.apache.log4j.xml.DOMConfigurator\";\n }\n\n if(clazz != null) {\n LogLog.debug(\"Preferred configurator class: \" + clazz);\n configurator = (Configurator) instantiateByClassName(clazz,\n\t\t\t\t\t\t\t Configurator.class,\n\t\t\t\t\t\t\t null);\n if(configurator == null) {\n \t LogLog.error(\"Could not instantiate configurator [\"+clazz+\"].\");\n \t return;\n }\n } else {\n configurator = new PropertyConfigurator();\n }\n\n configurator.doConfigure(url, hierarchy);\n }\n}\n", "file_name": "OptionConverter.java", "human_label": "Check whether a string is true or false after ignore cases and trim the whitespaces at both ends. If so, its boolean value is returned. Otherwise, dEfault is returned.", "level": "self_contained", "lineno": "128", "name": "toBoolean", "oracle_context": "{ \"apis\" : \"[trim, equalsIgnoreCase]\", \"classes\" : \"[String]\", \"vars\" : \"[]\" }", "package": "org.apache.log4j.helpers", "project": "logging-log4j1-main" }, { "_id": "6367676a1a6d9265ec0181cd", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static String trimLeadingWhitespace(String str){\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb=new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n}\n", "docstring": "/** \n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n", "end_lineno": "236", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *

\n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
\n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Trim the leading whitespaces in a string.", "level": "class_runnable", "lineno": "221", "name": "trimLeadingWhitespace", "oracle_context": "{ \"apis\" : \"[hasLength, length, isWhitespace, charAt, deleteCharAt, toString]\", \"classes\" : \"[StringBuilder]\", \"vars\" : \"[]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636766fe1a6d9265ec01782a", "all_context": "{ \"class_level\" : \"import java.io.ByteArrayOutputStream;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nint SKIP_CODE;\\nint SKIP_DEBUG;\\nint SKIP_FRAMES;\\nint EXPAND_FRAMES;\\nint EXPAND_ASM_INSNS;\\nint INPUT_STREAM_DATA_CHUNK_SIZE;\\nbyte[] b;\\nbyte[] classFileBuffer;\\nint[] cpInfoOffsets;\\nString[] constantUtf8Values;\\nConstantDynamic[] constantDynamicValues;\\nint[] bootstrapMethodOffsets;\\nint maxStringLength;\\nint header;\\nClassReader(byte[] classFile);\\nClassReader(byte[] classFileBuffer,int classFileOffset,int classFileLength);\\nClassReader(byte[] classFileBuffer,int classFileOffset,boolean checkClassVersion);\\nClassReader(InputStream inputStream);\\nClassReader(String className);\\ngetAccess();\\ngetClassName();\\ngetSuperName();\\ngetInterfaces();\\naccept(ClassVisitor classVisitor,int parsingOptions);\\naccept(ClassVisitor classVisitor,Attribute[] attributePrototypes,int parsingOptions);\\nreadModuleAttributes(ClassVisitor classVisitor,Context context,int moduleOffset,int modulePackagesOffset,String moduleMainClass);\\nreadRecordComponent(ClassVisitor classVisitor,Context context,int recordComponentOffset);\\nreadField(ClassVisitor classVisitor,Context context,int fieldInfoOffset);\\nreadMethod(ClassVisitor classVisitor,Context context,int methodInfoOffset);\\nreadCode(MethodVisitor methodVisitor,Context context,int codeOffset);\\nreadLabel(int bytecodeOffset,Label[] labels);\\ncreateLabel(int bytecodeOffset,Label[] labels);\\ncreateDebugLabel(int bytecodeOffset,Label[] labels);\\nreadTypeAnnotations(MethodVisitor methodVisitor,Context context,int runtimeTypeAnnotationsOffset,boolean visible);\\ngetTypeAnnotationBytecodeOffset(int[] typeAnnotationOffsets,int typeAnnotationIndex);\\nreadTypeAnnotationTarget(Context context,int typeAnnotationOffset);\\nreadParameterAnnotations(MethodVisitor methodVisitor,Context context,int runtimeParameterAnnotationsOffset,boolean visible);\\nreadElementValues(AnnotationVisitor annotationVisitor,int annotationOffset,boolean named,char[] charBuffer);\\nreadElementValue(AnnotationVisitor annotationVisitor,int elementValueOffset,String elementName,char[] charBuffer);\\ncomputeImplicitFrame(Context context);\\nreadStackMapFrame(int stackMapFrameOffset,boolean compressed,boolean expand,Context context);\\nreadVerificationTypeInfo(int verificationTypeInfoOffset,Object[] frame,int index,char[] charBuffer,Label[] labels);\\ngetFirstAttributeOffset();\\nreadBootstrapMethodsAttribute(int maxStringLength);\\nreadAttribute(Attribute[] attributePrototypes,String type,int offset,int length,char[] charBuffer,int codeAttributeOffset,Label[] labels);\\ngetItemCount();\\ngetItem(int constantPoolEntryIndex);\\ngetMaxStringLength();\\nreadByte(int offset);\\nreadUnsignedShort(int offset);\\nreadShort(int offset);\\nreadInt(int offset);\\nreadLong(int offset);\\nreadUTF8(int offset,char[] charBuffer);\\nreadUtf(int constantPoolEntryIndex,char[] charBuffer);\\nreadUtf(int utfOffset,int utfLength,char[] charBuffer);\\nreadStringish(int offset,char[] charBuffer);\\nreadClass(int offset,char[] charBuffer);\\nreadModule(int offset,char[] charBuffer);\\nreadPackage(int offset,char[] charBuffer);\\nreadConstantDynamic(int constantPoolEntryIndex,char[] charBuffer);\\nreadConst(int constantPoolEntryIndex,char[] charBuffer);\\nreadStream(InputStream inputStream,boolean close);\\n\", \"repo_level\" : \"\" }", "class_name": "ClassReader", "code": "final String readUtf(final int constantPoolEntryIndex,final char[] charBuffer){\n String value=constantUtf8Values[constantPoolEntryIndex];\n if (value != null) {\n return value;\n }\n int cpInfoOffset=cpInfoOffsets[constantPoolEntryIndex];\n return constantUtf8Values[constantPoolEntryIndex]=readUtf(cpInfoOffset + 2,readUnsignedShort(cpInfoOffset),charBuffer);\n}\n", "docstring": "/** \n * Reads a CONSTANT_Utf8 constant pool entry in {@link #classFileBuffer}.\n * @param constantPoolEntryIndex the index of a CONSTANT_Utf8 entry in the class's constant pooltable.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficientlylarge. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Utf8 entry.\n */\n", "end_lineno": "3172", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage net.hasor.utils.asm;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/**\n * A parser to make a {@link ClassVisitor} visit a ClassFile structure, as defined in the Java\n * Virtual Machine Specification (JVMS). This class parses the ClassFile content and calls the\n * appropriate visit methods of a given {@link ClassVisitor} for each field, method and bytecode\n * instruction encountered.\n *\n * @see JVMS 4\n * @author Eric Bruneton\n * @author Eugene Kuleshov\n */\npublic class ClassReader {\n /**\n * A flag to skip the Code attributes. If this flag is set the Code attributes are neither parsed\n * nor visited.\n */\n public static final int SKIP_CODE = 1;\n /**\n * A flag to skip the SourceFile, SourceDebugExtension, LocalVariableTable,\n * LocalVariableTypeTable, LineNumberTable and MethodParameters attributes. If this flag is set\n * these attributes are neither parsed nor visited (i.e. {@link ClassVisitor#visitSource}, {@link\n * MethodVisitor#visitLocalVariable}, {@link MethodVisitor#visitLineNumber} and {@link\n * MethodVisitor#visitParameter} are not called).\n */\n public static final int SKIP_DEBUG = 2;\n /**\n * A flag to skip the StackMap and StackMapTable attributes. If this flag is set these attributes\n * are neither parsed nor visited (i.e. {@link MethodVisitor#visitFrame} is not called). This flag\n * is useful when the {@link ClassWriter#COMPUTE_FRAMES} option is used: it avoids visiting frames\n * that will be ignored and recomputed from scratch.\n */\n public static final int SKIP_FRAMES = 4;\n /**\n * A flag to expand the stack map frames. By default stack map frames are visited in their\n * original format (i.e. \"expanded\" for classes whose version is less than V1_6, and \"compressed\"\n * for the other classes). If this flag is set, stack map frames are always visited in expanded\n * format (this option adds a decompression/compression step in ClassReader and ClassWriter which\n * degrades performance quite a lot).\n */\n public static final int EXPAND_FRAMES = 8;\n /**\n * A flag to expand the ASM specific instructions into an equivalent sequence of standard bytecode\n * instructions. When resolving a forward jump it may happen that the signed 2 bytes offset\n * reserved for it is not sufficient to store the bytecode offset. In this case the jump\n * instruction is replaced with a temporary ASM specific instruction using an unsigned 2 bytes\n * offset (see {@link Label#resolve}). This internal flag is used to re-read classes containing\n * such instructions, in order to replace them with standard instructions. In addition, when this\n * flag is used, goto_w and jsr_w are not converted into goto and jsr, to make sure that\n * infinite loops where a goto_w is replaced with a goto in ClassReader and converted back to a\n * goto_w in ClassWriter cannot occur.\n */\n static final int EXPAND_ASM_INSNS = 256;\n /** The size of the temporary byte array used to read class input streams chunk by chunk. */\n private static final int INPUT_STREAM_DATA_CHUNK_SIZE = 4096;\n /**\n * A byte array containing the JVMS ClassFile structure to be parsed.\n *\n * @deprecated Use {@link #readByte(int)} and the other read methods instead. This field will\n * eventually be deleted.\n */\n @Deprecated\n // DontCheck(MemberName): can't be renamed (for backward binary compatibility).\n public final byte[] b;\n /**\n * A byte array containing the JVMS ClassFile structure to be parsed. The content of this array\n * must not be modified. This field is intended for {@link Attribute} sub classes, and is normally\n * not needed by class visitors.\n *\n *

NOTE: the ClassFile structure can start at any offset within this array, i.e. it does not\n * necessarily start at offset 0. Use {@link #getItem} and {@link #header} to get correct\n * ClassFile element offsets within this byte array.\n */\n final byte[] classFileBuffer;\n /**\n * The offset in bytes, in {@link #classFileBuffer}, of each cp_info entry of the ClassFile's\n * constant_pool array, plus one. In other words, the offset of constant pool entry i is\n * given by cpInfoOffsets[i] - 1, i.e. its cp_info's tag field is given by b[cpInfoOffsets[i] -\n * 1].\n */\n private final int[] cpInfoOffsets;\n /**\n * The String objects corresponding to the CONSTANT_Utf8 constant pool items. This cache avoids\n * multiple parsing of a given CONSTANT_Utf8 constant pool item.\n */\n private final String[] constantUtf8Values;\n /**\n * The ConstantDynamic objects corresponding to the CONSTANT_Dynamic constant pool items. This\n * cache avoids multiple parsing of a given CONSTANT_Dynamic constant pool item.\n */\n private final ConstantDynamic[] constantDynamicValues;\n /**\n * The start offsets in {@link #classFileBuffer} of each element of the bootstrap_methods array\n * (in the BootstrapMethods attribute).\n *\n * @see JVMS\n * 4.7.23\n */\n private final int[] bootstrapMethodOffsets;\n /**\n * A conservative estimate of the maximum length of the strings contained in the constant pool of\n * the class.\n */\n private final int maxStringLength;\n /** The offset in bytes of the ClassFile's access_flags field. */\n public final int header;\n // -----------------------------------------------------------------------------------------------\n // Constructors\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param classFile the JVMS ClassFile structure to be read.\n */\n public ClassReader(final byte[] classFile) {\n this(classFile, 0, classFile.length);\n }\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read.\n * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read.\n * @param classFileLength the length in bytes of the ClassFile to be read.\n */\n public ClassReader(final byte[] classFileBuffer, final int classFileOffset, final int classFileLength) { // NOPMD(UnusedFormalParameter) used for backward compatibility.\n this(classFileBuffer, classFileOffset, /* checkClassVersion = */ true);\n }\n\n /**\n * Constructs a new {@link ClassReader} object. This internal constructor must not be exposed\n * as a public API.\n *\n * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read.\n * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read.\n * @param checkClassVersion whether to check the class version or not.\n */\n ClassReader(final byte[] classFileBuffer, final int classFileOffset, final boolean checkClassVersion) {\n this.classFileBuffer = classFileBuffer;\n this.b = classFileBuffer;\n // Check the class' major_version. This field is after the magic and minor_version fields, which\n // use 4 and 2 bytes respectively.\n if (checkClassVersion && readShort(classFileOffset + 6) > Opcodes.V15) {\n throw new IllegalArgumentException(\"Unsupported class file major version \" + readShort(classFileOffset + 6));\n }\n // Create the constant pool arrays. The constant_pool_count field is after the magic,\n // minor_version and major_version fields, which use 4, 2 and 2 bytes respectively.\n int constantPoolCount = readUnsignedShort(classFileOffset + 8);\n cpInfoOffsets = new int[constantPoolCount];\n constantUtf8Values = new String[constantPoolCount];\n // Compute the offset of each constant pool entry, as well as a conservative estimate of the\n // maximum length of the constant pool strings. The first constant pool entry is after the\n // magic, minor_version, major_version and constant_pool_count fields, which use 4, 2, 2 and 2\n // bytes respectively.\n int currentCpInfoIndex = 1;\n int currentCpInfoOffset = classFileOffset + 10;\n int currentMaxStringLength = 0;\n boolean hasBootstrapMethods = false;\n boolean hasConstantDynamic = false;\n // The offset of the other entries depend on the total size of all the previous entries.\n while (currentCpInfoIndex < constantPoolCount) {\n cpInfoOffsets[currentCpInfoIndex++] = currentCpInfoOffset + 1;\n int cpInfoSize;\n switch (classFileBuffer[currentCpInfoOffset]) {\n case Symbol.CONSTANT_FIELDREF_TAG:\n case Symbol.CONSTANT_METHODREF_TAG:\n case Symbol.CONSTANT_INTERFACE_METHODREF_TAG:\n case Symbol.CONSTANT_INTEGER_TAG:\n case Symbol.CONSTANT_FLOAT_TAG:\n case Symbol.CONSTANT_NAME_AND_TYPE_TAG:\n cpInfoSize = 5;\n break;\n case Symbol.CONSTANT_DYNAMIC_TAG:\n cpInfoSize = 5;\n hasBootstrapMethods = true;\n hasConstantDynamic = true;\n break;\n case Symbol.CONSTANT_INVOKE_DYNAMIC_TAG:\n cpInfoSize = 5;\n hasBootstrapMethods = true;\n break;\n case Symbol.CONSTANT_LONG_TAG:\n case Symbol.CONSTANT_DOUBLE_TAG:\n cpInfoSize = 9;\n currentCpInfoIndex++;\n break;\n case Symbol.CONSTANT_UTF8_TAG:\n cpInfoSize = 3 + readUnsignedShort(currentCpInfoOffset + 1);\n if (cpInfoSize > currentMaxStringLength) {\n // The size in bytes of this CONSTANT_Utf8 structure provides a conservative estimate\n // of the length in characters of the corresponding string, and is much cheaper to\n // compute than this exact length.\n currentMaxStringLength = cpInfoSize;\n }\n break;\n case Symbol.CONSTANT_METHOD_HANDLE_TAG:\n cpInfoSize = 4;\n break;\n case Symbol.CONSTANT_CLASS_TAG:\n case Symbol.CONSTANT_STRING_TAG:\n case Symbol.CONSTANT_METHOD_TYPE_TAG:\n case Symbol.CONSTANT_PACKAGE_TAG:\n case Symbol.CONSTANT_MODULE_TAG:\n cpInfoSize = 3;\n break;\n default:\n throw new IllegalArgumentException();\n }\n currentCpInfoOffset += cpInfoSize;\n }\n maxStringLength = currentMaxStringLength;\n // The Classfile's access_flags field is just after the last constant pool entry.\n header = currentCpInfoOffset;\n // Allocate the cache of ConstantDynamic values, if there is at least one.\n constantDynamicValues = hasConstantDynamic ? new ConstantDynamic[constantPoolCount] : null;\n // Read the BootstrapMethods attribute, if any (only get the offset of each method).\n bootstrapMethodOffsets = hasBootstrapMethods ? readBootstrapMethodsAttribute(currentMaxStringLength) : null;\n }\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param inputStream an input stream of the JVMS ClassFile structure to be read. This input\n * stream must contain nothing more than the ClassFile structure itself. It is read from its\n * current position to its end.\n * @throws IOException if a problem occurs during reading.\n */\n public ClassReader(final InputStream inputStream) throws IOException {\n this(readStream(inputStream, false));\n }\n\n /**\n * Constructs a new {@link ClassReader} object.\n *\n * @param className the fully qualified name of the class to be read. The ClassFile structure is\n * retrieved with the current class loader's {@link ClassLoader#getSystemResourceAsStream}.\n * @throws IOException if an exception occurs during reading.\n */\n public ClassReader(final String className) throws IOException {\n this(readStream(ClassLoader.getSystemResourceAsStream(className.replace('.', '/') + \".class\"), true));\n }\n\n /**\n * Reads the given input stream and returns its content as a byte array.\n *\n * @param inputStream an input stream.\n * @param close true to close the input stream after reading.\n * @return the content of the given input stream.\n * @throws IOException if a problem occurs during reading.\n */\n private static byte[] readStream(final InputStream inputStream, final boolean close) throws IOException {\n if (inputStream == null) {\n throw new IOException(\"Class not found\");\n }\n try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {\n byte[] data = new byte[INPUT_STREAM_DATA_CHUNK_SIZE];\n int bytesRead;\n while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {\n outputStream.write(data, 0, bytesRead);\n }\n outputStream.flush();\n return outputStream.toByteArray();\n } finally {\n if (close) {\n inputStream.close();\n }\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Accessors\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the class's access flags (see {@link Opcodes}). This value may not reflect Deprecated\n * and Synthetic flags when bytecode is before 1.5 and those flags are represented by attributes.\n *\n * @return the class access flags.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public int getAccess() {\n return readUnsignedShort(header);\n }\n\n /**\n * Returns the internal name of the class (see {@link Type#getInternalName()}).\n *\n * @return the internal class name.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public String getClassName() {\n // this_class is just after the access_flags field (using 2 bytes).\n return readClass(header + 2, new char[maxStringLength]);\n }\n\n /**\n * Returns the internal of name of the super class (see {@link Type#getInternalName()}). For\n * interfaces, the super class is {@link Object}.\n *\n * @return the internal name of the super class, or {@literal null} for {@link Object} class.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public String getSuperName() {\n // super_class is after the access_flags and this_class fields (2 bytes each).\n return readClass(header + 4, new char[maxStringLength]);\n }\n\n /**\n * Returns the internal names of the implemented interfaces (see {@link Type#getInternalName()}).\n *\n * @return the internal names of the directly implemented interfaces. Inherited implemented\n * interfaces are not returned.\n * @see ClassVisitor#visit(int, int, String, String, String, String[])\n */\n public String[] getInterfaces() {\n // interfaces_count is after the access_flags, this_class and super_class fields (2 bytes each).\n int currentOffset = header + 6;\n int interfacesCount = readUnsignedShort(currentOffset);\n String[] interfaces = new String[interfacesCount];\n if (interfacesCount > 0) {\n char[] charBuffer = new char[maxStringLength];\n for (int i = 0; i < interfacesCount; ++i) {\n currentOffset += 2;\n interfaces[i] = readClass(currentOffset, charBuffer);\n }\n }\n return interfaces;\n }\n // -----------------------------------------------------------------------------------------------\n // Public methods\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this\n * {@link ClassReader}.\n *\n * @param classVisitor the visitor that must visit this class.\n * @param parsingOptions the options to use to parse this class. One or more of {@link\n * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}.\n */\n public void accept(final ClassVisitor classVisitor, final int parsingOptions) {\n accept(classVisitor, new Attribute[0], parsingOptions);\n }\n\n /**\n * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this\n * {@link ClassReader}.\n *\n * @param classVisitor the visitor that must visit this class.\n * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of\n * the class. Any attribute whose type is not equal to the type of one the prototypes will not\n * be parsed: its byte array value will be passed unchanged to the ClassWriter. This may\n * corrupt it if this value contains references to the constant pool, or has syntactic or\n * semantic links with a class element that has been transformed by a class adapter between\n * the reader and the writer.\n * @param parsingOptions the options to use to parse this class. One or more of {@link\n * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}.\n */\n public void accept(final ClassVisitor classVisitor, final Attribute[] attributePrototypes, final int parsingOptions) {\n Context context = new Context();\n context.attributePrototypes = attributePrototypes;\n context.parsingOptions = parsingOptions;\n context.charBuffer = new char[maxStringLength];\n // Read the access_flags, this_class, super_class, interface_count and interfaces fields.\n char[] charBuffer = context.charBuffer;\n int currentOffset = header;\n int accessFlags = readUnsignedShort(currentOffset);\n String thisClass = readClass(currentOffset + 2, charBuffer);\n String superClass = readClass(currentOffset + 4, charBuffer);\n String[] interfaces = new String[readUnsignedShort(currentOffset + 6)];\n currentOffset += 8;\n for (int i = 0; i < interfaces.length; ++i) {\n interfaces[i] = readClass(currentOffset, charBuffer);\n currentOffset += 2;\n }\n // Read the class attributes (the variables are ordered as in Section 4.7 of the JVMS).\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The offset of the InnerClasses attribute, or 0.\n int innerClassesOffset = 0;\n // - The offset of the EnclosingMethod attribute, or 0.\n int enclosingMethodOffset = 0;\n // - The string corresponding to the Signature attribute, or null.\n String signature = null;\n // - The string corresponding to the SourceFile attribute, or null.\n String sourceFile = null;\n // - The string corresponding to the SourceDebugExtension attribute, or null.\n String sourceDebugExtension = null;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The offset of the Module attribute, or 0.\n int moduleOffset = 0;\n // - The offset of the ModulePackages attribute, or 0.\n int modulePackagesOffset = 0;\n // - The string corresponding to the ModuleMainClass attribute, or null.\n String moduleMainClass = null;\n // - The string corresponding to the NestHost attribute, or null.\n String nestHostClass = null;\n // - The offset of the NestMembers attribute, or 0.\n int nestMembersOffset = 0;\n // - The offset of the PermittedSubtypes attribute, or 0\n int permittedSubtypesOffset = 0;\n // - The offset of the Record attribute, or 0.\n int recordOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int currentAttributeOffset = getFirstAttributeOffset();\n for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentAttributeOffset, charBuffer);\n int attributeLength = readInt(currentAttributeOffset + 2);\n currentAttributeOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.SOURCE_FILE.equals(attributeName)) {\n sourceFile = readUTF8(currentAttributeOffset, charBuffer);\n } else if (Constants.INNER_CLASSES.equals(attributeName)) {\n innerClassesOffset = currentAttributeOffset;\n } else if (Constants.ENCLOSING_METHOD.equals(attributeName)) {\n enclosingMethodOffset = currentAttributeOffset;\n } else if (Constants.NEST_HOST.equals(attributeName)) {\n nestHostClass = readClass(currentAttributeOffset, charBuffer);\n } else if (Constants.NEST_MEMBERS.equals(attributeName)) {\n nestMembersOffset = currentAttributeOffset;\n } else if (Constants.PERMITTED_SUBTYPES.equals(attributeName)) {\n permittedSubtypesOffset = currentAttributeOffset;\n } else if (Constants.SIGNATURE.equals(attributeName)) {\n signature = readUTF8(currentAttributeOffset, charBuffer);\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.SYNTHETIC.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_SYNTHETIC;\n } else if (Constants.SOURCE_DEBUG_EXTENSION.equals(attributeName)) {\n sourceDebugExtension = readUtf(currentAttributeOffset, attributeLength, new char[attributeLength]);\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentAttributeOffset;\n } else if (Constants.RECORD.equals(attributeName)) {\n recordOffset = currentAttributeOffset;\n } else if (Constants.MODULE.equals(attributeName)) {\n moduleOffset = currentAttributeOffset;\n } else if (Constants.MODULE_MAIN_CLASS.equals(attributeName)) {\n moduleMainClass = readClass(currentAttributeOffset, charBuffer);\n } else if (Constants.MODULE_PACKAGES.equals(attributeName)) {\n modulePackagesOffset = currentAttributeOffset;\n } else if (!Constants.BOOTSTRAP_METHODS.equals(attributeName)) {\n // The BootstrapMethods attribute is read in the constructor.\n Attribute attribute = readAttribute(attributePrototypes, attributeName, currentAttributeOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentAttributeOffset += attributeLength;\n }\n // Visit the class declaration. The minor_version and major_version fields start 6 bytes before\n // the first constant pool entry, which itself starts at cpInfoOffsets[1] - 1 (by definition).\n classVisitor.visit(readInt(cpInfoOffsets[1] - 7), accessFlags, thisClass, signature, superClass, interfaces);\n // Visit the SourceFile and SourceDebugExtenstion attributes.\n if ((parsingOptions & SKIP_DEBUG) == 0 && (sourceFile != null || sourceDebugExtension != null)) {\n classVisitor.visitSource(sourceFile, sourceDebugExtension);\n }\n // Visit the Module, ModulePackages and ModuleMainClass attributes.\n if (moduleOffset != 0) {\n readModuleAttributes(classVisitor, context, moduleOffset, modulePackagesOffset, moduleMainClass);\n }\n // Visit the NestHost attribute.\n if (nestHostClass != null) {\n classVisitor.visitNestHost(nestHostClass);\n }\n // Visit the EnclosingMethod attribute.\n if (enclosingMethodOffset != 0) {\n String className = readClass(enclosingMethodOffset, charBuffer);\n int methodIndex = readUnsignedShort(enclosingMethodOffset + 2);\n String name = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex], charBuffer);\n String type = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex] + 2, charBuffer);\n classVisitor.visitOuterClass(className, name, type);\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(classVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in ClassWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n classVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the NestedMembers attribute.\n if (nestMembersOffset != 0) {\n int numberOfNestMembers = readUnsignedShort(nestMembersOffset);\n int currentNestMemberOffset = nestMembersOffset + 2;\n while (numberOfNestMembers-- > 0) {\n classVisitor.visitNestMember(readClass(currentNestMemberOffset, charBuffer));\n currentNestMemberOffset += 2;\n }\n }\n // Visit the PermittedSubtypes attribute.\n if (permittedSubtypesOffset != 0) {\n int numberOfPermittedSubtypes = readUnsignedShort(permittedSubtypesOffset);\n int currentPermittedSubtypeOffset = permittedSubtypesOffset + 2;\n while (numberOfPermittedSubtypes-- > 0) {\n classVisitor.visitPermittedSubtypeExperimental(readClass(currentPermittedSubtypeOffset, charBuffer));\n currentPermittedSubtypeOffset += 2;\n }\n }\n // Visit the InnerClasses attribute.\n if (innerClassesOffset != 0) {\n int numberOfClasses = readUnsignedShort(innerClassesOffset);\n int currentClassesOffset = innerClassesOffset + 2;\n while (numberOfClasses-- > 0) {\n classVisitor.visitInnerClass(readClass(currentClassesOffset, charBuffer), readClass(currentClassesOffset + 2, charBuffer), readUTF8(currentClassesOffset + 4, charBuffer), readUnsignedShort(currentClassesOffset + 6));\n currentClassesOffset += 8;\n }\n }\n // Visit Record components.\n if (recordOffset != 0) {\n int recordComponentsCount = readUnsignedShort(recordOffset);\n recordOffset += 2;\n while (recordComponentsCount-- > 0) {\n recordOffset = readRecordComponent(classVisitor, context, recordOffset);\n }\n }\n // Visit the fields and methods.\n int fieldsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (fieldsCount-- > 0) {\n currentOffset = readField(classVisitor, context, currentOffset);\n }\n int methodsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (methodsCount-- > 0) {\n currentOffset = readMethod(classVisitor, context, currentOffset);\n }\n // Visit the end of the class.\n classVisitor.visitEnd();\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse modules, fields and methods\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Reads the Module, ModulePackages and ModuleMainClass attributes and visit them.\n *\n * @param classVisitor the current class visitor\n * @param context information about the class being parsed.\n * @param moduleOffset the offset of the Module attribute (excluding the attribute_info's\n * attribute_name_index and attribute_length fields).\n * @param modulePackagesOffset the offset of the ModulePackages attribute (excluding the\n * attribute_info's attribute_name_index and attribute_length fields), or 0.\n * @param moduleMainClass the string corresponding to the ModuleMainClass attribute, or {@literal\n * null}.\n */\n private void readModuleAttributes(final ClassVisitor classVisitor, final Context context, final int moduleOffset, final int modulePackagesOffset, final String moduleMainClass) {\n char[] buffer = context.charBuffer;\n // Read the module_name_index, module_flags and module_version_index fields and visit them.\n int currentOffset = moduleOffset;\n String moduleName = readModule(currentOffset, buffer);\n int moduleFlags = readUnsignedShort(currentOffset + 2);\n String moduleVersion = readUTF8(currentOffset + 4, buffer);\n currentOffset += 6;\n ModuleVisitor moduleVisitor = classVisitor.visitModule(moduleName, moduleFlags, moduleVersion);\n if (moduleVisitor == null) {\n return;\n }\n // Visit the ModuleMainClass attribute.\n if (moduleMainClass != null) {\n moduleVisitor.visitMainClass(moduleMainClass);\n }\n // Visit the ModulePackages attribute.\n if (modulePackagesOffset != 0) {\n int packageCount = readUnsignedShort(modulePackagesOffset);\n int currentPackageOffset = modulePackagesOffset + 2;\n while (packageCount-- > 0) {\n moduleVisitor.visitPackage(readPackage(currentPackageOffset, buffer));\n currentPackageOffset += 2;\n }\n }\n // Read the 'requires_count' and 'requires' fields.\n int requiresCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (requiresCount-- > 0) {\n // Read the requires_index, requires_flags and requires_version fields and visit them.\n String requires = readModule(currentOffset, buffer);\n int requiresFlags = readUnsignedShort(currentOffset + 2);\n String requiresVersion = readUTF8(currentOffset + 4, buffer);\n currentOffset += 6;\n moduleVisitor.visitRequire(requires, requiresFlags, requiresVersion);\n }\n // Read the 'exports_count' and 'exports' fields.\n int exportsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (exportsCount-- > 0) {\n // Read the exports_index, exports_flags, exports_to_count and exports_to_index fields\n // and visit them.\n String exports = readPackage(currentOffset, buffer);\n int exportsFlags = readUnsignedShort(currentOffset + 2);\n int exportsToCount = readUnsignedShort(currentOffset + 4);\n currentOffset += 6;\n String[] exportsTo = null;\n if (exportsToCount != 0) {\n exportsTo = new String[exportsToCount];\n for (int i = 0; i < exportsToCount; ++i) {\n exportsTo[i] = readModule(currentOffset, buffer);\n currentOffset += 2;\n }\n }\n moduleVisitor.visitExport(exports, exportsFlags, exportsTo);\n }\n // Reads the 'opens_count' and 'opens' fields.\n int opensCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (opensCount-- > 0) {\n // Read the opens_index, opens_flags, opens_to_count and opens_to_index fields and visit them.\n String opens = readPackage(currentOffset, buffer);\n int opensFlags = readUnsignedShort(currentOffset + 2);\n int opensToCount = readUnsignedShort(currentOffset + 4);\n currentOffset += 6;\n String[] opensTo = null;\n if (opensToCount != 0) {\n opensTo = new String[opensToCount];\n for (int i = 0; i < opensToCount; ++i) {\n opensTo[i] = readModule(currentOffset, buffer);\n currentOffset += 2;\n }\n }\n moduleVisitor.visitOpen(opens, opensFlags, opensTo);\n }\n // Read the 'uses_count' and 'uses' fields.\n int usesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (usesCount-- > 0) {\n moduleVisitor.visitUse(readClass(currentOffset, buffer));\n currentOffset += 2;\n }\n // Read the 'provides_count' and 'provides' fields.\n int providesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (providesCount-- > 0) {\n // Read the provides_index, provides_with_count and provides_with_index fields and visit them.\n String provides = readClass(currentOffset, buffer);\n int providesWithCount = readUnsignedShort(currentOffset + 2);\n currentOffset += 4;\n String[] providesWith = new String[providesWithCount];\n for (int i = 0; i < providesWithCount; ++i) {\n providesWith[i] = readClass(currentOffset, buffer);\n currentOffset += 2;\n }\n moduleVisitor.visitProvide(provides, providesWith);\n }\n // Visit the end of the module attributes.\n moduleVisitor.visitEnd();\n }\n\n /**\n * Reads a record component and visit it.\n *\n * @param classVisitor the current class visitor\n * @param context information about the class being parsed.\n * @param recordComponentOffset the offset of the current record component.\n * @return the offset of the first byte following the record component.\n */\n private int readRecordComponent(final ClassVisitor classVisitor, final Context context, final int recordComponentOffset) {\n char[] charBuffer = context.charBuffer;\n int currentOffset = recordComponentOffset;\n String name = readUTF8(currentOffset, charBuffer);\n String descriptor = readUTF8(currentOffset + 2, charBuffer);\n currentOffset += 4;\n // Read the record component attributes (the variables are ordered as in Section 4.7 of the\n // JVMS).\n int accessFlags = 0;\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The string corresponding to the Signature attribute, or null.\n String signature = null;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.SIGNATURE.equals(attributeName)) {\n signature = readUTF8(currentOffset, charBuffer);\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentOffset;\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n RecordComponentVisitor recordComponentVisitor = classVisitor.visitRecordComponentExperimental(accessFlags, name, descriptor, signature);\n if (recordComponentVisitor == null) {\n return currentOffset;\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitAnnotationExperimental(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitAnnotationExperimental(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitTypeAnnotationExperimental(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(recordComponentVisitor.visitTypeAnnotationExperimental(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in FieldWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n recordComponentVisitor.visitAttributeExperimental(attributes);\n attributes = nextAttribute;\n }\n // Visit the end of the field.\n recordComponentVisitor.visitEndExperimental();\n return currentOffset;\n }\n\n /**\n * Reads a JVMS field_info structure and makes the given visitor visit it.\n *\n * @param classVisitor the visitor that must visit the field.\n * @param context information about the class being parsed.\n * @param fieldInfoOffset the start offset of the field_info structure.\n * @return the offset of the first byte following the field_info structure.\n */\n private int readField(final ClassVisitor classVisitor, final Context context, final int fieldInfoOffset) {\n char[] charBuffer = context.charBuffer;\n // Read the access_flags, name_index and descriptor_index fields.\n int currentOffset = fieldInfoOffset;\n int accessFlags = readUnsignedShort(currentOffset);\n String name = readUTF8(currentOffset + 2, charBuffer);\n String descriptor = readUTF8(currentOffset + 4, charBuffer);\n currentOffset += 6;\n // Read the field attributes (the variables are ordered as in Section 4.7 of the JVMS).\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The value corresponding to the ConstantValue attribute, or null.\n Object constantValue = null;\n // - The string corresponding to the Signature attribute, or null.\n String signature = null;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.CONSTANT_VALUE.equals(attributeName)) {\n int constantvalueIndex = readUnsignedShort(currentOffset);\n constantValue = constantvalueIndex == 0 ? null : readConst(constantvalueIndex, charBuffer);\n } else if (Constants.SIGNATURE.equals(attributeName)) {\n signature = readUTF8(currentOffset, charBuffer);\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.SYNTHETIC.equals(attributeName)) {\n accessFlags |= Opcodes.ACC_SYNTHETIC;\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentOffset;\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n // Visit the field declaration.\n FieldVisitor fieldVisitor = classVisitor.visitField(accessFlags, name, descriptor, signature, constantValue);\n if (fieldVisitor == null) {\n return currentOffset;\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(fieldVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in FieldWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n fieldVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the end of the field.\n fieldVisitor.visitEnd();\n return currentOffset;\n }\n\n /**\n * Reads a JVMS method_info structure and makes the given visitor visit it.\n *\n * @param classVisitor the visitor that must visit the method.\n * @param context information about the class being parsed.\n * @param methodInfoOffset the start offset of the method_info structure.\n * @return the offset of the first byte following the method_info structure.\n */\n private int readMethod(final ClassVisitor classVisitor, final Context context, final int methodInfoOffset) {\n char[] charBuffer = context.charBuffer;\n // Read the access_flags, name_index and descriptor_index fields.\n int currentOffset = methodInfoOffset;\n context.currentMethodAccessFlags = readUnsignedShort(currentOffset);\n context.currentMethodName = readUTF8(currentOffset + 2, charBuffer);\n context.currentMethodDescriptor = readUTF8(currentOffset + 4, charBuffer);\n currentOffset += 6;\n // Read the method attributes (the variables are ordered as in Section 4.7 of the JVMS).\n // Attribute offsets exclude the attribute_name_index and attribute_length fields.\n // - The offset of the Code attribute, or 0.\n int codeOffset = 0;\n // - The offset of the Exceptions attribute, or 0.\n int exceptionsOffset = 0;\n // - The strings corresponding to the Exceptions attribute, or null.\n String[] exceptions = null;\n // - Whether the method has a Synthetic attribute.\n boolean synthetic = false;\n // - The constant pool index contained in the Signature attribute, or 0.\n int signatureIndex = 0;\n // - The offset of the RuntimeVisibleAnnotations attribute, or 0.\n int runtimeVisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleAnnotations attribute, or 0.\n int runtimeInvisibleAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleParameterAnnotations attribute, or 0.\n int runtimeVisibleParameterAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleParameterAnnotations attribute, or 0.\n int runtimeInvisibleParameterAnnotationsOffset = 0;\n // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0.\n int runtimeVisibleTypeAnnotationsOffset = 0;\n // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0.\n int runtimeInvisibleTypeAnnotationsOffset = 0;\n // - The offset of the AnnotationDefault attribute, or 0.\n int annotationDefaultOffset = 0;\n // - The offset of the MethodParameters attribute, or 0.\n int methodParametersOffset = 0;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n // The tests are sorted in decreasing frequency order (based on frequencies observed on\n // typical classes).\n if (Constants.CODE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_CODE) == 0) {\n codeOffset = currentOffset;\n }\n } else if (Constants.EXCEPTIONS.equals(attributeName)) {\n exceptionsOffset = currentOffset;\n exceptions = new String[readUnsignedShort(exceptionsOffset)];\n int currentExceptionOffset = exceptionsOffset + 2;\n for (int i = 0; i < exceptions.length; ++i) {\n exceptions[i] = readClass(currentExceptionOffset, charBuffer);\n currentExceptionOffset += 2;\n }\n } else if (Constants.SIGNATURE.equals(attributeName)) {\n signatureIndex = readUnsignedShort(currentOffset);\n } else if (Constants.DEPRECATED.equals(attributeName)) {\n context.currentMethodAccessFlags |= Opcodes.ACC_DEPRECATED;\n } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.ANNOTATION_DEFAULT.equals(attributeName)) {\n annotationDefaultOffset = currentOffset;\n } else if (Constants.SYNTHETIC.equals(attributeName)) {\n synthetic = true;\n context.currentMethodAccessFlags |= Opcodes.ACC_SYNTHETIC;\n } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleTypeAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) {\n runtimeVisibleParameterAnnotationsOffset = currentOffset;\n } else if (Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) {\n runtimeInvisibleParameterAnnotationsOffset = currentOffset;\n } else if (Constants.METHOD_PARAMETERS.equals(attributeName)) {\n methodParametersOffset = currentOffset;\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, -1, null);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n // Visit the method declaration.\n MethodVisitor methodVisitor = classVisitor.visitMethod(context.currentMethodAccessFlags, context.currentMethodName, context.currentMethodDescriptor, signatureIndex == 0 ? null : readUtf(signatureIndex, charBuffer), exceptions);\n if (methodVisitor == null) {\n return currentOffset;\n }\n // If the returned MethodVisitor is in fact a MethodWriter, it means there is no method\n // adapter between the reader and the writer. In this case, it might be possible to copy\n // the method attributes directly into the writer. If so, return early without visiting\n // the content of these attributes.\n if (methodVisitor instanceof MethodWriter) {\n MethodWriter methodWriter = (MethodWriter) methodVisitor;\n if (methodWriter.canCopyMethodAttributes(this, synthetic, (context.currentMethodAccessFlags & Opcodes.ACC_DEPRECATED) != 0, readUnsignedShort(methodInfoOffset + 4), signatureIndex, exceptionsOffset)) {\n methodWriter.setMethodAttributesSource(methodInfoOffset, currentOffset - methodInfoOffset);\n return currentOffset;\n }\n }\n // Visit the MethodParameters attribute.\n if (methodParametersOffset != 0 && (context.parsingOptions & SKIP_DEBUG) == 0) {\n int parametersCount = readByte(methodParametersOffset);\n int currentParameterOffset = methodParametersOffset + 1;\n while (parametersCount-- > 0) {\n // Read the name_index and access_flags fields and visit them.\n methodVisitor.visitParameter(readUTF8(currentParameterOffset, charBuffer), readUnsignedShort(currentParameterOffset + 2));\n currentParameterOffset += 4;\n }\n }\n // Visit the AnnotationDefault attribute.\n if (annotationDefaultOffset != 0) {\n AnnotationVisitor annotationVisitor = methodVisitor.visitAnnotationDefault();\n readElementValue(annotationVisitor, annotationDefaultOffset, null, charBuffer);\n if (annotationVisitor != null) {\n annotationVisitor.visitEnd();\n }\n }\n // Visit the RuntimeVisibleAnnotations attribute.\n if (runtimeVisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleAnnotations attribute.\n if (runtimeInvisibleAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleTypeAnnotations attribute.\n if (runtimeVisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeInvisibleTypeAnnotations attribute.\n if (runtimeInvisibleTypeAnnotationsOffset != 0) {\n int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset);\n int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2;\n while (numAnnotations-- > 0) {\n // Parse the target_type, target_info and target_path fields.\n currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentAnnotationOffset = readElementValues(methodVisitor.visitTypeAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n }\n // Visit the RuntimeVisibleParameterAnnotations attribute.\n if (runtimeVisibleParameterAnnotationsOffset != 0) {\n readParameterAnnotations(methodVisitor, context, runtimeVisibleParameterAnnotationsOffset, /* visible = */ true);\n }\n // Visit the RuntimeInvisibleParameterAnnotations attribute.\n if (runtimeInvisibleParameterAnnotationsOffset != 0) {\n readParameterAnnotations(methodVisitor, context, runtimeInvisibleParameterAnnotationsOffset,\n /* visible = */ false);\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in MethodWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n methodVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the Code attribute.\n if (codeOffset != 0) {\n methodVisitor.visitCode();\n readCode(methodVisitor, context, codeOffset);\n }\n // Visit the end of the method.\n methodVisitor.visitEnd();\n return currentOffset;\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse a Code attribute\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Reads a JVMS 'Code' attribute and makes the given visitor visit it.\n *\n * @param methodVisitor the visitor that must visit the Code attribute.\n * @param context information about the class being parsed.\n * @param codeOffset the start offset in {@link #classFileBuffer} of the Code attribute, excluding\n * its attribute_name_index and attribute_length fields.\n */\n private void readCode(final MethodVisitor methodVisitor, final Context context, final int codeOffset) {\n int currentOffset = codeOffset;\n // Read the max_stack, max_locals and code_length fields.\n final byte[] classBuffer = classFileBuffer;\n final char[] charBuffer = context.charBuffer;\n final int maxStack = readUnsignedShort(currentOffset);\n final int maxLocals = readUnsignedShort(currentOffset + 2);\n final int codeLength = readInt(currentOffset + 4);\n currentOffset += 8;\n // Read the bytecode 'code' array to create a label for each referenced instruction.\n final int bytecodeStartOffset = currentOffset;\n final int bytecodeEndOffset = currentOffset + codeLength;\n final Label[] labels = context.currentMethodLabels = new Label[codeLength + 1];\n while (currentOffset < bytecodeEndOffset) {\n final int bytecodeOffset = currentOffset - bytecodeStartOffset;\n final int opcode = classBuffer[currentOffset] & 0xFF;\n switch (opcode) {\n case Constants.NOP:\n case Constants.ACONST_NULL:\n case Constants.ICONST_M1:\n case Constants.ICONST_0:\n case Constants.ICONST_1:\n case Constants.ICONST_2:\n case Constants.ICONST_3:\n case Constants.ICONST_4:\n case Constants.ICONST_5:\n case Constants.LCONST_0:\n case Constants.LCONST_1:\n case Constants.FCONST_0:\n case Constants.FCONST_1:\n case Constants.FCONST_2:\n case Constants.DCONST_0:\n case Constants.DCONST_1:\n case Constants.IALOAD:\n case Constants.LALOAD:\n case Constants.FALOAD:\n case Constants.DALOAD:\n case Constants.AALOAD:\n case Constants.BALOAD:\n case Constants.CALOAD:\n case Constants.SALOAD:\n case Constants.IASTORE:\n case Constants.LASTORE:\n case Constants.FASTORE:\n case Constants.DASTORE:\n case Constants.AASTORE:\n case Constants.BASTORE:\n case Constants.CASTORE:\n case Constants.SASTORE:\n case Constants.POP:\n case Constants.POP2:\n case Constants.DUP:\n case Constants.DUP_X1:\n case Constants.DUP_X2:\n case Constants.DUP2:\n case Constants.DUP2_X1:\n case Constants.DUP2_X2:\n case Constants.SWAP:\n case Constants.IADD:\n case Constants.LADD:\n case Constants.FADD:\n case Constants.DADD:\n case Constants.ISUB:\n case Constants.LSUB:\n case Constants.FSUB:\n case Constants.DSUB:\n case Constants.IMUL:\n case Constants.LMUL:\n case Constants.FMUL:\n case Constants.DMUL:\n case Constants.IDIV:\n case Constants.LDIV:\n case Constants.FDIV:\n case Constants.DDIV:\n case Constants.IREM:\n case Constants.LREM:\n case Constants.FREM:\n case Constants.DREM:\n case Constants.INEG:\n case Constants.LNEG:\n case Constants.FNEG:\n case Constants.DNEG:\n case Constants.ISHL:\n case Constants.LSHL:\n case Constants.ISHR:\n case Constants.LSHR:\n case Constants.IUSHR:\n case Constants.LUSHR:\n case Constants.IAND:\n case Constants.LAND:\n case Constants.IOR:\n case Constants.LOR:\n case Constants.IXOR:\n case Constants.LXOR:\n case Constants.I2L:\n case Constants.I2F:\n case Constants.I2D:\n case Constants.L2I:\n case Constants.L2F:\n case Constants.L2D:\n case Constants.F2I:\n case Constants.F2L:\n case Constants.F2D:\n case Constants.D2I:\n case Constants.D2L:\n case Constants.D2F:\n case Constants.I2B:\n case Constants.I2C:\n case Constants.I2S:\n case Constants.LCMP:\n case Constants.FCMPL:\n case Constants.FCMPG:\n case Constants.DCMPL:\n case Constants.DCMPG:\n case Constants.IRETURN:\n case Constants.LRETURN:\n case Constants.FRETURN:\n case Constants.DRETURN:\n case Constants.ARETURN:\n case Constants.RETURN:\n case Constants.ARRAYLENGTH:\n case Constants.ATHROW:\n case Constants.MONITORENTER:\n case Constants.MONITOREXIT:\n case Constants.ILOAD_0:\n case Constants.ILOAD_1:\n case Constants.ILOAD_2:\n case Constants.ILOAD_3:\n case Constants.LLOAD_0:\n case Constants.LLOAD_1:\n case Constants.LLOAD_2:\n case Constants.LLOAD_3:\n case Constants.FLOAD_0:\n case Constants.FLOAD_1:\n case Constants.FLOAD_2:\n case Constants.FLOAD_3:\n case Constants.DLOAD_0:\n case Constants.DLOAD_1:\n case Constants.DLOAD_2:\n case Constants.DLOAD_3:\n case Constants.ALOAD_0:\n case Constants.ALOAD_1:\n case Constants.ALOAD_2:\n case Constants.ALOAD_3:\n case Constants.ISTORE_0:\n case Constants.ISTORE_1:\n case Constants.ISTORE_2:\n case Constants.ISTORE_3:\n case Constants.LSTORE_0:\n case Constants.LSTORE_1:\n case Constants.LSTORE_2:\n case Constants.LSTORE_3:\n case Constants.FSTORE_0:\n case Constants.FSTORE_1:\n case Constants.FSTORE_2:\n case Constants.FSTORE_3:\n case Constants.DSTORE_0:\n case Constants.DSTORE_1:\n case Constants.DSTORE_2:\n case Constants.DSTORE_3:\n case Constants.ASTORE_0:\n case Constants.ASTORE_1:\n case Constants.ASTORE_2:\n case Constants.ASTORE_3:\n currentOffset += 1;\n break;\n case Constants.IFEQ:\n case Constants.IFNE:\n case Constants.IFLT:\n case Constants.IFGE:\n case Constants.IFGT:\n case Constants.IFLE:\n case Constants.IF_ICMPEQ:\n case Constants.IF_ICMPNE:\n case Constants.IF_ICMPLT:\n case Constants.IF_ICMPGE:\n case Constants.IF_ICMPGT:\n case Constants.IF_ICMPLE:\n case Constants.IF_ACMPEQ:\n case Constants.IF_ACMPNE:\n case Constants.GOTO:\n case Constants.JSR:\n case Constants.IFNULL:\n case Constants.IFNONNULL:\n createLabel(bytecodeOffset + readShort(currentOffset + 1), labels);\n currentOffset += 3;\n break;\n case Constants.ASM_IFEQ:\n case Constants.ASM_IFNE:\n case Constants.ASM_IFLT:\n case Constants.ASM_IFGE:\n case Constants.ASM_IFGT:\n case Constants.ASM_IFLE:\n case Constants.ASM_IF_ICMPEQ:\n case Constants.ASM_IF_ICMPNE:\n case Constants.ASM_IF_ICMPLT:\n case Constants.ASM_IF_ICMPGE:\n case Constants.ASM_IF_ICMPGT:\n case Constants.ASM_IF_ICMPLE:\n case Constants.ASM_IF_ACMPEQ:\n case Constants.ASM_IF_ACMPNE:\n case Constants.ASM_GOTO:\n case Constants.ASM_JSR:\n case Constants.ASM_IFNULL:\n case Constants.ASM_IFNONNULL:\n createLabel(bytecodeOffset + readUnsignedShort(currentOffset + 1), labels);\n currentOffset += 3;\n break;\n case Constants.GOTO_W:\n case Constants.JSR_W:\n case Constants.ASM_GOTO_W:\n createLabel(bytecodeOffset + readInt(currentOffset + 1), labels);\n currentOffset += 5;\n break;\n case Constants.WIDE:\n switch (classBuffer[currentOffset + 1] & 0xFF) {\n case Constants.ILOAD:\n case Constants.FLOAD:\n case Constants.ALOAD:\n case Constants.LLOAD:\n case Constants.DLOAD:\n case Constants.ISTORE:\n case Constants.FSTORE:\n case Constants.ASTORE:\n case Constants.LSTORE:\n case Constants.DSTORE:\n case Constants.RET:\n currentOffset += 4;\n break;\n case Constants.IINC:\n currentOffset += 6;\n break;\n default:\n throw new IllegalArgumentException();\n }\n break;\n case Constants.TABLESWITCH:\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (bytecodeOffset & 3);\n // Read the default label and the number of table entries.\n createLabel(bytecodeOffset + readInt(currentOffset), labels);\n int numTableEntries = readInt(currentOffset + 8) - readInt(currentOffset + 4) + 1;\n currentOffset += 12;\n // Read the table labels.\n while (numTableEntries-- > 0) {\n createLabel(bytecodeOffset + readInt(currentOffset), labels);\n currentOffset += 4;\n }\n break;\n case Constants.LOOKUPSWITCH:\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (bytecodeOffset & 3);\n // Read the default label and the number of switch cases.\n createLabel(bytecodeOffset + readInt(currentOffset), labels);\n int numSwitchCases = readInt(currentOffset + 4);\n currentOffset += 8;\n // Read the switch labels.\n while (numSwitchCases-- > 0) {\n createLabel(bytecodeOffset + readInt(currentOffset + 4), labels);\n currentOffset += 8;\n }\n break;\n case Constants.ILOAD:\n case Constants.LLOAD:\n case Constants.FLOAD:\n case Constants.DLOAD:\n case Constants.ALOAD:\n case Constants.ISTORE:\n case Constants.LSTORE:\n case Constants.FSTORE:\n case Constants.DSTORE:\n case Constants.ASTORE:\n case Constants.RET:\n case Constants.BIPUSH:\n case Constants.NEWARRAY:\n case Constants.LDC:\n currentOffset += 2;\n break;\n case Constants.SIPUSH:\n case Constants.LDC_W:\n case Constants.LDC2_W:\n case Constants.GETSTATIC:\n case Constants.PUTSTATIC:\n case Constants.GETFIELD:\n case Constants.PUTFIELD:\n case Constants.INVOKEVIRTUAL:\n case Constants.INVOKESPECIAL:\n case Constants.INVOKESTATIC:\n case Constants.NEW:\n case Constants.ANEWARRAY:\n case Constants.CHECKCAST:\n case Constants.INSTANCEOF:\n case Constants.IINC:\n currentOffset += 3;\n break;\n case Constants.INVOKEINTERFACE:\n case Constants.INVOKEDYNAMIC:\n currentOffset += 5;\n break;\n case Constants.MULTIANEWARRAY:\n currentOffset += 4;\n break;\n default:\n throw new IllegalArgumentException();\n }\n }\n // Read the 'exception_table_length' and 'exception_table' field to create a label for each\n // referenced instruction, and to make methodVisitor visit the corresponding try catch blocks.\n int exceptionTableLength = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (exceptionTableLength-- > 0) {\n Label start = createLabel(readUnsignedShort(currentOffset), labels);\n Label end = createLabel(readUnsignedShort(currentOffset + 2), labels);\n Label handler = createLabel(readUnsignedShort(currentOffset + 4), labels);\n String catchType = readUTF8(cpInfoOffsets[readUnsignedShort(currentOffset + 6)], charBuffer);\n currentOffset += 8;\n methodVisitor.visitTryCatchBlock(start, end, handler, catchType);\n }\n // Read the Code attributes to create a label for each referenced instruction (the variables\n // are ordered as in Section 4.7 of the JVMS). Attribute offsets exclude the\n // attribute_name_index and attribute_length fields.\n // - The offset of the current 'stack_map_frame' in the StackMap[Table] attribute, or 0.\n // Initially, this is the offset of the first 'stack_map_frame' entry. Then this offset is\n // updated after each stack_map_frame is read.\n int stackMapFrameOffset = 0;\n // - The end offset of the StackMap[Table] attribute, or 0.\n int stackMapTableEndOffset = 0;\n // - Whether the stack map frames are compressed (i.e. in a StackMapTable) or not.\n boolean compressedFrames = true;\n // - The offset of the LocalVariableTable attribute, or 0.\n int localVariableTableOffset = 0;\n // - The offset of the LocalVariableTypeTable attribute, or 0.\n int localVariableTypeTableOffset = 0;\n // - The offset of each 'type_annotation' entry in the RuntimeVisibleTypeAnnotations\n // attribute, or null.\n int[] visibleTypeAnnotationOffsets = null;\n // - The offset of each 'type_annotation' entry in the RuntimeInvisibleTypeAnnotations\n // attribute, or null.\n int[] invisibleTypeAnnotationOffsets = null;\n // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field).\n // This list in the reverse order or their order in the ClassFile structure.\n Attribute attributes = null;\n int attributesCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (attributesCount-- > 0) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentOffset, charBuffer);\n int attributeLength = readInt(currentOffset + 2);\n currentOffset += 6;\n if (Constants.LOCAL_VARIABLE_TABLE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_DEBUG) == 0) {\n localVariableTableOffset = currentOffset;\n // Parse the attribute to find the corresponding (debug only) labels.\n int currentLocalVariableTableOffset = currentOffset;\n int localVariableTableLength = readUnsignedShort(currentLocalVariableTableOffset);\n currentLocalVariableTableOffset += 2;\n while (localVariableTableLength-- > 0) {\n int startPc = readUnsignedShort(currentLocalVariableTableOffset);\n createDebugLabel(startPc, labels);\n int length = readUnsignedShort(currentLocalVariableTableOffset + 2);\n createDebugLabel(startPc + length, labels);\n // Skip the name_index, descriptor_index and index fields (2 bytes each).\n currentLocalVariableTableOffset += 10;\n }\n }\n } else if (Constants.LOCAL_VARIABLE_TYPE_TABLE.equals(attributeName)) {\n localVariableTypeTableOffset = currentOffset;\n // Here we do not extract the labels corresponding to the attribute content. We assume they\n // are the same or a subset of those of the LocalVariableTable attribute.\n } else if (Constants.LINE_NUMBER_TABLE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_DEBUG) == 0) {\n // Parse the attribute to find the corresponding (debug only) labels.\n int currentLineNumberTableOffset = currentOffset;\n int lineNumberTableLength = readUnsignedShort(currentLineNumberTableOffset);\n currentLineNumberTableOffset += 2;\n while (lineNumberTableLength-- > 0) {\n int startPc = readUnsignedShort(currentLineNumberTableOffset);\n int lineNumber = readUnsignedShort(currentLineNumberTableOffset + 2);\n currentLineNumberTableOffset += 4;\n createDebugLabel(startPc, labels);\n labels[startPc].addLineNumber(lineNumber);\n }\n }\n } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n visibleTypeAnnotationOffsets = readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ true);\n // Here we do not extract the labels corresponding to the attribute content. This would\n // require a full parsing of the attribute, which would need to be repeated when parsing\n // the bytecode instructions (see below). Instead, the content of the attribute is read one\n // type annotation at a time (i.e. after a type annotation has been visited, the next type\n // annotation is read), and the labels it contains are also extracted one annotation at a\n // time. This assumes that type annotations are ordered by increasing bytecode offset.\n } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) {\n invisibleTypeAnnotationOffsets = readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ false);\n // Same comment as above for the RuntimeVisibleTypeAnnotations attribute.\n } else if (Constants.STACK_MAP_TABLE.equals(attributeName)) {\n if ((context.parsingOptions & SKIP_FRAMES) == 0) {\n stackMapFrameOffset = currentOffset + 2;\n stackMapTableEndOffset = currentOffset + attributeLength;\n }\n // Here we do not extract the labels corresponding to the attribute content. This would\n // require a full parsing of the attribute, which would need to be repeated when parsing\n // the bytecode instructions (see below). Instead, the content of the attribute is read one\n // frame at a time (i.e. after a frame has been visited, the next frame is read), and the\n // labels it contains are also extracted one frame at a time. Thanks to the ordering of\n // frames, having only a \"one frame lookahead\" is not a problem, i.e. it is not possible to\n // see an offset smaller than the offset of the current instruction and for which no Label\n // exist. Except for UNINITIALIZED type offsets. We solve this by parsing the stack map\n // table without a full decoding (see below).\n } else if (\"StackMap\".equals(attributeName)) {\n if ((context.parsingOptions & SKIP_FRAMES) == 0) {\n stackMapFrameOffset = currentOffset + 2;\n stackMapTableEndOffset = currentOffset + attributeLength;\n compressedFrames = false;\n }\n // IMPORTANT! Here we assume that the frames are ordered, as in the StackMapTable attribute,\n // although this is not guaranteed by the attribute format. This allows an incremental\n // extraction of the labels corresponding to this attribute (see the comment above for the\n // StackMapTable attribute).\n } else {\n Attribute attribute = readAttribute(context.attributePrototypes, attributeName, currentOffset, attributeLength, charBuffer, codeOffset, labels);\n attribute.nextAttribute = attributes;\n attributes = attribute;\n }\n currentOffset += attributeLength;\n }\n // Initialize the context fields related to stack map frames, and generate the first\n // (implicit) stack map frame, if needed.\n final boolean expandFrames = (context.parsingOptions & EXPAND_FRAMES) != 0;\n if (stackMapFrameOffset != 0) {\n // The bytecode offset of the first explicit frame is not offset_delta + 1 but only\n // offset_delta. Setting the implicit frame offset to -1 allows us to use of the\n // \"offset_delta + 1\" rule in all cases.\n context.currentFrameOffset = -1;\n context.currentFrameType = 0;\n context.currentFrameLocalCount = 0;\n context.currentFrameLocalCountDelta = 0;\n context.currentFrameLocalTypes = new Object[maxLocals];\n context.currentFrameStackCount = 0;\n context.currentFrameStackTypes = new Object[maxStack];\n if (expandFrames) {\n computeImplicitFrame(context);\n }\n // Find the labels for UNINITIALIZED frame types. Instead of decoding each element of the\n // stack map table, we look for 3 consecutive bytes that \"look like\" an UNINITIALIZED type\n // (tag ITEM_Uninitialized, offset within bytecode bounds, NEW instruction at this offset).\n // We may find false positives (i.e. not real UNINITIALIZED types), but this should be rare,\n // and the only consequence will be the creation of an unneeded label. This is better than\n // creating a label for each NEW instruction, and faster than fully decoding the whole stack\n // map table.\n for (int offset = stackMapFrameOffset; offset < stackMapTableEndOffset - 2; ++offset) {\n if (classBuffer[offset] == Frame.ITEM_UNINITIALIZED) {\n int potentialBytecodeOffset = readUnsignedShort(offset + 1);\n if (potentialBytecodeOffset >= 0 && potentialBytecodeOffset < codeLength && (classBuffer[bytecodeStartOffset + potentialBytecodeOffset] & 0xFF) == Opcodes.NEW) {\n createLabel(potentialBytecodeOffset, labels);\n }\n }\n }\n }\n if (expandFrames && (context.parsingOptions & EXPAND_ASM_INSNS) != 0) {\n // Expanding the ASM specific instructions can introduce F_INSERT frames, even if the method\n // does not currently have any frame. These inserted frames must be computed by simulating the\n // effect of the bytecode instructions, one by one, starting from the implicit first frame.\n // For this, MethodWriter needs to know maxLocals before the first instruction is visited. To\n // ensure this, we visit the implicit first frame here (passing only maxLocals - the rest is\n // computed in MethodWriter).\n methodVisitor.visitFrame(Opcodes.F_NEW, maxLocals, null, 0, null);\n }\n // Visit the bytecode instructions. First, introduce state variables for the incremental parsing\n // of the type annotations.\n // Index of the next runtime visible type annotation to read (in the\n // visibleTypeAnnotationOffsets array).\n int currentVisibleTypeAnnotationIndex = 0;\n // The bytecode offset of the next runtime visible type annotation to read, or -1.\n int currentVisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(visibleTypeAnnotationOffsets, 0);\n // Index of the next runtime invisible type annotation to read (in the\n // invisibleTypeAnnotationOffsets array).\n int currentInvisibleTypeAnnotationIndex = 0;\n // The bytecode offset of the next runtime invisible type annotation to read, or -1.\n int currentInvisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(invisibleTypeAnnotationOffsets, 0);\n // Whether a F_INSERT stack map frame must be inserted before the current instruction.\n boolean insertFrame = false;\n // The delta to subtract from a goto_w or jsr_w opcode to get the corresponding goto or jsr\n // opcode, or 0 if goto_w and jsr_w must be left unchanged (i.e. when expanding ASM specific\n // instructions).\n final int wideJumpOpcodeDelta = (context.parsingOptions & EXPAND_ASM_INSNS) == 0 ? Constants.WIDE_JUMP_OPCODE_DELTA : 0;\n currentOffset = bytecodeStartOffset;\n while (currentOffset < bytecodeEndOffset) {\n final int currentBytecodeOffset = currentOffset - bytecodeStartOffset;\n // Visit the label and the line number(s) for this bytecode offset, if any.\n Label currentLabel = labels[currentBytecodeOffset];\n if (currentLabel != null) {\n currentLabel.accept(methodVisitor, (context.parsingOptions & SKIP_DEBUG) == 0);\n }\n // Visit the stack map frame for this bytecode offset, if any.\n while (stackMapFrameOffset != 0 && (context.currentFrameOffset == currentBytecodeOffset || context.currentFrameOffset == -1)) {\n // If there is a stack map frame for this offset, make methodVisitor visit it, and read the\n // next stack map frame if there is one.\n if (context.currentFrameOffset != -1) {\n if (!compressedFrames || expandFrames) {\n methodVisitor.visitFrame(Opcodes.F_NEW, context.currentFrameLocalCount, context.currentFrameLocalTypes, context.currentFrameStackCount, context.currentFrameStackTypes);\n } else {\n methodVisitor.visitFrame(context.currentFrameType, context.currentFrameLocalCountDelta, context.currentFrameLocalTypes, context.currentFrameStackCount, context.currentFrameStackTypes);\n }\n // Since there is already a stack map frame for this bytecode offset, there is no need to\n // insert a new one.\n insertFrame = false;\n }\n if (stackMapFrameOffset < stackMapTableEndOffset) {\n stackMapFrameOffset = readStackMapFrame(stackMapFrameOffset, compressedFrames, expandFrames, context);\n } else {\n stackMapFrameOffset = 0;\n }\n }\n // Insert a stack map frame for this bytecode offset, if requested by setting insertFrame to\n // true during the previous iteration. The actual frame content is computed in MethodWriter.\n if (insertFrame) {\n if ((context.parsingOptions & EXPAND_FRAMES) != 0) {\n methodVisitor.visitFrame(Constants.F_INSERT, 0, null, 0, null);\n }\n insertFrame = false;\n }\n // Visit the instruction at this bytecode offset.\n int opcode = classBuffer[currentOffset] & 0xFF;\n switch (opcode) {\n case Constants.NOP:\n case Constants.ACONST_NULL:\n case Constants.ICONST_M1:\n case Constants.ICONST_0:\n case Constants.ICONST_1:\n case Constants.ICONST_2:\n case Constants.ICONST_3:\n case Constants.ICONST_4:\n case Constants.ICONST_5:\n case Constants.LCONST_0:\n case Constants.LCONST_1:\n case Constants.FCONST_0:\n case Constants.FCONST_1:\n case Constants.FCONST_2:\n case Constants.DCONST_0:\n case Constants.DCONST_1:\n case Constants.IALOAD:\n case Constants.LALOAD:\n case Constants.FALOAD:\n case Constants.DALOAD:\n case Constants.AALOAD:\n case Constants.BALOAD:\n case Constants.CALOAD:\n case Constants.SALOAD:\n case Constants.IASTORE:\n case Constants.LASTORE:\n case Constants.FASTORE:\n case Constants.DASTORE:\n case Constants.AASTORE:\n case Constants.BASTORE:\n case Constants.CASTORE:\n case Constants.SASTORE:\n case Constants.POP:\n case Constants.POP2:\n case Constants.DUP:\n case Constants.DUP_X1:\n case Constants.DUP_X2:\n case Constants.DUP2:\n case Constants.DUP2_X1:\n case Constants.DUP2_X2:\n case Constants.SWAP:\n case Constants.IADD:\n case Constants.LADD:\n case Constants.FADD:\n case Constants.DADD:\n case Constants.ISUB:\n case Constants.LSUB:\n case Constants.FSUB:\n case Constants.DSUB:\n case Constants.IMUL:\n case Constants.LMUL:\n case Constants.FMUL:\n case Constants.DMUL:\n case Constants.IDIV:\n case Constants.LDIV:\n case Constants.FDIV:\n case Constants.DDIV:\n case Constants.IREM:\n case Constants.LREM:\n case Constants.FREM:\n case Constants.DREM:\n case Constants.INEG:\n case Constants.LNEG:\n case Constants.FNEG:\n case Constants.DNEG:\n case Constants.ISHL:\n case Constants.LSHL:\n case Constants.ISHR:\n case Constants.LSHR:\n case Constants.IUSHR:\n case Constants.LUSHR:\n case Constants.IAND:\n case Constants.LAND:\n case Constants.IOR:\n case Constants.LOR:\n case Constants.IXOR:\n case Constants.LXOR:\n case Constants.I2L:\n case Constants.I2F:\n case Constants.I2D:\n case Constants.L2I:\n case Constants.L2F:\n case Constants.L2D:\n case Constants.F2I:\n case Constants.F2L:\n case Constants.F2D:\n case Constants.D2I:\n case Constants.D2L:\n case Constants.D2F:\n case Constants.I2B:\n case Constants.I2C:\n case Constants.I2S:\n case Constants.LCMP:\n case Constants.FCMPL:\n case Constants.FCMPG:\n case Constants.DCMPL:\n case Constants.DCMPG:\n case Constants.IRETURN:\n case Constants.LRETURN:\n case Constants.FRETURN:\n case Constants.DRETURN:\n case Constants.ARETURN:\n case Constants.RETURN:\n case Constants.ARRAYLENGTH:\n case Constants.ATHROW:\n case Constants.MONITORENTER:\n case Constants.MONITOREXIT:\n methodVisitor.visitInsn(opcode);\n currentOffset += 1;\n break;\n case Constants.ILOAD_0:\n case Constants.ILOAD_1:\n case Constants.ILOAD_2:\n case Constants.ILOAD_3:\n case Constants.LLOAD_0:\n case Constants.LLOAD_1:\n case Constants.LLOAD_2:\n case Constants.LLOAD_3:\n case Constants.FLOAD_0:\n case Constants.FLOAD_1:\n case Constants.FLOAD_2:\n case Constants.FLOAD_3:\n case Constants.DLOAD_0:\n case Constants.DLOAD_1:\n case Constants.DLOAD_2:\n case Constants.DLOAD_3:\n case Constants.ALOAD_0:\n case Constants.ALOAD_1:\n case Constants.ALOAD_2:\n case Constants.ALOAD_3:\n opcode -= Constants.ILOAD_0;\n methodVisitor.visitVarInsn(Opcodes.ILOAD + (opcode >> 2), opcode & 0x3);\n currentOffset += 1;\n break;\n case Constants.ISTORE_0:\n case Constants.ISTORE_1:\n case Constants.ISTORE_2:\n case Constants.ISTORE_3:\n case Constants.LSTORE_0:\n case Constants.LSTORE_1:\n case Constants.LSTORE_2:\n case Constants.LSTORE_3:\n case Constants.FSTORE_0:\n case Constants.FSTORE_1:\n case Constants.FSTORE_2:\n case Constants.FSTORE_3:\n case Constants.DSTORE_0:\n case Constants.DSTORE_1:\n case Constants.DSTORE_2:\n case Constants.DSTORE_3:\n case Constants.ASTORE_0:\n case Constants.ASTORE_1:\n case Constants.ASTORE_2:\n case Constants.ASTORE_3:\n opcode -= Constants.ISTORE_0;\n methodVisitor.visitVarInsn(Opcodes.ISTORE + (opcode >> 2), opcode & 0x3);\n currentOffset += 1;\n break;\n case Constants.IFEQ:\n case Constants.IFNE:\n case Constants.IFLT:\n case Constants.IFGE:\n case Constants.IFGT:\n case Constants.IFLE:\n case Constants.IF_ICMPEQ:\n case Constants.IF_ICMPNE:\n case Constants.IF_ICMPLT:\n case Constants.IF_ICMPGE:\n case Constants.IF_ICMPGT:\n case Constants.IF_ICMPLE:\n case Constants.IF_ACMPEQ:\n case Constants.IF_ACMPNE:\n case Constants.GOTO:\n case Constants.JSR:\n case Constants.IFNULL:\n case Constants.IFNONNULL:\n methodVisitor.visitJumpInsn(opcode, labels[currentBytecodeOffset + readShort(currentOffset + 1)]);\n currentOffset += 3;\n break;\n case Constants.GOTO_W:\n case Constants.JSR_W:\n methodVisitor.visitJumpInsn(opcode - wideJumpOpcodeDelta, labels[currentBytecodeOffset + readInt(currentOffset + 1)]);\n currentOffset += 5;\n break;\n case Constants.ASM_IFEQ:\n case Constants.ASM_IFNE:\n case Constants.ASM_IFLT:\n case Constants.ASM_IFGE:\n case Constants.ASM_IFGT:\n case Constants.ASM_IFLE:\n case Constants.ASM_IF_ICMPEQ:\n case Constants.ASM_IF_ICMPNE:\n case Constants.ASM_IF_ICMPLT:\n case Constants.ASM_IF_ICMPGE:\n case Constants.ASM_IF_ICMPGT:\n case Constants.ASM_IF_ICMPLE:\n case Constants.ASM_IF_ACMPEQ:\n case Constants.ASM_IF_ACMPNE:\n case Constants.ASM_GOTO:\n case Constants.ASM_JSR:\n case Constants.ASM_IFNULL:\n case Constants.ASM_IFNONNULL: {\n // A forward jump with an offset > 32767. In this case we automatically replace ASM_GOTO\n // with GOTO_W, ASM_JSR with JSR_W and ASM_IFxxx with IFNOTxxx GOTO_W L:...,\n // where IFNOTxxx is the \"opposite\" opcode of ASMS_IFxxx (e.g. IFNE for ASM_IFEQ) and\n // where designates the instruction just after the GOTO_W.\n // First, change the ASM specific opcodes ASM_IFEQ ... ASM_JSR, ASM_IFNULL and\n // ASM_IFNONNULL to IFEQ ... JSR, IFNULL and IFNONNULL.\n opcode = opcode < Constants.ASM_IFNULL ? opcode - Constants.ASM_OPCODE_DELTA : opcode - Constants.ASM_IFNULL_OPCODE_DELTA;\n Label target = labels[currentBytecodeOffset + readUnsignedShort(currentOffset + 1)];\n if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) {\n // Replace GOTO with GOTO_W and JSR with JSR_W.\n methodVisitor.visitJumpInsn(opcode + Constants.WIDE_JUMP_OPCODE_DELTA, target);\n } else {\n // Compute the \"opposite\" of opcode. This can be done by flipping the least\n // significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ\n // (with a pre and post offset by 1).\n opcode = opcode < Opcodes.GOTO ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1;\n Label endif = createLabel(currentBytecodeOffset + 3, labels);\n methodVisitor.visitJumpInsn(opcode, endif);\n methodVisitor.visitJumpInsn(Constants.GOTO_W, target);\n // endif designates the instruction just after GOTO_W, and is visited as part of the\n // next instruction. Since it is a jump target, we need to insert a frame here.\n insertFrame = true;\n }\n currentOffset += 3;\n break;\n }\n case Constants.ASM_GOTO_W:\n // Replace ASM_GOTO_W with GOTO_W.\n methodVisitor.visitJumpInsn(Constants.GOTO_W, labels[currentBytecodeOffset + readInt(currentOffset + 1)]);\n // The instruction just after is a jump target (because ASM_GOTO_W is used in patterns\n // IFNOTxxx ASM_GOTO_W L:..., see MethodWriter), so we need to insert a frame\n // here.\n insertFrame = true;\n currentOffset += 5;\n break;\n case Constants.WIDE:\n opcode = classBuffer[currentOffset + 1] & 0xFF;\n if (opcode == Opcodes.IINC) {\n methodVisitor.visitIincInsn(readUnsignedShort(currentOffset + 2), readShort(currentOffset + 4));\n currentOffset += 6;\n } else {\n methodVisitor.visitVarInsn(opcode, readUnsignedShort(currentOffset + 2));\n currentOffset += 4;\n }\n break;\n case Constants.TABLESWITCH: {\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (currentBytecodeOffset & 3);\n // Read the instruction.\n Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)];\n int low = readInt(currentOffset + 4);\n int high = readInt(currentOffset + 8);\n currentOffset += 12;\n Label[] table = new Label[high - low + 1];\n for (int i = 0; i < table.length; ++i) {\n table[i] = labels[currentBytecodeOffset + readInt(currentOffset)];\n currentOffset += 4;\n }\n methodVisitor.visitTableSwitchInsn(low, high, defaultLabel, table);\n break;\n }\n case Constants.LOOKUPSWITCH: {\n // Skip 0 to 3 padding bytes.\n currentOffset += 4 - (currentBytecodeOffset & 3);\n // Read the instruction.\n Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)];\n int numPairs = readInt(currentOffset + 4);\n currentOffset += 8;\n int[] keys = new int[numPairs];\n Label[] values = new Label[numPairs];\n for (int i = 0; i < numPairs; ++i) {\n keys[i] = readInt(currentOffset);\n values[i] = labels[currentBytecodeOffset + readInt(currentOffset + 4)];\n currentOffset += 8;\n }\n methodVisitor.visitLookupSwitchInsn(defaultLabel, keys, values);\n break;\n }\n case Constants.ILOAD:\n case Constants.LLOAD:\n case Constants.FLOAD:\n case Constants.DLOAD:\n case Constants.ALOAD:\n case Constants.ISTORE:\n case Constants.LSTORE:\n case Constants.FSTORE:\n case Constants.DSTORE:\n case Constants.ASTORE:\n case Constants.RET:\n methodVisitor.visitVarInsn(opcode, classBuffer[currentOffset + 1] & 0xFF);\n currentOffset += 2;\n break;\n case Constants.BIPUSH:\n case Constants.NEWARRAY:\n methodVisitor.visitIntInsn(opcode, classBuffer[currentOffset + 1]);\n currentOffset += 2;\n break;\n case Constants.SIPUSH:\n methodVisitor.visitIntInsn(opcode, readShort(currentOffset + 1));\n currentOffset += 3;\n break;\n case Constants.LDC:\n methodVisitor.visitLdcInsn(readConst(classBuffer[currentOffset + 1] & 0xFF, charBuffer));\n currentOffset += 2;\n break;\n case Constants.LDC_W:\n case Constants.LDC2_W:\n methodVisitor.visitLdcInsn(readConst(readUnsignedShort(currentOffset + 1), charBuffer));\n currentOffset += 3;\n break;\n case Constants.GETSTATIC:\n case Constants.PUTSTATIC:\n case Constants.GETFIELD:\n case Constants.PUTFIELD:\n case Constants.INVOKEVIRTUAL:\n case Constants.INVOKESPECIAL:\n case Constants.INVOKESTATIC:\n case Constants.INVOKEINTERFACE: {\n int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)];\n String owner = readClass(cpInfoOffset, charBuffer);\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n if (opcode < Opcodes.INVOKEVIRTUAL) {\n methodVisitor.visitFieldInsn(opcode, owner, name, descriptor);\n } else {\n boolean isInterface = classBuffer[cpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG;\n methodVisitor.visitMethodInsn(opcode, owner, name, descriptor, isInterface);\n }\n if (opcode == Opcodes.INVOKEINTERFACE) {\n currentOffset += 5;\n } else {\n currentOffset += 3;\n }\n break;\n }\n case Constants.INVOKEDYNAMIC: {\n int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)];\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)];\n Handle handle = (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n Object[] bootstrapMethodArguments = new Object[readUnsignedShort(bootstrapMethodOffset + 2)];\n bootstrapMethodOffset += 4;\n for (int i = 0; i < bootstrapMethodArguments.length; i++) {\n bootstrapMethodArguments[i] = readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n bootstrapMethodOffset += 2;\n }\n methodVisitor.visitInvokeDynamicInsn(name, descriptor, handle, bootstrapMethodArguments);\n currentOffset += 5;\n break;\n }\n case Constants.NEW:\n case Constants.ANEWARRAY:\n case Constants.CHECKCAST:\n case Constants.INSTANCEOF:\n methodVisitor.visitTypeInsn(opcode, readClass(currentOffset + 1, charBuffer));\n currentOffset += 3;\n break;\n case Constants.IINC:\n methodVisitor.visitIincInsn(classBuffer[currentOffset + 1] & 0xFF, classBuffer[currentOffset + 2]);\n currentOffset += 3;\n break;\n case Constants.MULTIANEWARRAY:\n methodVisitor.visitMultiANewArrayInsn(readClass(currentOffset + 1, charBuffer), classBuffer[currentOffset + 3] & 0xFF);\n currentOffset += 4;\n break;\n default:\n throw new AssertionError();\n }\n // Visit the runtime visible instruction annotations, if any.\n while (visibleTypeAnnotationOffsets != null && currentVisibleTypeAnnotationIndex < visibleTypeAnnotationOffsets.length && currentVisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) {\n if (currentVisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) {\n // Parse the target_type, target_info and target_path fields.\n int currentAnnotationOffset = readTypeAnnotationTarget(context, visibleTypeAnnotationOffsets[currentVisibleTypeAnnotationIndex]);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitInsnAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ true), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n currentVisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(visibleTypeAnnotationOffsets, ++currentVisibleTypeAnnotationIndex);\n }\n // Visit the runtime invisible instruction annotations, if any.\n while (invisibleTypeAnnotationOffsets != null && currentInvisibleTypeAnnotationIndex < invisibleTypeAnnotationOffsets.length && currentInvisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) {\n if (currentInvisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) {\n // Parse the target_type, target_info and target_path fields.\n int currentAnnotationOffset = readTypeAnnotationTarget(context, invisibleTypeAnnotationOffsets[currentInvisibleTypeAnnotationIndex]);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer);\n currentAnnotationOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitInsnAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, annotationDescriptor,\n /* visible = */ false), currentAnnotationOffset,\n /* named = */ true, charBuffer);\n }\n currentInvisibleTypeAnnotationBytecodeOffset = getTypeAnnotationBytecodeOffset(invisibleTypeAnnotationOffsets, ++currentInvisibleTypeAnnotationIndex);\n }\n }\n if (labels[codeLength] != null) {\n methodVisitor.visitLabel(labels[codeLength]);\n }\n // Visit LocalVariableTable and LocalVariableTypeTable attributes.\n if (localVariableTableOffset != 0 && (context.parsingOptions & SKIP_DEBUG) == 0) {\n // The (start_pc, index, signature_index) fields of each entry of the LocalVariableTypeTable.\n int[] typeTable = null;\n if (localVariableTypeTableOffset != 0) {\n typeTable = new int[readUnsignedShort(localVariableTypeTableOffset) * 3];\n currentOffset = localVariableTypeTableOffset + 2;\n int typeTableIndex = typeTable.length;\n while (typeTableIndex > 0) {\n // Store the offset of 'signature_index', and the value of 'index' and 'start_pc'.\n typeTable[--typeTableIndex] = currentOffset + 6;\n typeTable[--typeTableIndex] = readUnsignedShort(currentOffset + 8);\n typeTable[--typeTableIndex] = readUnsignedShort(currentOffset);\n currentOffset += 10;\n }\n }\n int localVariableTableLength = readUnsignedShort(localVariableTableOffset);\n currentOffset = localVariableTableOffset + 2;\n while (localVariableTableLength-- > 0) {\n int startPc = readUnsignedShort(currentOffset);\n int length = readUnsignedShort(currentOffset + 2);\n String name = readUTF8(currentOffset + 4, charBuffer);\n String descriptor = readUTF8(currentOffset + 6, charBuffer);\n int index = readUnsignedShort(currentOffset + 8);\n currentOffset += 10;\n String signature = null;\n if (typeTable != null) {\n for (int i = 0; i < typeTable.length; i += 3) {\n if (typeTable[i] == startPc && typeTable[i + 1] == index) {\n signature = readUTF8(typeTable[i + 2], charBuffer);\n break;\n }\n }\n }\n methodVisitor.visitLocalVariable(name, descriptor, signature, labels[startPc], labels[startPc + length], index);\n }\n }\n // Visit the local variable type annotations of the RuntimeVisibleTypeAnnotations attribute.\n if (visibleTypeAnnotationOffsets != null) {\n for (int typeAnnotationOffset : visibleTypeAnnotationOffsets) {\n int targetType = readByte(typeAnnotationOffset);\n if (targetType == TypeReference.LOCAL_VARIABLE || targetType == TypeReference.RESOURCE_VARIABLE) {\n // Parse the target_type, target_info and target_path fields.\n currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitLocalVariableAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, context.currentLocalVariableAnnotationRangeStarts, context.currentLocalVariableAnnotationRangeEnds, context.currentLocalVariableAnnotationRangeIndices, annotationDescriptor,\n /* visible = */ true), currentOffset,\n /* named = */ true, charBuffer);\n }\n }\n }\n // Visit the local variable type annotations of the RuntimeInvisibleTypeAnnotations attribute.\n if (invisibleTypeAnnotationOffsets != null) {\n for (int typeAnnotationOffset : invisibleTypeAnnotationOffsets) {\n int targetType = readByte(typeAnnotationOffset);\n if (targetType == TypeReference.LOCAL_VARIABLE || targetType == TypeReference.RESOURCE_VARIABLE) {\n // Parse the target_type, target_info and target_path fields.\n currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset);\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n readElementValues(methodVisitor.visitLocalVariableAnnotation(context.currentTypeAnnotationTarget, context.currentTypeAnnotationTargetPath, context.currentLocalVariableAnnotationRangeStarts, context.currentLocalVariableAnnotationRangeEnds, context.currentLocalVariableAnnotationRangeIndices, annotationDescriptor,\n /* visible = */ false), currentOffset,\n /* named = */ true, charBuffer);\n }\n }\n }\n // Visit the non standard attributes.\n while (attributes != null) {\n // Copy and reset the nextAttribute field so that it can also be used in MethodWriter.\n Attribute nextAttribute = attributes.nextAttribute;\n attributes.nextAttribute = null;\n methodVisitor.visitAttribute(attributes);\n attributes = nextAttribute;\n }\n // Visit the max stack and max locals values.\n methodVisitor.visitMaxs(maxStack, maxLocals);\n }\n\n /**\n * Returns the label corresponding to the given bytecode offset. The default implementation of\n * this method creates a label for the given offset if it has not been already created.\n *\n * @param bytecodeOffset a bytecode offset in a method.\n * @param labels the already created labels, indexed by their offset. If a label already exists\n * for bytecodeOffset this method must not create a new one. Otherwise it must store the new\n * label in this array.\n * @return a non null Label, which must be equal to labels[bytecodeOffset].\n */\n protected Label readLabel(final int bytecodeOffset, final Label[] labels) {\n if (labels[bytecodeOffset] == null) {\n labels[bytecodeOffset] = new Label();\n }\n return labels[bytecodeOffset];\n }\n\n /**\n * Creates a label without the {@link Label#FLAG_DEBUG_ONLY} flag set, for the given bytecode\n * offset. The label is created with a call to {@link #readLabel} and its {@link\n * Label#FLAG_DEBUG_ONLY} flag is cleared.\n *\n * @param bytecodeOffset a bytecode offset in a method.\n * @param labels the already created labels, indexed by their offset.\n * @return a Label without the {@link Label#FLAG_DEBUG_ONLY} flag set.\n */\n private Label createLabel(final int bytecodeOffset, final Label[] labels) {\n Label label = readLabel(bytecodeOffset, labels);\n label.flags &= ~Label.FLAG_DEBUG_ONLY;\n return label;\n }\n\n /**\n * Creates a label with the {@link Label#FLAG_DEBUG_ONLY} flag set, if there is no already\n * existing label for the given bytecode offset (otherwise does nothing). The label is created\n * with a call to {@link #readLabel}.\n *\n * @param bytecodeOffset a bytecode offset in a method.\n * @param labels the already created labels, indexed by their offset.\n */\n private void createDebugLabel(final int bytecodeOffset, final Label[] labels) {\n if (labels[bytecodeOffset] == null) {\n readLabel(bytecodeOffset, labels).flags |= Label.FLAG_DEBUG_ONLY;\n }\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse annotations, type annotations and parameter annotations\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Parses a Runtime[In]VisibleTypeAnnotations attribute to find the offset of each type_annotation\n * entry it contains, to find the corresponding labels, and to visit the try catch block\n * annotations.\n *\n * @param methodVisitor the method visitor to be used to visit the try catch block annotations.\n * @param context information about the class being parsed.\n * @param runtimeTypeAnnotationsOffset the start offset of a Runtime[In]VisibleTypeAnnotations\n * attribute, excluding the attribute_info's attribute_name_index and attribute_length fields.\n * @param visible true if the attribute to parse is a RuntimeVisibleTypeAnnotations attribute,\n * false it is a RuntimeInvisibleTypeAnnotations attribute.\n * @return the start offset of each entry of the Runtime[In]VisibleTypeAnnotations_attribute's\n * 'annotations' array field.\n */\n private int[] readTypeAnnotations(final MethodVisitor methodVisitor, final Context context, final int runtimeTypeAnnotationsOffset, final boolean visible) {\n char[] charBuffer = context.charBuffer;\n int currentOffset = runtimeTypeAnnotationsOffset;\n // Read the num_annotations field and create an array to store the type_annotation offsets.\n int[] typeAnnotationsOffsets = new int[readUnsignedShort(currentOffset)];\n currentOffset += 2;\n // Parse the 'annotations' array field.\n for (int i = 0; i < typeAnnotationsOffsets.length; ++i) {\n typeAnnotationsOffsets[i] = currentOffset;\n // Parse the type_annotation's target_type and the target_info fields. The size of the\n // target_info field depends on the value of target_type.\n int targetType = readInt(currentOffset);\n switch (targetType >>> 24) {\n case TypeReference.LOCAL_VARIABLE:\n case TypeReference.RESOURCE_VARIABLE:\n // A localvar_target has a variable size, which depends on the value of their table_length\n // field. It also references bytecode offsets, for which we need labels.\n int tableLength = readUnsignedShort(currentOffset + 1);\n currentOffset += 3;\n while (tableLength-- > 0) {\n int startPc = readUnsignedShort(currentOffset);\n int length = readUnsignedShort(currentOffset + 2);\n // Skip the index field (2 bytes).\n currentOffset += 6;\n createLabel(startPc, context.currentMethodLabels);\n createLabel(startPc + length, context.currentMethodLabels);\n }\n break;\n case TypeReference.CAST:\n case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:\n case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT:\n currentOffset += 4;\n break;\n case TypeReference.CLASS_EXTENDS:\n case TypeReference.CLASS_TYPE_PARAMETER_BOUND:\n case TypeReference.METHOD_TYPE_PARAMETER_BOUND:\n case TypeReference.THROWS:\n case TypeReference.EXCEPTION_PARAMETER:\n case TypeReference.INSTANCEOF:\n case TypeReference.NEW:\n case TypeReference.CONSTRUCTOR_REFERENCE:\n case TypeReference.METHOD_REFERENCE:\n currentOffset += 3;\n break;\n case TypeReference.CLASS_TYPE_PARAMETER:\n case TypeReference.METHOD_TYPE_PARAMETER:\n case TypeReference.METHOD_FORMAL_PARAMETER:\n case TypeReference.FIELD:\n case TypeReference.METHOD_RETURN:\n case TypeReference.METHOD_RECEIVER:\n default:\n // TypeReference type which can't be used in Code attribute, or which is unknown.\n throw new IllegalArgumentException();\n }\n // Parse the rest of the type_annotation structure, starting with the target_path structure\n // (whose size depends on its path_length field).\n int pathLength = readByte(currentOffset);\n if ((targetType >>> 24) == TypeReference.EXCEPTION_PARAMETER) {\n // Parse the target_path structure and create a corresponding TypePath.\n TypePath path = pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset);\n currentOffset += 1 + 2 * pathLength;\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentOffset = readElementValues(methodVisitor.visitTryCatchAnnotation(targetType & 0xFFFFFF00, path, annotationDescriptor, visible), currentOffset,\n /* named = */ true, charBuffer);\n } else {\n // We don't want to visit the other target_type annotations, so we just skip them (which\n // requires some parsing because the element_value_pairs array has a variable size). First,\n // skip the target_path structure:\n currentOffset += 3 + 2 * pathLength;\n // Then skip the num_element_value_pairs and element_value_pairs fields (by reading them\n // with a null AnnotationVisitor).\n currentOffset = readElementValues(\n /* annotationVisitor = */ null, currentOffset, /* named = */ true, charBuffer);\n }\n }\n return typeAnnotationsOffsets;\n }\n\n /**\n * Returns the bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or\n * -1 if there is no such type_annotation of if it does not have a bytecode offset.\n *\n * @param typeAnnotationOffsets the offset of each 'type_annotation' entry in a\n * Runtime[In]VisibleTypeAnnotations attribute, or {@literal null}.\n * @param typeAnnotationIndex the index a 'type_annotation' entry in typeAnnotationOffsets.\n * @return bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or -1\n * if there is no such type_annotation of if it does not have a bytecode offset.\n */\n private int getTypeAnnotationBytecodeOffset(final int[] typeAnnotationOffsets, final int typeAnnotationIndex) {\n if (typeAnnotationOffsets == null || typeAnnotationIndex >= typeAnnotationOffsets.length || readByte(typeAnnotationOffsets[typeAnnotationIndex]) < TypeReference.INSTANCEOF) {\n return -1;\n }\n return readUnsignedShort(typeAnnotationOffsets[typeAnnotationIndex] + 1);\n }\n\n /**\n * Parses the header of a JVMS type_annotation structure to extract its target_type, target_info\n * and target_path (the result is stored in the given context), and returns the start offset of\n * the rest of the type_annotation structure.\n *\n * @param context information about the class being parsed. This is where the extracted\n * target_type and target_path must be stored.\n * @param typeAnnotationOffset the start offset of a type_annotation structure.\n * @return the start offset of the rest of the type_annotation structure.\n */\n private int readTypeAnnotationTarget(final Context context, final int typeAnnotationOffset) {\n int currentOffset = typeAnnotationOffset;\n // Parse and store the target_type structure.\n int targetType = readInt(typeAnnotationOffset);\n switch (targetType >>> 24) {\n case TypeReference.CLASS_TYPE_PARAMETER:\n case TypeReference.METHOD_TYPE_PARAMETER:\n case TypeReference.METHOD_FORMAL_PARAMETER:\n targetType &= 0xFFFF0000;\n currentOffset += 2;\n break;\n case TypeReference.FIELD:\n case TypeReference.METHOD_RETURN:\n case TypeReference.METHOD_RECEIVER:\n targetType &= 0xFF000000;\n currentOffset += 1;\n break;\n case TypeReference.LOCAL_VARIABLE:\n case TypeReference.RESOURCE_VARIABLE:\n targetType &= 0xFF000000;\n int tableLength = readUnsignedShort(currentOffset + 1);\n currentOffset += 3;\n context.currentLocalVariableAnnotationRangeStarts = new Label[tableLength];\n context.currentLocalVariableAnnotationRangeEnds = new Label[tableLength];\n context.currentLocalVariableAnnotationRangeIndices = new int[tableLength];\n for (int i = 0; i < tableLength; ++i) {\n int startPc = readUnsignedShort(currentOffset);\n int length = readUnsignedShort(currentOffset + 2);\n int index = readUnsignedShort(currentOffset + 4);\n currentOffset += 6;\n context.currentLocalVariableAnnotationRangeStarts[i] = createLabel(startPc, context.currentMethodLabels);\n context.currentLocalVariableAnnotationRangeEnds[i] = createLabel(startPc + length, context.currentMethodLabels);\n context.currentLocalVariableAnnotationRangeIndices[i] = index;\n }\n break;\n case TypeReference.CAST:\n case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT:\n case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:\n case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT:\n targetType &= 0xFF0000FF;\n currentOffset += 4;\n break;\n case TypeReference.CLASS_EXTENDS:\n case TypeReference.CLASS_TYPE_PARAMETER_BOUND:\n case TypeReference.METHOD_TYPE_PARAMETER_BOUND:\n case TypeReference.THROWS:\n case TypeReference.EXCEPTION_PARAMETER:\n targetType &= 0xFFFFFF00;\n currentOffset += 3;\n break;\n case TypeReference.INSTANCEOF:\n case TypeReference.NEW:\n case TypeReference.CONSTRUCTOR_REFERENCE:\n case TypeReference.METHOD_REFERENCE:\n targetType &= 0xFF000000;\n currentOffset += 3;\n break;\n default:\n throw new IllegalArgumentException();\n }\n context.currentTypeAnnotationTarget = targetType;\n // Parse and store the target_path structure.\n int pathLength = readByte(currentOffset);\n context.currentTypeAnnotationTargetPath = pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset);\n // Return the start offset of the rest of the type_annotation structure.\n return currentOffset + 1 + 2 * pathLength;\n }\n\n /**\n * Reads a Runtime[In]VisibleParameterAnnotations attribute and makes the given visitor visit it.\n *\n * @param methodVisitor the visitor that must visit the parameter annotations.\n * @param context information about the class being parsed.\n * @param runtimeParameterAnnotationsOffset the start offset of a\n * Runtime[In]VisibleParameterAnnotations attribute, excluding the attribute_info's\n * attribute_name_index and attribute_length fields.\n * @param visible true if the attribute to parse is a RuntimeVisibleParameterAnnotations\n * attribute, false it is a RuntimeInvisibleParameterAnnotations attribute.\n */\n private void readParameterAnnotations(final MethodVisitor methodVisitor, final Context context, final int runtimeParameterAnnotationsOffset, final boolean visible) {\n int currentOffset = runtimeParameterAnnotationsOffset;\n int numParameters = classFileBuffer[currentOffset++] & 0xFF;\n methodVisitor.visitAnnotableParameterCount(numParameters, visible);\n char[] charBuffer = context.charBuffer;\n for (int i = 0; i < numParameters; ++i) {\n int numAnnotations = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (numAnnotations-- > 0) {\n // Parse the type_index field.\n String annotationDescriptor = readUTF8(currentOffset, charBuffer);\n currentOffset += 2;\n // Parse num_element_value_pairs and element_value_pairs and visit these values.\n currentOffset = readElementValues(methodVisitor.visitParameterAnnotation(i, annotationDescriptor, visible), currentOffset,\n /* named = */ true, charBuffer);\n }\n }\n }\n\n /**\n * Reads the element values of a JVMS 'annotation' structure and makes the given visitor visit\n * them. This method can also be used to read the values of the JVMS 'array_value' field of an\n * annotation's 'element_value'.\n *\n * @param annotationVisitor the visitor that must visit the values.\n * @param annotationOffset the start offset of an 'annotation' structure (excluding its type_index\n * field) or of an 'array_value' structure.\n * @param named if the annotation values are named or not. This should be true to parse the values\n * of a JVMS 'annotation' structure, and false to parse the JVMS 'array_value' of an\n * annotation's element_value.\n * @param charBuffer the buffer used to read strings in the constant pool.\n * @return the end offset of the JVMS 'annotation' or 'array_value' structure.\n */\n private int readElementValues(final AnnotationVisitor annotationVisitor, final int annotationOffset, final boolean named, final char[] charBuffer) {\n int currentOffset = annotationOffset;\n // Read the num_element_value_pairs field (or num_values field for an array_value).\n int numElementValuePairs = readUnsignedShort(currentOffset);\n currentOffset += 2;\n if (named) {\n // Parse the element_value_pairs array.\n while (numElementValuePairs-- > 0) {\n String elementName = readUTF8(currentOffset, charBuffer);\n currentOffset = readElementValue(annotationVisitor, currentOffset + 2, elementName, charBuffer);\n }\n } else {\n // Parse the array_value array.\n while (numElementValuePairs-- > 0) {\n currentOffset = readElementValue(annotationVisitor, currentOffset, /* named = */ null, charBuffer);\n }\n }\n if (annotationVisitor != null) {\n annotationVisitor.visitEnd();\n }\n return currentOffset;\n }\n\n /**\n * Reads a JVMS 'element_value' structure and makes the given visitor visit it.\n *\n * @param annotationVisitor the visitor that must visit the element_value structure.\n * @param elementValueOffset the start offset in {@link #classFileBuffer} of the element_value\n * structure to be read.\n * @param elementName the name of the element_value structure to be read, or {@literal null}.\n * @param charBuffer the buffer used to read strings in the constant pool.\n * @return the end offset of the JVMS 'element_value' structure.\n */\n private int readElementValue(final AnnotationVisitor annotationVisitor, final int elementValueOffset, final String elementName, final char[] charBuffer) {\n int currentOffset = elementValueOffset;\n if (annotationVisitor == null) {\n switch (classFileBuffer[currentOffset] & 0xFF) {\n case 'e': // enum_const_value\n return currentOffset + 5;\n case '@': // annotation_value\n return readElementValues(null, currentOffset + 3, /* named = */ true, charBuffer);\n case '[': // array_value\n return readElementValues(null, currentOffset + 1, /* named = */ false, charBuffer);\n default:\n return currentOffset + 3;\n }\n }\n switch (classFileBuffer[currentOffset++] & 0xFF) {\n case 'B': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]));\n currentOffset += 2;\n break;\n case 'C': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]));\n currentOffset += 2;\n break;\n case 'D': // const_value_index, CONSTANT_Double\n case 'F': // const_value_index, CONSTANT_Float\n case 'I': // const_value_index, CONSTANT_Integer\n case 'J': // const_value_index, CONSTANT_Long\n annotationVisitor.visit(elementName, readConst(readUnsignedShort(currentOffset), charBuffer));\n currentOffset += 2;\n break;\n case 'S': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]));\n currentOffset += 2;\n break;\n case 'Z': // const_value_index, CONSTANT_Integer\n annotationVisitor.visit(elementName, readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]) == 0 ? Boolean.FALSE : Boolean.TRUE);\n currentOffset += 2;\n break;\n case 's': // const_value_index, CONSTANT_Utf8\n annotationVisitor.visit(elementName, readUTF8(currentOffset, charBuffer));\n currentOffset += 2;\n break;\n case 'e': // enum_const_value\n annotationVisitor.visitEnum(elementName, readUTF8(currentOffset, charBuffer), readUTF8(currentOffset + 2, charBuffer));\n currentOffset += 4;\n break;\n case 'c': // class_info\n annotationVisitor.visit(elementName, Type.getType(readUTF8(currentOffset, charBuffer)));\n currentOffset += 2;\n break;\n case '@': // annotation_value\n currentOffset = readElementValues(annotationVisitor.visitAnnotation(elementName, readUTF8(currentOffset, charBuffer)), currentOffset + 2, true, charBuffer);\n break;\n case '[': // array_value\n int numValues = readUnsignedShort(currentOffset);\n currentOffset += 2;\n if (numValues == 0) {\n return readElementValues(annotationVisitor.visitArray(elementName), currentOffset - 2,\n /* named = */ false, charBuffer);\n }\n switch (classFileBuffer[currentOffset] & 0xFF) {\n case 'B':\n byte[] byteValues = new byte[numValues];\n for (int i = 0; i < numValues; i++) {\n byteValues[i] = (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, byteValues);\n break;\n case 'Z':\n boolean[] booleanValues = new boolean[numValues];\n for (int i = 0; i < numValues; i++) {\n booleanValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]) != 0;\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, booleanValues);\n break;\n case 'S':\n short[] shortValues = new short[numValues];\n for (int i = 0; i < numValues; i++) {\n shortValues[i] = (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, shortValues);\n break;\n case 'C':\n char[] charValues = new char[numValues];\n for (int i = 0; i < numValues; i++) {\n charValues[i] = (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, charValues);\n break;\n case 'I':\n int[] intValues = new int[numValues];\n for (int i = 0; i < numValues; i++) {\n intValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, intValues);\n break;\n case 'J':\n long[] longValues = new long[numValues];\n for (int i = 0; i < numValues; i++) {\n longValues[i] = readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]);\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, longValues);\n break;\n case 'F':\n float[] floatValues = new float[numValues];\n for (int i = 0; i < numValues; i++) {\n floatValues[i] = Float.intBitsToFloat(readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]));\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, floatValues);\n break;\n case 'D':\n double[] doubleValues = new double[numValues];\n for (int i = 0; i < numValues; i++) {\n doubleValues[i] = Double.longBitsToDouble(readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]));\n currentOffset += 3;\n }\n annotationVisitor.visit(elementName, doubleValues);\n break;\n default:\n currentOffset = readElementValues(annotationVisitor.visitArray(elementName), currentOffset - 2,\n /* named = */ false, charBuffer);\n break;\n }\n break;\n default:\n throw new IllegalArgumentException();\n }\n return currentOffset;\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse stack map frames\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Computes the implicit frame of the method currently being parsed (as defined in the given\n * {@link Context}) and stores it in the given context.\n *\n * @param context information about the class being parsed.\n */\n private void computeImplicitFrame(final Context context) {\n String methodDescriptor = context.currentMethodDescriptor;\n Object[] locals = context.currentFrameLocalTypes;\n int numLocal = 0;\n if ((context.currentMethodAccessFlags & Opcodes.ACC_STATIC) == 0) {\n if (\"\".equals(context.currentMethodName)) {\n locals[numLocal++] = Opcodes.UNINITIALIZED_THIS;\n } else {\n locals[numLocal++] = readClass(header + 2, context.charBuffer);\n }\n }\n // Parse the method descriptor, one argument type descriptor at each iteration. Start by\n // skipping the first method descriptor character, which is always '('.\n int currentMethodDescritorOffset = 1;\n while (true) {\n int currentArgumentDescriptorStartOffset = currentMethodDescritorOffset;\n switch (methodDescriptor.charAt(currentMethodDescritorOffset++)) {\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n locals[numLocal++] = Opcodes.INTEGER;\n break;\n case 'F':\n locals[numLocal++] = Opcodes.FLOAT;\n break;\n case 'J':\n locals[numLocal++] = Opcodes.LONG;\n break;\n case 'D':\n locals[numLocal++] = Opcodes.DOUBLE;\n break;\n case '[':\n while (methodDescriptor.charAt(currentMethodDescritorOffset) == '[') {\n ++currentMethodDescritorOffset;\n }\n if (methodDescriptor.charAt(currentMethodDescritorOffset) == 'L') {\n ++currentMethodDescritorOffset;\n while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') {\n ++currentMethodDescritorOffset;\n }\n }\n locals[numLocal++] = methodDescriptor.substring(currentArgumentDescriptorStartOffset, ++currentMethodDescritorOffset);\n break;\n case 'L':\n while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') {\n ++currentMethodDescritorOffset;\n }\n locals[numLocal++] = methodDescriptor.substring(currentArgumentDescriptorStartOffset + 1, currentMethodDescritorOffset++);\n break;\n default:\n context.currentFrameLocalCount = numLocal;\n return;\n }\n }\n }\n\n /**\n * Reads a JVMS 'stack_map_frame' structure and stores the result in the given {@link Context}\n * object. This method can also be used to read a full_frame structure, excluding its frame_type\n * field (this is used to parse the legacy StackMap attributes).\n *\n * @param stackMapFrameOffset the start offset in {@link #classFileBuffer} of the\n * stack_map_frame_value structure to be read, or the start offset of a full_frame structure\n * (excluding its frame_type field).\n * @param compressed true to read a 'stack_map_frame' structure, false to read a 'full_frame'\n * structure without its frame_type field.\n * @param expand if the stack map frame must be expanded. See {@link #EXPAND_FRAMES}.\n * @param context where the parsed stack map frame must be stored.\n * @return the end offset of the JVMS 'stack_map_frame' or 'full_frame' structure.\n */\n private int readStackMapFrame(final int stackMapFrameOffset, final boolean compressed, final boolean expand, final Context context) {\n int currentOffset = stackMapFrameOffset;\n final char[] charBuffer = context.charBuffer;\n final Label[] labels = context.currentMethodLabels;\n int frameType;\n if (compressed) {\n // Read the frame_type field.\n frameType = classFileBuffer[currentOffset++] & 0xFF;\n } else {\n frameType = Frame.FULL_FRAME;\n context.currentFrameOffset = -1;\n }\n int offsetDelta;\n context.currentFrameLocalCountDelta = 0;\n if (frameType < Frame.SAME_LOCALS_1_STACK_ITEM_FRAME) {\n offsetDelta = frameType;\n context.currentFrameType = Opcodes.F_SAME;\n context.currentFrameStackCount = 0;\n } else if (frameType < Frame.RESERVED) {\n offsetDelta = frameType - Frame.SAME_LOCALS_1_STACK_ITEM_FRAME;\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels);\n context.currentFrameType = Opcodes.F_SAME1;\n context.currentFrameStackCount = 1;\n } else if (frameType >= Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {\n offsetDelta = readUnsignedShort(currentOffset);\n currentOffset += 2;\n if (frameType == Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels);\n context.currentFrameType = Opcodes.F_SAME1;\n context.currentFrameStackCount = 1;\n } else if (frameType >= Frame.CHOP_FRAME && frameType < Frame.SAME_FRAME_EXTENDED) {\n context.currentFrameType = Opcodes.F_CHOP;\n context.currentFrameLocalCountDelta = Frame.SAME_FRAME_EXTENDED - frameType;\n context.currentFrameLocalCount -= context.currentFrameLocalCountDelta;\n context.currentFrameStackCount = 0;\n } else if (frameType == Frame.SAME_FRAME_EXTENDED) {\n context.currentFrameType = Opcodes.F_SAME;\n context.currentFrameStackCount = 0;\n } else if (frameType < Frame.FULL_FRAME) {\n int local = expand ? context.currentFrameLocalCount : 0;\n for (int k = frameType - Frame.SAME_FRAME_EXTENDED; k > 0; k--) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameLocalTypes, local++, charBuffer, labels);\n }\n context.currentFrameType = Opcodes.F_APPEND;\n context.currentFrameLocalCountDelta = frameType - Frame.SAME_FRAME_EXTENDED;\n context.currentFrameLocalCount += context.currentFrameLocalCountDelta;\n context.currentFrameStackCount = 0;\n } else {\n final int numberOfLocals = readUnsignedShort(currentOffset);\n currentOffset += 2;\n context.currentFrameType = Opcodes.F_FULL;\n context.currentFrameLocalCountDelta = numberOfLocals;\n context.currentFrameLocalCount = numberOfLocals;\n for (int local = 0; local < numberOfLocals; ++local) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameLocalTypes, local, charBuffer, labels);\n }\n final int numberOfStackItems = readUnsignedShort(currentOffset);\n currentOffset += 2;\n context.currentFrameStackCount = numberOfStackItems;\n for (int stack = 0; stack < numberOfStackItems; ++stack) {\n currentOffset = readVerificationTypeInfo(currentOffset, context.currentFrameStackTypes, stack, charBuffer, labels);\n }\n }\n } else {\n throw new IllegalArgumentException();\n }\n context.currentFrameOffset += offsetDelta + 1;\n createLabel(context.currentFrameOffset, labels);\n return currentOffset;\n }\n\n /**\n * Reads a JVMS 'verification_type_info' structure and stores it at the given index in the given\n * array.\n *\n * @param verificationTypeInfoOffset the start offset of the 'verification_type_info' structure to\n * read.\n * @param frame the array where the parsed type must be stored.\n * @param index the index in 'frame' where the parsed type must be stored.\n * @param charBuffer the buffer used to read strings in the constant pool.\n * @param labels the labels of the method currently being parsed, indexed by their offset. If the\n * parsed type is an ITEM_Uninitialized, a new label for the corresponding NEW instruction is\n * stored in this array if it does not already exist.\n * @return the end offset of the JVMS 'verification_type_info' structure.\n */\n private int readVerificationTypeInfo(final int verificationTypeInfoOffset, final Object[] frame, final int index, final char[] charBuffer, final Label[] labels) {\n int currentOffset = verificationTypeInfoOffset;\n int tag = classFileBuffer[currentOffset++] & 0xFF;\n switch (tag) {\n case Frame.ITEM_TOP:\n frame[index] = Opcodes.TOP;\n break;\n case Frame.ITEM_INTEGER:\n frame[index] = Opcodes.INTEGER;\n break;\n case Frame.ITEM_FLOAT:\n frame[index] = Opcodes.FLOAT;\n break;\n case Frame.ITEM_DOUBLE:\n frame[index] = Opcodes.DOUBLE;\n break;\n case Frame.ITEM_LONG:\n frame[index] = Opcodes.LONG;\n break;\n case Frame.ITEM_NULL:\n frame[index] = Opcodes.NULL;\n break;\n case Frame.ITEM_UNINITIALIZED_THIS:\n frame[index] = Opcodes.UNINITIALIZED_THIS;\n break;\n case Frame.ITEM_OBJECT:\n frame[index] = readClass(currentOffset, charBuffer);\n currentOffset += 2;\n break;\n case Frame.ITEM_UNINITIALIZED:\n frame[index] = createLabel(readUnsignedShort(currentOffset), labels);\n currentOffset += 2;\n break;\n default:\n throw new IllegalArgumentException();\n }\n return currentOffset;\n }\n // ----------------------------------------------------------------------------------------------\n // Methods to parse attributes\n // ----------------------------------------------------------------------------------------------\n\n /**\n * Returns the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array\n * field entry.\n *\n * @return the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array\n * field entry.\n */\n final int getFirstAttributeOffset() {\n // Skip the access_flags, this_class, super_class, and interfaces_count fields (using 2 bytes\n // each), as well as the interfaces array field (2 bytes per interface).\n int currentOffset = header + 8 + readUnsignedShort(header + 6) * 2;\n // Read the fields_count field.\n int fieldsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n // Skip the 'fields' array field.\n while (fieldsCount-- > 0) {\n // Invariant: currentOffset is the offset of a field_info structure.\n // Skip the access_flags, name_index and descriptor_index fields (2 bytes each), and read the\n // attributes_count field.\n int attributesCount = readUnsignedShort(currentOffset + 6);\n currentOffset += 8;\n // Skip the 'attributes' array field.\n while (attributesCount-- > 0) {\n // Invariant: currentOffset is the offset of an attribute_info structure.\n // Read the attribute_length field (2 bytes after the start of the attribute_info) and skip\n // this many bytes, plus 6 for the attribute_name_index and attribute_length fields\n // (yielding the total size of the attribute_info structure).\n currentOffset += 6 + readInt(currentOffset + 2);\n }\n }\n // Skip the methods_count and 'methods' fields, using the same method as above.\n int methodsCount = readUnsignedShort(currentOffset);\n currentOffset += 2;\n while (methodsCount-- > 0) {\n int attributesCount = readUnsignedShort(currentOffset + 6);\n currentOffset += 8;\n while (attributesCount-- > 0) {\n currentOffset += 6 + readInt(currentOffset + 2);\n }\n }\n // Skip the ClassFile's attributes_count field.\n return currentOffset + 2;\n }\n\n /**\n * Reads the BootstrapMethods attribute to compute the offset of each bootstrap method.\n *\n * @param maxStringLength a conservative estimate of the maximum length of the strings contained\n * in the constant pool of the class.\n * @return the offsets of the bootstrap methods.\n */\n private int[] readBootstrapMethodsAttribute(final int maxStringLength) {\n char[] charBuffer = new char[maxStringLength];\n int currentAttributeOffset = getFirstAttributeOffset();\n int[] currentBootstrapMethodOffsets = null;\n for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) {\n // Read the attribute_info's attribute_name and attribute_length fields.\n String attributeName = readUTF8(currentAttributeOffset, charBuffer);\n int attributeLength = readInt(currentAttributeOffset + 2);\n currentAttributeOffset += 6;\n if (Constants.BOOTSTRAP_METHODS.equals(attributeName)) {\n // Read the num_bootstrap_methods field and create an array of this size.\n currentBootstrapMethodOffsets = new int[readUnsignedShort(currentAttributeOffset)];\n // Compute and store the offset of each 'bootstrap_methods' array field entry.\n int currentBootstrapMethodOffset = currentAttributeOffset + 2;\n for (int j = 0; j < currentBootstrapMethodOffsets.length; ++j) {\n currentBootstrapMethodOffsets[j] = currentBootstrapMethodOffset;\n // Skip the bootstrap_method_ref and num_bootstrap_arguments fields (2 bytes each),\n // as well as the bootstrap_arguments array field (of size num_bootstrap_arguments * 2).\n currentBootstrapMethodOffset += 4 + readUnsignedShort(currentBootstrapMethodOffset + 2) * 2;\n }\n return currentBootstrapMethodOffsets;\n }\n currentAttributeOffset += attributeLength;\n }\n throw new IllegalArgumentException();\n }\n\n /**\n * Reads a non standard JVMS 'attribute' structure in {@link #classFileBuffer}.\n *\n * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of\n * the class. Any attribute whose type is not equal to the type of one the prototypes will not\n * be parsed: its byte array value will be passed unchanged to the ClassWriter.\n * @param type the type of the attribute.\n * @param offset the start offset of the JVMS 'attribute' structure in {@link #classFileBuffer}.\n * The 6 attribute header bytes (attribute_name_index and attribute_length) are not taken into\n * account here.\n * @param length the length of the attribute's content (excluding the 6 attribute header bytes).\n * @param charBuffer the buffer to be used to read strings in the constant pool.\n * @param codeAttributeOffset the start offset of the enclosing Code attribute in {@link\n * #classFileBuffer}, or -1 if the attribute to be read is not a code attribute. The 6\n * attribute header bytes (attribute_name_index and attribute_length) are not taken into\n * account here.\n * @param labels the labels of the method's code, or {@literal null} if the attribute to be read\n * is not a code attribute.\n * @return the attribute that has been read.\n */\n private Attribute readAttribute(final Attribute[] attributePrototypes, final String type, final int offset, final int length, final char[] charBuffer, final int codeAttributeOffset, final Label[] labels) {\n for (Attribute attributePrototype : attributePrototypes) {\n if (attributePrototype.type.equals(type)) {\n return attributePrototype.read(this, offset, length, charBuffer, codeAttributeOffset, labels);\n }\n }\n return new Attribute(type).read(this, offset, length, null, -1, null);\n }\n // -----------------------------------------------------------------------------------------------\n // Utility methods: low level parsing\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the number of entries in the class's constant pool table.\n *\n * @return the number of entries in the class's constant pool table.\n */\n public int getItemCount() {\n return cpInfoOffsets.length;\n }\n\n /**\n * Returns the start offset in this {@link ClassReader} of a JVMS 'cp_info' structure (i.e. a\n * constant pool entry), plus one. This method is intended for {@link Attribute} sub classes,\n * and is normally not needed by class generators or adapters.\n *\n * @param constantPoolEntryIndex the index a constant pool entry in the class's constant pool\n * table.\n * @return the start offset in this {@link ClassReader} of the corresponding JVMS 'cp_info'\n * structure, plus one.\n */\n public int getItem(final int constantPoolEntryIndex) {\n return cpInfoOffsets[constantPoolEntryIndex];\n }\n\n /**\n * Returns a conservative estimate of the maximum length of the strings contained in the class's\n * constant pool table.\n *\n * @return a conservative estimate of the maximum length of the strings contained in the class's\n * constant pool table.\n */\n public int getMaxStringLength() {\n return maxStringLength;\n }\n\n /**\n * Reads a byte value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public int readByte(final int offset) {\n return classFileBuffer[offset] & 0xFF;\n }\n\n /**\n * Reads an unsigned short value in this {@link ClassReader}. This method is intended for\n * {@link Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start index of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public int readUnsignedShort(final int offset) {\n byte[] classBuffer = classFileBuffer;\n return ((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF);\n }\n\n /**\n * Reads a signed short value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public short readShort(final int offset) {\n byte[] classBuffer = classFileBuffer;\n return (short) (((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF));\n }\n\n /**\n * Reads a signed int value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public int readInt(final int offset) {\n byte[] classBuffer = classFileBuffer;\n return ((classBuffer[offset] & 0xFF) << 24) | ((classBuffer[offset + 1] & 0xFF) << 16) | ((classBuffer[offset + 2] & 0xFF) << 8) | (classBuffer[offset + 3] & 0xFF);\n }\n\n /**\n * Reads a signed long value in this {@link ClassReader}. This method is intended for {@link\n * Attribute} sub classes, and is normally not needed by class generators or adapters.\n *\n * @param offset the start offset of the value to be read in this {@link ClassReader}.\n * @return the read value.\n */\n public long readLong(final int offset) {\n long l1 = readInt(offset);\n long l0 = readInt(offset + 4) & 0xFFFFFFFFL;\n return (l1 << 32) | l0;\n }\n\n /**\n * Reads a CONSTANT_Utf8 constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Utf8 entry in the class's constant pool table.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Utf8 entry.\n */\n // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility).\n public String readUTF8(final int offset, final char[] charBuffer) {\n int constantPoolEntryIndex = readUnsignedShort(offset);\n if (offset == 0 || constantPoolEntryIndex == 0) {\n return null;\n }\n return readUtf(constantPoolEntryIndex, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Utf8 constant pool entry in {@link #classFileBuffer}.\n *\n * @param constantPoolEntryIndex the index of a CONSTANT_Utf8 entry in the class's constant pool\n * table.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Utf8 entry.\n */\n final String readUtf(final int constantPoolEntryIndex, final char[] charBuffer) {\n String value = constantUtf8Values[constantPoolEntryIndex];\n if (value != null) {\n return value;\n }\n int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex];\n return constantUtf8Values[constantPoolEntryIndex] = readUtf(cpInfoOffset + 2, readUnsignedShort(cpInfoOffset), charBuffer);\n }\n\n /**\n * Reads an UTF8 string in {@link #classFileBuffer}.\n *\n * @param utfOffset the start offset of the UTF8 string to be read.\n * @param utfLength the length of the UTF8 string to be read.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified UTF8 string.\n */\n private String readUtf(final int utfOffset, final int utfLength, final char[] charBuffer) {\n int currentOffset = utfOffset;\n int endOffset = currentOffset + utfLength;\n int strLength = 0;\n byte[] classBuffer = classFileBuffer;\n while (currentOffset < endOffset) {\n int currentByte = classBuffer[currentOffset++];\n if ((currentByte & 0x80) == 0) {\n charBuffer[strLength++] = (char) (currentByte & 0x7F);\n } else if ((currentByte & 0xE0) == 0xC0) {\n charBuffer[strLength++] = (char) (((currentByte & 0x1F) << 6) + (classBuffer[currentOffset++] & 0x3F));\n } else {\n charBuffer[strLength++] = (char) (((currentByte & 0xF) << 12) + ((classBuffer[currentOffset++] & 0x3F) << 6) + (classBuffer[currentOffset++] & 0x3F));\n }\n }\n return new String(charBuffer, 0, strLength);\n }\n\n /**\n * Reads a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, CONSTANT_Module or\n * CONSTANT_Package constant pool entry in {@link #classFileBuffer}. This method is intended\n * for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in {@link #classFileBuffer}, whose\n * value is the index of a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType,\n * CONSTANT_Module or CONSTANT_Package entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified constant pool entry.\n */\n private String readStringish(final int offset, final char[] charBuffer) {\n // Get the start offset of the cp_info structure (plus one), and read the CONSTANT_Utf8 entry\n // designated by the first two bytes of this cp_info.\n return readUTF8(cpInfoOffsets[readUnsignedShort(offset)], charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Class constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Class entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Class entry.\n */\n public String readClass(final int offset, final char[] charBuffer) {\n return readStringish(offset, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Module constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Module entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Module entry.\n */\n public String readModule(final int offset, final char[] charBuffer) {\n return readStringish(offset, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Package constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose\n * value is the index of a CONSTANT_Package entry in class's constant pool table.\n * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the String corresponding to the specified CONSTANT_Package entry.\n */\n public String readPackage(final int offset, final char[] charBuffer) {\n return readStringish(offset, charBuffer);\n }\n\n /**\n * Reads a CONSTANT_Dynamic constant pool entry in {@link #classFileBuffer}.\n *\n * @param constantPoolEntryIndex the index of a CONSTANT_Dynamic entry in the class's constant\n * pool table.\n * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the ConstantDynamic corresponding to the specified CONSTANT_Dynamic entry.\n */\n private ConstantDynamic readConstantDynamic(final int constantPoolEntryIndex, final char[] charBuffer) {\n ConstantDynamic constantDynamic = constantDynamicValues[constantPoolEntryIndex];\n if (constantDynamic != null) {\n return constantDynamic;\n }\n int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)];\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)];\n Handle handle = (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n Object[] bootstrapMethodArguments = new Object[readUnsignedShort(bootstrapMethodOffset + 2)];\n bootstrapMethodOffset += 4;\n for (int i = 0; i < bootstrapMethodArguments.length; i++) {\n bootstrapMethodArguments[i] = readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer);\n bootstrapMethodOffset += 2;\n }\n return constantDynamicValues[constantPoolEntryIndex] = new ConstantDynamic(name, descriptor, handle, bootstrapMethodArguments);\n }\n\n /**\n * Reads a numeric or string constant pool entry in this {@link ClassReader}. This method is\n * intended for {@link Attribute} sub classes, and is normally not needed by class generators or\n * adapters.\n *\n * @param constantPoolEntryIndex the index of a CONSTANT_Integer, CONSTANT_Float, CONSTANT_Long,\n * CONSTANT_Double, CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType,\n * CONSTANT_MethodHandle or CONSTANT_Dynamic entry in the class's constant pool.\n * @param charBuffer the buffer to be used to read strings. This buffer must be sufficiently\n * large. It is not automatically resized.\n * @return the {@link Integer}, {@link Float}, {@link Long}, {@link Double}, {@link String},\n * {@link Type}, {@link Handle} or {@link ConstantDynamic} corresponding to the specified\n * constant pool entry.\n */\n public Object readConst(final int constantPoolEntryIndex, final char[] charBuffer) {\n int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex];\n switch (classFileBuffer[cpInfoOffset - 1]) {\n case Symbol.CONSTANT_INTEGER_TAG:\n return readInt(cpInfoOffset);\n case Symbol.CONSTANT_FLOAT_TAG:\n return Float.intBitsToFloat(readInt(cpInfoOffset));\n case Symbol.CONSTANT_LONG_TAG:\n return readLong(cpInfoOffset);\n case Symbol.CONSTANT_DOUBLE_TAG:\n return Double.longBitsToDouble(readLong(cpInfoOffset));\n case Symbol.CONSTANT_CLASS_TAG:\n return Type.getObjectType(readUTF8(cpInfoOffset, charBuffer));\n case Symbol.CONSTANT_STRING_TAG:\n return readUTF8(cpInfoOffset, charBuffer);\n case Symbol.CONSTANT_METHOD_TYPE_TAG:\n return Type.getMethodType(readUTF8(cpInfoOffset, charBuffer));\n case Symbol.CONSTANT_METHOD_HANDLE_TAG:\n int referenceKind = readByte(cpInfoOffset);\n int referenceCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 1)];\n int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(referenceCpInfoOffset + 2)];\n String owner = readClass(referenceCpInfoOffset, charBuffer);\n String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer);\n String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer);\n boolean isInterface = classFileBuffer[referenceCpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG;\n return new Handle(referenceKind, owner, name, descriptor, isInterface);\n case Symbol.CONSTANT_DYNAMIC_TAG:\n return readConstantDynamic(constantPoolEntryIndex, charBuffer);\n default:\n throw new IllegalArgumentException();\n }\n }\n}\n", "file_name": "ClassReader.java", "human_label": "Read a CONSTANT_Utf8 constant pool entry in the classFileBuffer.", "level": "class_runnable", "lineno": "3156", "name": "readUtf", "oracle_context": "{ \"apis\" : \"[readUnsignedShort]\", \"classes\" : \"[String]\", \"vars\" : \"[constantUtf8Values, cpInfoOffsets]\" }", "package": "net.hasor.utils.asm", "project": "hasor-master" }, { "_id": "636766851a6d9265ec01751b", "all_context": "{ \"class_level\" : \"import java.io.UnsupportedEncodingException;\\nimport java.net.URI;\\nimport java.net.URLDecoder;\\nimport java.nio.charset.Charset;\\nimport java.nio.charset.StandardCharsets;\\nimport java.util.ArrayList;\\nimport java.util.Collections;\\nimport java.util.LinkedHashMap;\\nimport java.util.List;\\nimport java.util.Map;\\nint DEFAULT_MAX_PARAMS;\\nCharset UTF_8;\\nCharset charset;\\nString uri;\\nboolean hasPath;\\nint maxParams;\\nString path;\\nMap> params;\\nint nParams;\\nQueryStringDecoder(String uri);\\nQueryStringDecoder(String uri,boolean hasPath);\\nQueryStringDecoder(String uri,Charset charset);\\nQueryStringDecoder(String uri,Charset charset,boolean hasPath);\\nQueryStringDecoder(String uri,Charset charset,boolean hasPath,int maxParams);\\nQueryStringDecoder(String uri,String charset);\\nQueryStringDecoder(URI uri);\\nQueryStringDecoder(URI uri,Charset charset);\\nQueryStringDecoder(URI uri,Charset charset,int maxParams);\\nQueryStringDecoder(URI uri,String charset);\\ngetPath();\\ngetParameters();\\ndecodeParams(String s);\\naddParam(Map params,String name,String value);\\ndecodeComponent(String s,Charset charset);\\ndecodeHexNibble(char c);\\ndecodeComponent(String s);\\n\", \"repo_level\" : \"\" }", "class_name": "QueryStringDecoder", "code": "private static char decodeHexNibble(final char c){\n if ('0' <= c && c <= '9') {\n return (char)(c - '0');\n }\n else if ('a' <= c && c <= 'f') {\n return (char)(c - 'a' + 10);\n }\n else if ('A' <= c && c <= 'F') {\n return (char)(c - 'A' + 10);\n }\n else {\n return Character.MAX_VALUE;\n }\n}\n", "docstring": "/** \n * Helper to decode half of a hexadecimal number from a string.\n * @param c The ASCII character of the hexadecimal number to decode.Must be in the range {@code [0-9a-fA-F]}.\n * @return The hexadecimal value represented in the ASCII charactergiven, or {@link Character#MAX_VALUE} if the character is invalid.\n */\n", "end_lineno": "425", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n/*\n * Copyright 2018 The Netty Project\n *\n * The Netty Project licenses this file to you under the Apache License,\n * version 2.0 (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at:\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\npackage org.atmosphere.util;\n\nimport java.io.UnsupportedEncodingException;\nimport java.net.URI;\nimport java.net.URLDecoder;\nimport java.nio.charset.Charset;\nimport java.nio.charset.StandardCharsets;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Splits an HTTP query string into a path string and key-value parameter pairs.\n * This decoder is for one time use only. Create a new instance for each URI:\n *

\n * {@link QueryStringDecoder} decoder = new {@link QueryStringDecoder}(\"/hello?recipient=world&x=1;y=2\");\n * assert decoder.getPath().equals(\"/hello\");\n * assert decoder.getParameters().get(\"recipient\").get(0).equals(\"world\");\n * assert decoder.getParameters().get(\"x\").get(0).equals(\"1\");\n * assert decoder.getParameters().get(\"y\").get(0).equals(\"2\");\n * 
\n *\n * This decoder can also decode the content of an HTTP POST request whose\n * content type is application/x-www-form-urlencoded:\n *
\n * {@link QueryStringDecoder} decoder = new {@link QueryStringDecoder}(\"recipient=world&x=1;y=2\", false);\n * ...\n * 
\n *\n *

HashDOS vulnerability fix

\n *\n * As a workaround to the HashDOS vulnerability, the decoder\n * limits the maximum number of decoded key-value parameter pairs, up to {@literal 1024} by\n * default, and you can configure it when you construct the decoder by passing an additional\n * integer parameter.\n *\n * @apiviz.stereotype utility\n * @apiviz.has org.jboss.netty.handler.codec.http.HttpRequest oneway - - decodes\n */\npublic class QueryStringDecoder {\n\n private static final int DEFAULT_MAX_PARAMS = 1024;\n public static final Charset UTF_8 = StandardCharsets.UTF_8;\n\n private final Charset charset;\n private final String uri;\n private final boolean hasPath;\n private final int maxParams;\n private String path;\n private Map> params;\n private int nParams;\n\n /**\n * Creates a new decoder that decodes the specified URI. The decoder will\n * assume that the query string is encoded in UTF-8.\n */\n public QueryStringDecoder(String uri) {\n this(uri, UTF_8);\n }\n\n /**\n * Creates a new decoder that decodes the specified URI encoded in the\n * specified charset.\n */\n public QueryStringDecoder(String uri, boolean hasPath) {\n this(uri, UTF_8, hasPath);\n }\n\n /**\n * Creates a new decoder that decodes the specified URI encoded in the\n * specified charset.\n */\n public QueryStringDecoder(String uri, Charset charset) {\n this(uri, charset, true);\n }\n\n /**\n * Creates a new decoder that decodes the specified URI encoded in the\n * specified charset.\n */\n public QueryStringDecoder(String uri, Charset charset, boolean hasPath) {\n this(uri, charset, hasPath, DEFAULT_MAX_PARAMS);\n }\n\n /**\n * Creates a new decoder that decodes the specified URI encoded in the\n * specified charset.\n */\n public QueryStringDecoder(String uri, Charset charset, boolean hasPath, int maxParams) {\n if (uri == null) {\n throw new NullPointerException(\"uri\");\n }\n if (charset == null) {\n throw new NullPointerException(\"charset\");\n }\n if (maxParams <= 0) {\n throw new IllegalArgumentException(\n \"maxParams: \" + maxParams + \" (expected: a positive integer)\");\n }\n\n // http://en.wikipedia.org/wiki/Query_string\n this.uri = uri.replace(';', '&');\n this.charset = charset;\n this.maxParams = maxParams;\n this.hasPath = hasPath;\n }\n\n /**\n * @deprecated Use {@link #QueryStringDecoder(String, Charset)} instead.\n */\n @Deprecated\n public QueryStringDecoder(String uri, String charset) {\n this(uri, Charset.forName(charset));\n }\n\n /**\n * Creates a new decoder that decodes the specified URI. The decoder will\n * assume that the query string is encoded in UTF-8.\n */\n public QueryStringDecoder(URI uri) {\n this(uri, UTF_8);\n }\n\n /**\n * Creates a new decoder that decodes the specified URI encoded in the\n * specified charset.\n */\n public QueryStringDecoder(URI uri, Charset charset) {\n this(uri, charset, DEFAULT_MAX_PARAMS);\n }\n\n /**\n * Creates a new decoder that decodes the specified URI encoded in the\n * specified charset.\n */\n public QueryStringDecoder(URI uri, Charset charset, int maxParams) {\n if (uri == null) {\n throw new NullPointerException(\"uri\");\n }\n if (charset == null) {\n throw new NullPointerException(\"charset\");\n }\n if (maxParams <= 0) {\n throw new IllegalArgumentException(\n \"maxParams: \" + maxParams + \" (expected: a positive integer)\");\n }\n\n String rawPath = uri.getRawPath();\n if (rawPath != null) {\n hasPath = true;\n } else {\n rawPath = \"\";\n hasPath = false;\n }\n // Also take care of cut of things like \"http://localhost\"\n String newUri = rawPath + \"?\" + uri.getRawQuery();\n\n // http://en.wikipedia.org/wiki/Query_string\n this.uri = newUri.replace(';', '&');\n this.charset = charset;\n this.maxParams = maxParams;\n\n }\n\n /**\n * @deprecated Use {@link #QueryStringDecoder(URI, Charset)} instead.\n */\n @Deprecated\n public QueryStringDecoder(URI uri, String charset) {\n this(uri, Charset.forName(charset));\n }\n\n /**\n * Returns the decoded path string of the URI.\n */\n public String getPath() {\n if (path == null) {\n if (!hasPath) {\n return path = \"\";\n }\n\n int pathEndPos = uri.indexOf('?');\n if (pathEndPos < 0) {\n path = uri;\n } else {\n return path = uri.substring(0, pathEndPos);\n }\n }\n return path;\n }\n\n /**\n * Returns the decoded key-value parameter pairs of the URI.\n */\n public Map> getParameters() {\n if (params == null) {\n if (hasPath) {\n int pathLength = getPath().length();\n if (uri.length() == pathLength) {\n return Collections.emptyMap();\n }\n decodeParams(uri.substring(pathLength + 1));\n } else {\n if (uri.length() == 0) {\n return Collections.emptyMap();\n }\n decodeParams(uri);\n }\n }\n return params;\n }\n\n private void decodeParams(String s) {\n Map> params = this.params = new LinkedHashMap<>();\n nParams = 0;\n String name = null;\n int pos = 0; // Beginning of the unprocessed region\n int i; // End of the unprocessed region\n char c; // Current character\n for (i = 0; i < s.length(); i++) {\n c = s.charAt(i);\n if (c == '=' && name == null) {\n if (pos != i) {\n name = decodeComponent(s.substring(pos, i), charset);\n }\n pos = i + 1;\n } else if (c == '&') {\n if (name == null && pos != i) {\n // We haven't seen an `=' so far but moved forward.\n // Must be a param of the form '&a&' so add it with\n // an empty value.\n if (!addParam(params, decodeComponent(s.substring(pos, i), charset), \"\")) {\n return;\n }\n } else if (name != null) {\n if (!addParam(params, name, decodeComponent(s.substring(pos, i), charset))) {\n return;\n }\n name = null;\n }\n pos = i + 1;\n }\n }\n\n if (pos != i) { // Are there characters we haven't dealt with?\n if (name == null) { // Yes and we haven't seen any `='.\n if (!addParam(params, decodeComponent(s.substring(pos, i), charset), \"\")) {\n return;\n }\n } else { // Yes and this must be the last value.\n if (!addParam(params, name, decodeComponent(s.substring(pos, i), charset))) {\n return;\n }\n }\n } else if (name != null) { // Have we seen a name without value?\n if (!addParam(params, name, \"\")) {\n return;\n }\n }\n }\n\n private boolean addParam(Map> params, String name, String value) {\n if (nParams >= maxParams) {\n return false;\n }\n\n List values = params.computeIfAbsent(name, k -> new ArrayList<>(1));\n // Often there's only 1 value.\n values.add(value);\n nParams ++;\n return true;\n }\n\n /**\n * Decodes a bit of an URL encoded by a browser.\n *

\n * This is equivalent to calling {@link #decodeComponent(String, Charset)}\n * with the UTF-8 charset (recommended to comply with RFC 3986, Section 2).\n * @param s The string to decode (can be empty).\n * @return The decoded string, or {@code s} if there's nothing to decode.\n * If the string to decode is {@code null}, returns an empty string.\n * @throws IllegalArgumentException if the string contains a malformed\n * escape sequence.\n */\n public static String decodeComponent(final String s) {\n return decodeComponent(s, UTF_8);\n }\n\n /**\n * Decodes a bit of an URL encoded by a browser.\n *

\n * The string is expected to be encoded as per RFC 3986, Section 2.\n * This is the encoding used by JavaScript functions {@code encodeURI}\n * and {@code encodeURIComponent}, but not {@code escape}. For example\n * in this encoding, é (in Unicode {@code U+00E9} or in UTF-8\n * {@code 0xC3 0xA9}) is encoded as {@code %C3%A9} or {@code %c3%a9}.\n *

\n * This is essentially equivalent to calling\n * {@link URLDecoder#decode(String, String) URLDecoder.decode}(s, charset.name())\n * except that it's over 2x faster and generates less garbage for the GC.\n * Actually this function doesn't allocate any memory if there's nothing\n * to decode, the argument itself is returned.\n * @param s The string to decode (can be empty).\n * @param charset The charset to use to decode the string (should really\n * be {@link #UTF_8}.\n * @return The decoded string, or {@code s} if there's nothing to decode.\n * If the string to decode is {@code null}, returns an empty string.\n * @throws IllegalArgumentException if the string contains a malformed\n * escape sequence.\n */\n @SuppressWarnings(\"fallthrough\")\n public static String decodeComponent(final String s,\n final Charset charset) {\n if (s == null) {\n return \"\";\n }\n final int size = s.length();\n boolean modified = false;\n for (int i = 0; i < size; i++) {\n final char c = s.charAt(i);\n switch (c) {\n case '%':\n i++; // We can skip at least one char, e.g. `%%'.\n // Fall through.\n case '+':\n modified = true;\n break;\n }\n }\n if (!modified) {\n return s;\n }\n final byte[] buf = new byte[size];\n int pos = 0; // position in `buf'.\n for (int i = 0; i < size; i++) {\n char c = s.charAt(i);\n switch (c) {\n case '+':\n buf[pos++] = ' '; // \"+\" -> \" \"\n break;\n case '%':\n if (i == size - 1) {\n throw new IllegalArgumentException(\"unterminated escape\"\n + \" sequence at end of string: \" + s);\n }\n c = s.charAt(++i);\n if (c == '%') {\n buf[pos++] = '%'; // \"%%\" -> \"%\"\n break;\n } else if (i == size - 1) {\n throw new IllegalArgumentException(\"partial escape\"\n + \" sequence at end of string: \" + s);\n }\n c = decodeHexNibble(c);\n final char c2 = decodeHexNibble(s.charAt(++i));\n if (c == Character.MAX_VALUE || c2 == Character.MAX_VALUE) {\n throw new IllegalArgumentException(\n \"invalid escape sequence `%\" + s.charAt(i - 1)\n + s.charAt(i) + \"' at index \" + (i - 2)\n + \" of: \" + s);\n }\n c = (char) (c * 16 + c2);\n // Fall through.\n default:\n buf[pos++] = (byte) c;\n break;\n }\n }\n try {\n return new String(buf, 0, pos, charset.name());\n } catch (UnsupportedEncodingException e) {\n throw new IllegalArgumentException(\"unsupported encoding: \" + charset.name());\n }\n }\n\n /**\n * Helper to decode half of a hexadecimal number from a string.\n * @param c The ASCII character of the hexadecimal number to decode.\n * Must be in the range {@code [0-9a-fA-F]}.\n * @return The hexadecimal value represented in the ASCII character\n * given, or {@link Character#MAX_VALUE} if the character is invalid.\n */\n private static char decodeHexNibble(final char c) {\n if ('0' <= c && c <= '9') {\n return (char) (c - '0');\n } else if ('a' <= c && c <= 'f') {\n return (char) (c - 'a' + 10);\n } else if ('A' <= c && c <= 'F') {\n return (char) (c - 'A' + 10);\n } else {\n return Character.MAX_VALUE;\n }\n }\n}", "file_name": "QueryStringDecoder.java", "human_label": "Convert a hexadecimal number to binary and return its character type.", "level": "slib_runnable", "lineno": "408", "name": "decodeHexNibble", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[Character]\", \"vars\" : \"[MAX_VALUE]\" }", "package": "org.atmosphere.util", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636766f21a6d9265ec01767d", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.List;\\nimport java.util.Locale;\\nString EMPTY;\\nint INDEX_NOT_FOUND;\\nint PAD_LIMIT;\\nchar[] escapes;\\nStringUtils();\\nisNotEmpty(String str);\\nisBlank(String str);\\nisNotBlank(String str);\\ntrim(String str);\\ntrimToNull(String str);\\ntrimToEmpty(String str);\\nstrip(String str);\\nstripToNull(String str);\\nstripToEmpty(String str);\\nstrip(String str,String stripChars);\\nstripStart(String str,String stripChars);\\nstripEnd(String str,String stripChars);\\nstripAll(String[] strs);\\nstripAll(String[] strs,String stripChars);\\nequals(String str1,String str2);\\nequalsIgnoreCase(String str1,String str2);\\nindexOf(String str,char searchChar);\\nindexOf(String str,char searchChar,int startPos);\\nindexOf(String str,String searchStr);\\nordinalIndexOf(String str,String searchStr,int ordinal);\\nordinalIndexOf(String str,String searchStr,int ordinal,boolean lastIndex);\\nindexOf(String str,String searchStr,int startPos);\\nindexOfIgnoreCase(String str,String searchStr);\\nindexOfIgnoreCase(String str,String searchStr,int startPos);\\nlastIndexOf(String str,char searchChar);\\nlastIndexOf(String str,char searchChar,int startPos);\\nlastIndexOf(String str,String searchStr);\\nlastOrdinalIndexOf(String str,String searchStr,int ordinal);\\nlastIndexOf(String str,String searchStr,int startPos);\\nlastIndexOfIgnoreCase(String str,String searchStr);\\nlastIndexOfIgnoreCase(String str,String searchStr,int startPos);\\ncontains(String str,char searchChar);\\ncontains(String str,String searchStr);\\ncontainsIgnoreCase(String str,String searchStr);\\nindexOfAny(String str,char[] searchChars);\\nindexOfAny(String str,String searchChars);\\ncontainsAny(String str,char[] searchChars);\\ncontainsAny(String str,String searchChars);\\nindexOfAnyBut(String str,char[] searchChars);\\nindexOfAnyBut(String str,String searchChars);\\ncontainsOnly(String str,char[] valid);\\ncontainsOnly(String str,String validChars);\\ncontainsNone(String str,char[] searchChars);\\ncontainsNone(String str,String invalidChars);\\nindexOfAny(String str,String[] searchStrs);\\nlastIndexOfAny(String str,String[] searchStrs);\\nsubstring(String str,int start);\\nsubstring(String str,int start,int end);\\nleft(String str,int len);\\nright(String str,int len);\\nmid(String str,int pos,int len);\\nsubstringBefore(String str,String separator);\\nsubstringAfter(String str,String separator);\\nsubstringBeforeLast(String str,String separator);\\nsubstringAfterLast(String str,String separator);\\nsubstringBetween(String str,String tag);\\nsubstringBetween(String str,String open,String close);\\nsubstringsBetween(String str,String open,String close);\\nsplitKeep(String str,char separatorChar);\\nsplitKeep(String str,String separatorStr);\\nsplit(String str);\\nsplit(String str,char separatorChar);\\nsplit(String str,String separatorChars);\\nsplit(String str,String separatorChars,int max);\\nsplitByWholeSeparator(String str,String separator);\\nsplitByWholeSeparator(String str,String separator,int max);\\nsplitByWholeSeparatorPreserveAllTokens(String str,String separator);\\nsplitByWholeSeparatorPreserveAllTokens(String str,String separator,int max);\\nsplitByWholeSeparatorWorker(String str,String separator,int max,boolean preserveAllTokens);\\nsplitPreserveAllTokens(String str);\\nsplitPreserveAllTokens(String str,char separatorChar);\\nsplitWorker(String str,char separatorChar,boolean preserveAllTokens);\\nsplitPreserveAllTokens(String str,String separatorChars);\\nsplitPreserveAllTokens(String str,String separatorChars,int max);\\nsplitWorker(String str,String separatorChars,int max,boolean preserveAllTokens);\\nsplitByCharacterType(String str);\\nsplitByCharacterTypeCamelCase(String str);\\nsplitByCharacterType(String str,boolean camelCase);\\njoin(Object[] array);\\njoin(Object[] array,char separator);\\njoin(Object[] array,char separator,int startIndex,int endIndex);\\njoin(Object[] array,String separator);\\njoin(Object[] array,String separator,int startIndex,int endIndex);\\ndeleteWhitespace(String str);\\nremoveStart(String str,String remove);\\nremoveStartIgnoreCase(String str,String remove);\\nremoveEnd(String str,String remove);\\nremoveEndIgnoreCase(String str,String remove);\\nremove(String str,String remove);\\nremove(String str,char remove);\\nreplaceOnce(String text,String searchString,String replacement);\\nreplace(String text,String searchString,String replacement);\\nreplace(String text,String searchString,String replacement,int max);\\nreplaceEach(String text,String[] searchList,String[] replacementList);\\nreplaceEachRepeatedly(String text,String[] searchList,String[] replacementList);\\nreplaceEach(String text,String[] searchList,String[] replacementList,boolean repeat,int timeToLive);\\nreplaceChars(String str,char searchChar,char replaceChar);\\nreplaceChars(String str,String searchChars,String replaceChars);\\noverlay(String str,String overlay,int start,int end);\\nchomp(String str);\\nchomp(String str,String separator);\\nchop(String str);\\nrepeat(char character,int repeat);\\nrepeat(String str,int repeat);\\nrepeat(String str,String separator,int repeat);\\npadding(int repeat,char padChar);\\nrightPad(String str,int size);\\nrightPad(String str,int size,char padChar);\\nrightPad(String str,int size,String padStr);\\nleftPad(String str,int size);\\nleftPad(String str,int size,char padChar);\\nleftPad(String str,int size,String padStr);\\nlength(String str);\\ncenter(String str,int size);\\ncenter(String str,int size,char padChar);\\ncenter(String str,int size,String padStr);\\nupperCase(String str);\\nupperCase(String str,Locale locale);\\nlowerCase(String str);\\nlowerCase(String str,Locale locale);\\ncapitalize(String str);\\nuncapitalize(String str);\\nswapCase(String str);\\ncountMatches(String str,String sub);\\nisAlpha(String str);\\nisAlphaSpace(String str);\\nisAlphanumeric(String str);\\nisAlphanumericSpace(String str);\\nisAsciiPrintable(String str);\\nisNumeric(String str);\\nisNumericSpace(String str);\\nisWhitespace(String str);\\nisAllLowerCase(String str);\\nisAllUpperCase(String str);\\ndefaultString(String str);\\ndefaultString(String str,String defaultStr);\\ndefaultIfBlank(String str,String defaultStr);\\ndefaultIfEmpty(String str,String defaultStr);\\nreverse(String str);\\nreverseDelimited(String str,char separatorChar);\\nabbreviate(String str,int maxWidth);\\nabbreviate(String str,int offset,int maxWidth);\\nabbreviateMiddle(String str,String middle,int length);\\ndifference(String str1,String str2);\\nindexOfDifference(String str1,String str2);\\nindexOfDifference(String[] strs);\\ngetCommonPrefix(String[] strs);\\ngetLevenshteinDistance(String s,String t);\\nstartsWith(String str,String prefix);\\nstartsWithIgnoreCase(String str,String prefix);\\nstartsWith(String str,String prefix,boolean ignoreCase);\\nstartsWithAny(String string,String[] searchStrings);\\nendsWith(String str,String suffix);\\nendsWithIgnoreCase(String str,String suffix);\\nendsWith(String str,String suffix,boolean ignoreCase);\\nnormalizeSpace(String str);\\nendsWithAny(String string,String[] searchStrings);\\nfirstCharToUpperCase(String value);\\nfirstCharToLowerCase(String value);\\nequalsBlankIgnoreCase(String str1,String str2);\\nquote(String input);\\nquote(Appendable buffer,String input);\\ntoString(Object object);\\nisEmpty(String str);\\n\", \"repo_level\" : \"\" }", "class_name": "StringUtils", "code": "public static String toString(Object object){\n return (object == null) ? null : object.toString();\n}\n", "docstring": "/** \n * Object to String ,when null object then null else return toString(); \n */\n", "end_lineno": "6136", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Locale;\n\n/**\n *

Operations on {@link String} that are\n * null safe.

\n *\n *
    \n *
  • IsEmpty/IsBlank\n * - checks if a String contains text
  • \n *
  • Trim/Strip\n * - removes leading and trailing whitespace
  • \n *
  • Equals\n * - compares two strings null-safe
  • \n *
  • startsWith\n * - check if a String starts with a prefix null-safe
  • \n *
  • endsWith\n * - check if a String ends with a suffix null-safe
  • \n *
  • IndexOf/LastIndexOf/Contains\n * - null-safe index-of checks\n *
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut\n * - index-of any of a set of Strings
  • \n *
  • ContainsOnly/ContainsNone/ContainsAny\n * - does String contains only/none/any of these characters
  • \n *
  • Substring/Left/Right/Mid\n * - null-safe substring extractions
  • \n *
  • SubstringBefore/SubstringAfter/SubstringBetween\n * - substring extraction relative to other strings
  • \n *
  • Split/Join\n * - splits a String into an array of substrings and vice versa
  • \n *
  • Remove/Delete\n * - removes part of a String
  • \n *
  • Replace/Overlay\n * - Searches a String and replaces one String with another
  • \n *
  • Chomp/Chop\n * - removes the last part of a String
  • \n *
  • LeftPad/RightPad/Center/Repeat\n * - pads a String
  • \n *
  • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize\n * - changes the case of a String
  • \n *
  • CountMatches\n * - counts the number of occurrences of one String in another
  • \n *
  • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable\n * - checks the characters in a String
  • \n *
  • DefaultString\n * - protects against a null input String
  • \n *
  • Reverse/ReverseDelimited\n * - reverses a String
  • \n *
  • Abbreviate\n * - abbreviates a string using ellipsis
  • \n *
  • Difference\n * - compares Strings and reports on their differences
  • \n *
  • LevensteinDistance\n * - the number of changes needed to change one String into another
  • \n *
\n *\n *

The StringUtils class defines certain words related to\n * String handling.

\n *\n *
    \n *
  • null - null
  • \n *
  • empty - a zero-length string (\"\")
  • \n *
  • space - the space character (' ', char 32)
  • \n *
  • whitespace - the characters defined by {@link Character#isWhitespace(char)}
  • \n *
  • trim - the characters <= 32 as in {@link String#trim()}
  • \n *
\n *\n *

StringUtils handles null input Strings quietly.\n * That is to say that a null input will return null.\n * Where a boolean or int is being returned\n * details vary by method.

\n *\n *

A side effect of the null handling is that a\n * NullPointerException should be considered a bug in\n * StringUtils (except for deprecated methods).

\n *\n *

Methods in this class give sample code to explain their operation.\n * The symbol * is used to indicate any input including null.

\n *\n *

#ThreadSafe#

\n * @see String\n * @author Apache Software Foundation\n * @author Apache Jakarta Turbine\n * @author Jon S. Stevens\n * @author Daniel L. Rall\n * @author Greg Coladonato\n * @author Ed Korthof\n * @author Rand McNeely\n * @author Fredrik Westermarck\n * @author Holger Krauth\n * @author Alexander Day Chaffee\n * @author Henning P. Schmiedehausen\n * @author Arun Mammen Thomas\n * @author Gary Gregory\n * @author Phil Steitz\n * @author Al Chou\n * @author Michael Davey\n * @author Reuben Sivan\n * @author Chris Hyzer\n * @author Scott Johnson\n * @since 1.0\n * @version $Id: StringUtils.java 1058365 2011-01-13 00:04:49Z niallp $\n */\n//@Immutable\npublic class StringUtils {\n // Performance testing notes (JDK 1.4, Jul03, scolebourne)\n // Whitespace:\n // Character.isWhitespace() is faster than WHITESPACE.indexOf()\n // where WHITESPACE is a string of all whitespace characters\n //\n // Character access:\n // String.charAt(n) versus toCharArray(), then array[n]\n // String.charAt(n) is about 15% worse for a 10K string\n // They are about equal for a length 50 string\n // String.charAt(n) is about 4 times better for a length 3 string\n // String.charAt(n) is best bet overall\n //\n // Append:\n // String.concat about twice as fast as StringBuffer.append\n // (not sure who tested this)\n /**\n * The empty String \"\".\n * @since 2.0\n */\n public static final String EMPTY = \"\";\n /**\n * Represents a failed index search.\n * @since 2.1\n */\n public static final int INDEX_NOT_FOUND = -1;\n /**\n *

The maximum size to which the padding constant(s) can expand.

\n */\n private static final int PAD_LIMIT = 8192;\n\n /**\n *

StringUtils instances should NOT be constructed in\n * standard programming. Instead, the class should be used as\n * StringUtils.trim(\" foo \");.

\n *\n *

This constructor is public to permit tools that require a JavaBean\n * instance to operate.

\n */\n public StringUtils() {\n super();\n }\n // Empty checks\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if a String is empty (\"\") or null.

\n *\n *
\n     * StringUtils.isEmpty(null)      = true\n     * StringUtils.isEmpty(\"\")        = true\n     * StringUtils.isEmpty(\" \")       = false\n     * StringUtils.isEmpty(\"bob\")     = false\n     * StringUtils.isEmpty(\"  bob  \") = false\n     * 
\n *\n *

NOTE: This method changed in Lang version 2.0.\n * It no longer trims the String.\n * That functionality is available in isBlank().

\n *\n * @param str the String to check, may be null\n * @return true if the String is empty or null\n */\n public static boolean isEmpty(final String str) {\n return str == null || str.length() == 0;\n }\n\n /**\n *

Checks if a String is not empty (\"\") and not null.

\n *\n *
\n     * StringUtils.isNotEmpty(null)      = false\n     * StringUtils.isNotEmpty(\"\")        = false\n     * StringUtils.isNotEmpty(\" \")       = true\n     * StringUtils.isNotEmpty(\"bob\")     = true\n     * StringUtils.isNotEmpty(\"  bob  \") = true\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if the String is not empty and not null\n */\n public static boolean isNotEmpty(final String str) {\n return !StringUtils.isEmpty(str);\n }\n\n /**\n *

Checks if a String is whitespace, empty (\"\") or null.

\n *\n *
\n     * StringUtils.isBlank(null)      = true\n     * StringUtils.isBlank(\"\")        = true\n     * StringUtils.isBlank(\" \")       = true\n     * StringUtils.isBlank(\"bob\")     = false\n     * StringUtils.isBlank(\"  bob  \") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if the String is null, empty or whitespace\n * @since 2.0\n */\n public static boolean isBlank(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return true;\n }\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i)) == false) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if a String is not empty (\"\"), not null and not whitespace only.

\n *\n *
\n     * StringUtils.isNotBlank(null)      = false\n     * StringUtils.isNotBlank(\"\")        = false\n     * StringUtils.isNotBlank(\" \")       = false\n     * StringUtils.isNotBlank(\"bob\")     = true\n     * StringUtils.isNotBlank(\"  bob  \") = true\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if the String is\n * not empty and not null and not whitespace\n * @since 2.0\n */\n public static boolean isNotBlank(final String str) {\n return !StringUtils.isBlank(str);\n }\n // Trim\n //-----------------------------------------------------------------------\n\n /**\n *

Removes control characters (char <= 32) from both\n * ends of this String, handling null by returning\n * null.

\n *\n *

The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #strip(String)}.

\n *\n *

To trim your choice of characters, use the\n * {@link #strip(String, String)} methods.

\n *\n *
\n     * StringUtils.trim(null)          = null\n     * StringUtils.trim(\"\")            = \"\"\n     * StringUtils.trim(\"     \")       = \"\"\n     * StringUtils.trim(\"abc\")         = \"abc\"\n     * StringUtils.trim(\"    abc    \") = \"abc\"\n     * 
\n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed string, null if null String input\n */\n public static String trim(final String str) {\n return str == null ? null : str.trim();\n }\n\n /**\n *

Removes control characters (char <= 32) from both\n * ends of this String returning null if the String is\n * empty (\"\") after the trim or if it is null.\n *\n *

The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #stripToNull(String)}.

\n *\n *
\n     * StringUtils.trimToNull(null)          = null\n     * StringUtils.trimToNull(\"\")            = null\n     * StringUtils.trimToNull(\"     \")       = null\n     * StringUtils.trimToNull(\"abc\")         = \"abc\"\n     * StringUtils.trimToNull(\"    abc    \") = \"abc\"\n     * 
\n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed String,\n * null if only chars <= 32, empty or null String input\n * @since 2.0\n */\n public static String trimToNull(final String str) {\n String ts = StringUtils.trim(str);\n return StringUtils.isEmpty(ts) ? null : ts;\n }\n\n /**\n *

Removes control characters (char <= 32) from both\n * ends of this String returning an empty String (\"\") if the String\n * is empty (\"\") after the trim or if it is null.\n *\n *

The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #stripToEmpty(String)}.

\n *\n *
\n     * StringUtils.trimToEmpty(null)          = \"\"\n     * StringUtils.trimToEmpty(\"\")            = \"\"\n     * StringUtils.trimToEmpty(\"     \")       = \"\"\n     * StringUtils.trimToEmpty(\"abc\")         = \"abc\"\n     * StringUtils.trimToEmpty(\"    abc    \") = \"abc\"\n     * 
\n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed String, or an empty String if null input\n * @since 2.0\n */\n public static String trimToEmpty(final String str) {\n return str == null ? StringUtils.EMPTY : str.trim();\n }\n // Stripping\n //-----------------------------------------------------------------------\n\n /**\n *

Strips whitespace from the start and end of a String.

\n *\n *

This is similar to {@link #trim(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.strip(null)     = null\n     * StringUtils.strip(\"\")       = \"\"\n     * StringUtils.strip(\"   \")    = \"\"\n     * StringUtils.strip(\"abc\")    = \"abc\"\n     * StringUtils.strip(\"  abc\")  = \"abc\"\n     * StringUtils.strip(\"abc  \")  = \"abc\"\n     * StringUtils.strip(\" abc \")  = \"abc\"\n     * StringUtils.strip(\" ab c \") = \"ab c\"\n     * 
\n *\n * @param str the String to remove whitespace from, may be null\n * @return the stripped String, null if null String input\n */\n public static String strip(final String str) {\n return StringUtils.strip(str, null);\n }\n\n /**\n *

Strips whitespace from the start and end of a String returning\n * null if the String is empty (\"\") after the strip.

\n *\n *

This is similar to {@link #trimToNull(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripToNull(null)     = null\n     * StringUtils.stripToNull(\"\")       = null\n     * StringUtils.stripToNull(\"   \")    = null\n     * StringUtils.stripToNull(\"abc\")    = \"abc\"\n     * StringUtils.stripToNull(\"  abc\")  = \"abc\"\n     * StringUtils.stripToNull(\"abc  \")  = \"abc\"\n     * StringUtils.stripToNull(\" abc \")  = \"abc\"\n     * StringUtils.stripToNull(\" ab c \") = \"ab c\"\n     * 
\n *\n * @param str the String to be stripped, may be null\n * @return the stripped String,\n * null if whitespace, empty or null String input\n * @since 2.0\n */\n public static String stripToNull(String str) {\n if (str == null) {\n return null;\n }\n str = StringUtils.strip(str, null);\n return str.length() == 0 ? null : str;\n }\n\n /**\n *

Strips whitespace from the start and end of a String returning\n * an empty String if null input.

\n *\n *

This is similar to {@link #trimToEmpty(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripToEmpty(null)     = \"\"\n     * StringUtils.stripToEmpty(\"\")       = \"\"\n     * StringUtils.stripToEmpty(\"   \")    = \"\"\n     * StringUtils.stripToEmpty(\"abc\")    = \"abc\"\n     * StringUtils.stripToEmpty(\"  abc\")  = \"abc\"\n     * StringUtils.stripToEmpty(\"abc  \")  = \"abc\"\n     * StringUtils.stripToEmpty(\" abc \")  = \"abc\"\n     * StringUtils.stripToEmpty(\" ab c \") = \"ab c\"\n     * 
\n *\n * @param str the String to be stripped, may be null\n * @return the trimmed String, or an empty String if null input\n * @since 2.0\n */\n public static String stripToEmpty(final String str) {\n return str == null ? StringUtils.EMPTY : StringUtils.strip(str, null);\n }\n\n /**\n *

Strips any of a set of characters from the start and end of a String.\n * This is similar to {@link String#trim()} but allows the characters\n * to be stripped to be controlled.

\n *\n *

A null input String returns null.\n * An empty string (\"\") input returns the empty string.

\n *\n *

If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.\n * Alternatively use {@link #strip(String)}.

\n *\n *
\n     * StringUtils.strip(null, *)          = null\n     * StringUtils.strip(\"\", *)            = \"\"\n     * StringUtils.strip(\"abc\", null)      = \"abc\"\n     * StringUtils.strip(\"  abc\", null)    = \"abc\"\n     * StringUtils.strip(\"abc  \", null)    = \"abc\"\n     * StringUtils.strip(\" abc \", null)    = \"abc\"\n     * StringUtils.strip(\"  abcyx\", \"xyz\") = \"  abc\"\n     * 
\n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String strip(String str, final String stripChars) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n str = StringUtils.stripStart(str, stripChars);\n return StringUtils.stripEnd(str, stripChars);\n }\n\n /**\n *

Strips any of a set of characters from the start of a String.

\n *\n *

A null input String returns null.\n * An empty string (\"\") input returns the empty string.

\n *\n *

If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripStart(null, *)          = null\n     * StringUtils.stripStart(\"\", *)            = \"\"\n     * StringUtils.stripStart(\"abc\", \"\")        = \"abc\"\n     * StringUtils.stripStart(\"abc\", null)      = \"abc\"\n     * StringUtils.stripStart(\"  abc\", null)    = \"abc\"\n     * StringUtils.stripStart(\"abc  \", null)    = \"abc  \"\n     * StringUtils.stripStart(\" abc \", null)    = \"abc \"\n     * StringUtils.stripStart(\"yxabc  \", \"xyz\") = \"abc  \"\n     * 
\n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String stripStart(final String str, final String stripChars) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n int start = 0;\n if (stripChars == null) {\n while (start != strLen && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n } else if (stripChars.length() == 0) {\n return str;\n } else {\n while (start != strLen && stripChars.indexOf(str.charAt(start)) != StringUtils.INDEX_NOT_FOUND) {\n start++;\n }\n }\n return str.substring(start);\n }\n\n /**\n *

Strips any of a set of characters from the end of a String.

\n *\n *

A null input String returns null.\n * An empty string (\"\") input returns the empty string.

\n *\n *

If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripEnd(null, *)          = null\n     * StringUtils.stripEnd(\"\", *)            = \"\"\n     * StringUtils.stripEnd(\"abc\", \"\")        = \"abc\"\n     * StringUtils.stripEnd(\"abc\", null)      = \"abc\"\n     * StringUtils.stripEnd(\"  abc\", null)    = \"  abc\"\n     * StringUtils.stripEnd(\"abc  \", null)    = \"abc\"\n     * StringUtils.stripEnd(\" abc \", null)    = \" abc\"\n     * StringUtils.stripEnd(\"  abcyx\", \"xyz\") = \"  abc\"\n     * StringUtils.stripEnd(\"120.00\", \".0\")   = \"12\"\n     * 
\n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the set of characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String stripEnd(final String str, final String stripChars) {\n int end;\n if (str == null || (end = str.length()) == 0) {\n return str;\n }\n if (stripChars == null) {\n while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n } else if (stripChars.length() == 0) {\n return str;\n } else {\n while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != StringUtils.INDEX_NOT_FOUND) {\n end--;\n }\n }\n return str.substring(0, end);\n }\n // StripAll\n //-----------------------------------------------------------------------\n\n /**\n *

Strips whitespace from the start and end of every String in an array.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

A new array is returned each time, except for length zero.\n * A null array will return null.\n * An empty array will return itself.\n * A null array entry will be ignored.

\n *\n *
\n     * StringUtils.stripAll(null)             = null\n     * StringUtils.stripAll([])               = []\n     * StringUtils.stripAll([\"abc\", \"  abc\"]) = [\"abc\", \"abc\"]\n     * StringUtils.stripAll([\"abc  \", null])  = [\"abc\", null]\n     * 
\n *\n * @param strs the array to remove whitespace from, may be null\n * @return the stripped Strings, null if null array input\n */\n public static String[] stripAll(final String[] strs) {\n return StringUtils.stripAll(strs, null);\n }\n\n /**\n *

Strips any of a set of characters from the start and end of every\n * String in an array.

\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

A new array is returned each time, except for length zero.\n * A null array will return null.\n * An empty array will return itself.\n * A null array entry will be ignored.\n * A null stripChars will strip whitespace as defined by\n * {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.stripAll(null, *)                = null\n     * StringUtils.stripAll([], *)                  = []\n     * StringUtils.stripAll([\"abc\", \"  abc\"], null) = [\"abc\", \"abc\"]\n     * StringUtils.stripAll([\"abc  \", null], null)  = [\"abc\", null]\n     * StringUtils.stripAll([\"abc  \", null], \"yz\")  = [\"abc  \", null]\n     * StringUtils.stripAll([\"yabcz\", null], \"yz\")  = [\"abc\", null]\n     * 
\n *\n * @param strs the array to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped Strings, null if null array input\n */\n public static String[] stripAll(final String[] strs, final String stripChars) {\n int strsLen;\n if (strs == null || (strsLen = strs.length) == 0) {\n return strs;\n }\n String[] newArr = new String[strsLen];\n for (int i = 0; i < strsLen; i++) {\n newArr[i] = StringUtils.strip(strs[i], stripChars);\n }\n return newArr;\n }\n // Equals\n //-----------------------------------------------------------------------\n\n /**\n *

Compares two Strings, returning true if they are equal.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

\n *\n *
\n     * StringUtils.equals(null, null)   = true\n     * StringUtils.equals(null, \"abc\")  = false\n     * StringUtils.equals(\"abc\", null)  = false\n     * StringUtils.equals(\"abc\", \"abc\") = true\n     * StringUtils.equals(\"abc\", \"ABC\") = false\n     * 
\n *\n * @see String#equals(Object)\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return true if the Strings are equal, case sensitive, or\n * both null\n */\n public static boolean equals(final String str1, final String str2) {\n return str1 == null ? str2 == null : str1.equals(str2);\n }\n\n /**\n *

Compares two Strings, returning true if they are equal ignoring\n * the case.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered equal. Comparison is case insensitive.

\n *\n *
\n     * StringUtils.equalsIgnoreCase(null, null)   = true\n     * StringUtils.equalsIgnoreCase(null, \"abc\")  = false\n     * StringUtils.equalsIgnoreCase(\"abc\", null)  = false\n     * StringUtils.equalsIgnoreCase(\"abc\", \"abc\") = true\n     * StringUtils.equalsIgnoreCase(\"abc\", \"ABC\") = true\n     * 
\n *\n * @see String#equalsIgnoreCase(String)\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return true if the Strings are equal, case insensitive, or\n * both null\n */\n public static boolean equalsIgnoreCase(final String str1, final String str2) {\n return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);\n }\n // IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(int)}.

\n *\n *

A null or empty (\"\") String will return INDEX_NOT_FOUND (-1).

\n *\n *
\n     * StringUtils.indexOf(null, *)         = -1\n     * StringUtils.indexOf(\"\", *)           = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'a') = 0\n     * StringUtils.indexOf(\"aabaabaa\", 'b') = 2\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return the first index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchChar);\n }\n\n /**\n *

Finds the first index within a String from a start position,\n * handling null.\n * This method uses {@link String#indexOf(int, int)}.

\n *\n *

A null or empty (\"\") String will return (INDEX_NOT_FOUND) -1.\n * A negative start position is treated as zero.\n * A start position greater than the string length returns -1.

\n *\n *
\n     * StringUtils.indexOf(null, *, *)          = -1\n     * StringUtils.indexOf(\"\", *, *)            = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 0)  = 2\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 3)  = 5\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 9)  = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'b', -1) = 2\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final char searchChar, final int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchChar, startPos);\n }\n\n /**\n *

Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n *
\n     * StringUtils.indexOf(null, *)          = -1\n     * StringUtils.indexOf(*, null)          = -1\n     * StringUtils.indexOf(\"\", \"\")           = 0\n     * StringUtils.indexOf(\"\", *)            = -1 (except when * = \"\")\n     * StringUtils.indexOf(\"aabaabaa\", \"a\")  = 0\n     * StringUtils.indexOf(\"aabaabaa\", \"b\")  = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"ab\") = 1\n     * StringUtils.indexOf(\"aabaabaa\", \"\")   = 0\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr);\n }\n\n /**\n *

Finds the n-th index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n *
\n     * StringUtils.ordinalIndexOf(null, *, *)          = -1\n     * StringUtils.ordinalIndexOf(*, null, *)          = -1\n     * StringUtils.ordinalIndexOf(\"\", \"\", *)           = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"a\", 1)  = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"a\", 2)  = 1\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"b\", 1)  = 2\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"b\", 2)  = 5\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"ab\", 1) = 1\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"ab\", 2) = 4\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"\", 1)   = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"\", 2)   = 0\n     * 
\n *\n *

Note that 'head(String str, int n)' may be implemented as:

\n *\n *
\n     *   str.substring(0, lastOrdinalIndexOf(str, \"\\n\", n))\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th searchStr to find\n * @return the n-th index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n * @since 2.1\n */\n public static int ordinalIndexOf(final String str, final String searchStr, final int ordinal) {\n return StringUtils.ordinalIndexOf(str, searchStr, ordinal, false);\n }\n\n /**\n *

Finds the n-th index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th searchStr to find\n * @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf()\n * @return the n-th index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n */\n // Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int)\n private static int ordinalIndexOf(final String str, final String searchStr, final int ordinal, final boolean lastIndex) {\n if (str == null || searchStr == null || ordinal <= 0) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return lastIndex ? str.length() : 0;\n }\n int found = 0;\n int index = lastIndex ? str.length() : StringUtils.INDEX_NOT_FOUND;\n do {\n if (lastIndex) {\n index = str.lastIndexOf(searchStr, index - 1);\n } else {\n index = str.indexOf(searchStr, index + 1);\n }\n if (index < 0) {\n return index;\n }\n found++;\n } while (found < ordinal);\n return index;\n }\n\n /**\n *

Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(String, int)}.

\n *\n *

A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

\n *\n *
\n     * StringUtils.indexOf(null, *, *)          = -1\n     * StringUtils.indexOf(*, null, *)          = -1\n     * StringUtils.indexOf(\"\", \"\", 0)           = 0\n     * StringUtils.indexOf(\"\", *, 0)            = -1 (except when * = \"\")\n     * StringUtils.indexOf(\"aabaabaa\", \"a\", 0)  = 0\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 0)  = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"ab\", 0) = 1\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 3)  = 5\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 9)  = -1\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", -1) = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"\", 2)   = 2\n     * StringUtils.indexOf(\"abc\", \"\", 9)        = 3\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final String searchStr, final int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n // JDK1.2/JDK1.3 have a bug, when startPos > str.length for \"\", hence\n if (searchStr.length() == 0 && startPos >= str.length()) {\n return str.length();\n }\n return str.indexOf(searchStr, startPos);\n }\n\n /**\n *

Case in-sensitive find of the first index within a String.

\n *\n *

A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

\n *\n *
\n     * StringUtils.indexOfIgnoreCase(null, *)          = -1\n     * StringUtils.indexOfIgnoreCase(*, null)          = -1\n     * StringUtils.indexOfIgnoreCase(\"\", \"\")           = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"a\")  = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"b\")  = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"ab\") = 1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int indexOfIgnoreCase(final String str, final String searchStr) {\n return StringUtils.indexOfIgnoreCase(str, searchStr, 0);\n }\n\n /**\n *

Case in-sensitive find of the first index within a String\n * from the specified position.

\n *\n *

A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

\n *\n *
\n     * StringUtils.indexOfIgnoreCase(null, *, *)          = -1\n     * StringUtils.indexOfIgnoreCase(*, null, *)          = -1\n     * StringUtils.indexOfIgnoreCase(\"\", \"\", 0)           = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"A\", 0)  = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 0)  = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"AB\", 0) = 1\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 3)  = 5\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 9)  = -1\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", -1) = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"\", 2)   = 2\n     * StringUtils.indexOfIgnoreCase(\"abc\", \"\", 9)        = 3\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int indexOfIgnoreCase(final String str, final String searchStr, int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (startPos < 0) {\n startPos = 0;\n }\n int endLimit = str.length() - searchStr.length() + 1;\n if (startPos > endLimit) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return startPos;\n }\n for (int i = startPos; i < endLimit; i++) {\n if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {\n return i;\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // LastIndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

Finds the last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(int)}.

\n *\n *

A null or empty (\"\") String will return -1.

\n *\n *
\n     * StringUtils.lastIndexOf(null, *)         = -1\n     * StringUtils.lastIndexOf(\"\", *)           = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'a') = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b') = 5\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return the last index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar);\n }\n\n /**\n *

Finds the last index within a String from a start position,\n * handling null.\n * This method uses {@link String#lastIndexOf(int, int)}.

\n *\n *

A null or empty (\"\") String will return -1.\n * A negative start position returns -1.\n * A start position greater than the string length searches the whole string.

\n *\n *
\n     * StringUtils.lastIndexOf(null, *, *)          = -1\n     * StringUtils.lastIndexOf(\"\", *,  *)           = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 8)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 4)  = 2\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 0)  = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 9)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', -1) = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'a', 0)  = 0\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @param startPos the start position\n * @return the last index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final char searchChar, final int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar, startPos);\n }\n\n /**\n *

Finds the last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n *
\n     * StringUtils.lastIndexOf(null, *)          = -1\n     * StringUtils.lastIndexOf(*, null)          = -1\n     * StringUtils.lastIndexOf(\"\", \"\")           = 0\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\")  = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\")  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"ab\") = 4\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"\")   = 8\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the last index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr);\n }\n\n /**\n *

Finds the n-th last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String)}.

\n *\n *

A null String will return -1.

\n *\n *
\n     * StringUtils.lastOrdinalIndexOf(null, *, *)          = -1\n     * StringUtils.lastOrdinalIndexOf(*, null, *)          = -1\n     * StringUtils.lastOrdinalIndexOf(\"\", \"\", *)           = 0\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"a\", 1)  = 7\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"a\", 2)  = 6\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"b\", 1)  = 5\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"b\", 2)  = 2\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"ab\", 1) = 4\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"ab\", 2) = 1\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"\", 1)   = 8\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"\", 2)   = 8\n     * 
\n *\n *

Note that 'tail(String str, int n)' may be implemented as:

\n *\n *
\n     *   str.substring(lastOrdinalIndexOf(str, \"\\n\", n) + 1)\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th last searchStr to find\n * @return the n-th last index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n * @since 2.5\n */\n public static int lastOrdinalIndexOf(final String str, final String searchStr, final int ordinal) {\n return StringUtils.ordinalIndexOf(str, searchStr, ordinal, true);\n }\n\n /**\n *

Finds the first index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String, int)}.

\n *\n *

A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

\n *\n *
\n     * StringUtils.lastIndexOf(null, *, *)          = -1\n     * StringUtils.lastIndexOf(*, null, *)          = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\", 8)  = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 8)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"ab\", 8) = 4\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 9)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", -1) = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\", 0)  = 0\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 0)  = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final String searchStr, final int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr, startPos);\n }\n\n /**\n *

Case in-sensitive find of the last index within a String.

\n *\n *

A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

\n *\n *
\n     * StringUtils.lastIndexOfIgnoreCase(null, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(*, null)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\")  = 7\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\")  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"AB\") = 4\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int lastIndexOfIgnoreCase(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return StringUtils.lastIndexOfIgnoreCase(str, searchStr, str.length());\n }\n\n /**\n *

Case in-sensitive find of the last index within a String\n * from the specified position.

\n *\n *

A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

\n *\n *
\n     * StringUtils.lastIndexOfIgnoreCase(null, *, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(*, null, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\", 8)  = 7\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 8)  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"AB\", 8) = 4\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 9)  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", -1) = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\", 0)  = 0\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 0)  = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int lastIndexOfIgnoreCase(final String str, final String searchStr, int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (startPos > str.length() - searchStr.length()) {\n startPos = str.length() - searchStr.length();\n }\n if (startPos < 0) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return startPos;\n }\n for (int i = startPos; i >= 0; i--) {\n if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {\n return i;\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // Contains\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if String contains a search character, handling null.\n * This method uses {@link String#indexOf(int)}.

\n *\n *

A null or empty (\"\") String will return false.

\n *\n *
\n     * StringUtils.contains(null, *)    = false\n     * StringUtils.contains(\"\", *)      = false\n     * StringUtils.contains(\"abc\", 'a') = true\n     * StringUtils.contains(\"abc\", 'z') = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return true if the String contains the search character,\n * false if not or null string input\n * @since 2.0\n */\n public static boolean contains(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return false;\n }\n return str.indexOf(searchChar) >= 0;\n }\n\n /**\n *

Checks if String contains a search String, handling null.\n * This method uses {@link String#indexOf(String)}.

\n *\n *

A null String will return false.

\n *\n *
\n     * StringUtils.contains(null, *)     = false\n     * StringUtils.contains(*, null)     = false\n     * StringUtils.contains(\"\", \"\")      = true\n     * StringUtils.contains(\"abc\", \"\")   = true\n     * StringUtils.contains(\"abc\", \"a\")  = true\n     * StringUtils.contains(\"abc\", \"z\")  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return true if the String contains the search String,\n * false if not or null string input\n * @since 2.0\n */\n public static boolean contains(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n return str.contains(searchStr);\n }\n\n /**\n *

Checks if String contains a search String irrespective of case,\n * handling null. Case-insensitivity is defined as by\n * {@link String#equalsIgnoreCase(String)}.\n *\n *

A null String will return false.

\n *\n *
\n     * StringUtils.contains(null, *) = false\n     * StringUtils.contains(*, null) = false\n     * StringUtils.contains(\"\", \"\") = true\n     * StringUtils.contains(\"abc\", \"\") = true\n     * StringUtils.contains(\"abc\", \"a\") = true\n     * StringUtils.contains(\"abc\", \"z\") = false\n     * StringUtils.contains(\"abc\", \"A\") = true\n     * StringUtils.contains(\"abc\", \"Z\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return true if the String contains the search String irrespective of\n * case or false if not or null string input\n */\n public static boolean containsIgnoreCase(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n int len = searchStr.length();\n int max = str.length() - len;\n for (int i = 0; i <= max; i++) {\n if (str.regionMatches(true, i, searchStr, 0, len)) {\n return true;\n }\n }\n return false;\n }\n // IndexOfAny chars\n //-----------------------------------------------------------------------\n\n /**\n *

Search a String to find the first index of any\n * character in the given set of characters.

\n *\n *

A null String will return -1.\n * A null or zero length search array will return -1.

\n *\n *
\n     * StringUtils.indexOfAny(null, *)                = -1\n     * StringUtils.indexOfAny(\"\", *)                  = -1\n     * StringUtils.indexOfAny(*, null)                = -1\n     * StringUtils.indexOfAny(*, [])                  = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\",['z','a']) = 0\n     * StringUtils.indexOfAny(\"zzabyycdxx\",['b','y']) = 3\n     * StringUtils.indexOfAny(\"aba\", ['z'])           = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAny(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) {\n // ch is a supplementary character\n if (searchChars[j + 1] == str.charAt(i + 1)) {\n return i;\n }\n } else {\n return i;\n }\n }\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Search a String to find the first index of any\n * character in the given set of characters.

\n *\n *

A null String will return -1.\n * A null search string will return -1.

\n *\n *
\n     * StringUtils.indexOfAny(null, *)            = -1\n     * StringUtils.indexOfAny(\"\", *)              = -1\n     * StringUtils.indexOfAny(*, null)            = -1\n     * StringUtils.indexOfAny(*, \"\")              = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", \"za\") = 0\n     * StringUtils.indexOfAny(\"zzabyycdxx\", \"by\") = 3\n     * StringUtils.indexOfAny(\"aba\",\"z\")          = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAny(final String str, final String searchChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return StringUtils.indexOfAny(str, searchChars.toCharArray());\n }\n // ContainsAny\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if the String contains any character in the given\n * set of characters.

\n *\n *

A null String will return false.\n * A null or zero length search array will return false.

\n *\n *
\n     * StringUtils.containsAny(null, *)                = false\n     * StringUtils.containsAny(\"\", *)                  = false\n     * StringUtils.containsAny(*, null)                = false\n     * StringUtils.containsAny(*, [])                  = false\n     * StringUtils.containsAny(\"zzabyycdxx\",['z','a']) = true\n     * StringUtils.containsAny(\"zzabyycdxx\",['b','y']) = true\n     * StringUtils.containsAny(\"aba\", ['z'])           = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the true if any of the chars are found,\n * false if no match or null input\n * @since 2.4\n */\n public static boolean containsAny(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return false;\n }\n int csLength = str.length();\n int searchLength = searchChars.length;\n int csLast = csLength - 1;\n int searchLast = searchLength - 1;\n for (int i = 0; i < csLength; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLength; j++) {\n if (searchChars[j] == ch) {\n if (CharUtils.isHighSurrogate(ch)) {\n if (j == searchLast) {\n // missing low surrogate, fine, like String.indexOf(String)\n return true;\n }\n if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) {\n return true;\n }\n } else {\n // ch is in the Basic Multilingual Plane\n return true;\n }\n }\n }\n }\n return false;\n }\n\n /**\n *

\n * Checks if the String contains any character in the given set of characters.\n *

\n *\n *

\n * A null String will return false. A null search string will return\n * false.\n *

\n *\n *
\n     * StringUtils.containsAny(null, *)            = false\n     * StringUtils.containsAny(\"\", *)              = false\n     * StringUtils.containsAny(*, null)            = false\n     * StringUtils.containsAny(*, \"\")              = false\n     * StringUtils.containsAny(\"zzabyycdxx\", \"za\") = true\n     * StringUtils.containsAny(\"zzabyycdxx\", \"by\") = true\n     * StringUtils.containsAny(\"aba\",\"z\")          = false\n     * 
\n *\n * @param str\n * the String to check, may be null\n * @param searchChars\n * the chars to search for, may be null\n * @return the true if any of the chars are found, false if no match or null input\n * @since 2.4\n */\n public static boolean containsAny(final String str, final String searchChars) {\n if (searchChars == null) {\n return false;\n }\n return StringUtils.containsAny(str, searchChars.toCharArray());\n }\n // IndexOfAnyBut chars\n //-----------------------------------------------------------------------\n\n /**\n *

Search a String to find the first index of any\n * character not in the given set of characters.

\n *\n *

A null String will return -1.\n * A null or zero length search array will return -1.

\n *\n *
\n     * StringUtils.indexOfAnyBut(null, *)                              = -1\n     * StringUtils.indexOfAnyBut(\"\", *)                                = -1\n     * StringUtils.indexOfAnyBut(*, null)                              = -1\n     * StringUtils.indexOfAnyBut(*, [])                                = -1\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", new char[] {'z', 'a'} ) = 3\n     * StringUtils.indexOfAnyBut(\"aba\", new char[] {'z'} )             = 0\n     * StringUtils.indexOfAnyBut(\"aba\", new char[] {'a', 'b'} )        = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAnyBut(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n outer:\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) {\n if (searchChars[j + 1] == str.charAt(i + 1)) {\n continue outer;\n }\n } else {\n continue outer;\n }\n }\n }\n return i;\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Search a String to find the first index of any\n * character not in the given set of characters.

\n *\n *

A null String will return -1.\n * A null or empty search string will return -1.

\n *\n *
\n     * StringUtils.indexOfAnyBut(null, *)            = -1\n     * StringUtils.indexOfAnyBut(\"\", *)              = -1\n     * StringUtils.indexOfAnyBut(*, null)            = -1\n     * StringUtils.indexOfAnyBut(*, \"\")              = -1\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", \"za\") = 3\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", \"\")   = -1\n     * StringUtils.indexOfAnyBut(\"aba\",\"ab\")         = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAnyBut(final String str, final String searchChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n char ch = str.charAt(i);\n boolean chFound = searchChars.indexOf(ch) >= 0;\n if (i + 1 < strLen && CharUtils.isHighSurrogate(ch)) {\n char ch2 = str.charAt(i + 1);\n if (chFound && searchChars.indexOf(ch2) < 0) {\n return i;\n }\n } else {\n if (!chFound) {\n return i;\n }\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // ContainsOnly\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if the String contains only certain characters.

\n *\n *

A null String will return false.\n * A null valid character array will return false.\n * An empty String (length()=0) always returns true.

\n *\n *
\n     * StringUtils.containsOnly(null, *)       = false\n     * StringUtils.containsOnly(*, null)       = false\n     * StringUtils.containsOnly(\"\", *)         = true\n     * StringUtils.containsOnly(\"ab\", '')      = false\n     * StringUtils.containsOnly(\"abab\", 'abc') = true\n     * StringUtils.containsOnly(\"ab1\", 'abc')  = false\n     * StringUtils.containsOnly(\"abz\", 'abc')  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param valid an array of valid chars, may be null\n * @return true if it only contains valid chars and is non-null\n */\n public static boolean containsOnly(final String str, final char[] valid) {\n // All these pre-checks are to maintain API with an older version\n if (valid == null || str == null) {\n return false;\n }\n if (str.length() == 0) {\n return true;\n }\n if (valid.length == 0) {\n return false;\n }\n return StringUtils.indexOfAnyBut(str, valid) == StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Checks if the String contains only certain characters.

\n *\n *

A null String will return false.\n * A null valid character String will return false.\n * An empty String (length()=0) always returns true.

\n *\n *
\n     * StringUtils.containsOnly(null, *)       = false\n     * StringUtils.containsOnly(*, null)       = false\n     * StringUtils.containsOnly(\"\", *)         = true\n     * StringUtils.containsOnly(\"ab\", \"\")      = false\n     * StringUtils.containsOnly(\"abab\", \"abc\") = true\n     * StringUtils.containsOnly(\"ab1\", \"abc\")  = false\n     * StringUtils.containsOnly(\"abz\", \"abc\")  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param validChars a String of valid chars, may be null\n * @return true if it only contains valid chars and is non-null\n * @since 2.0\n */\n public static boolean containsOnly(final String str, final String validChars) {\n if (str == null || validChars == null) {\n return false;\n }\n return StringUtils.containsOnly(str, validChars.toCharArray());\n }\n // ContainsNone\n //-----------------------------------------------------------------------\n\n /**\n *

Checks that the String does not contain certain characters.

\n *\n *

A null String will return true.\n * A null invalid character array will return true.\n * An empty String (length()=0) always returns true.

\n *\n *
\n     * StringUtils.containsNone(null, *)       = true\n     * StringUtils.containsNone(*, null)       = true\n     * StringUtils.containsNone(\"\", *)         = true\n     * StringUtils.containsNone(\"ab\", '')      = true\n     * StringUtils.containsNone(\"abab\", 'xyz') = true\n     * StringUtils.containsNone(\"ab1\", 'xyz')  = true\n     * StringUtils.containsNone(\"abz\", 'xyz')  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchChars an array of invalid chars, may be null\n * @return true if it contains none of the invalid chars, or is null\n * @since 2.0\n */\n public static boolean containsNone(final String str, final char[] searchChars) {\n if (str == null || searchChars == null) {\n return true;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (CharUtils.isHighSurrogate(ch)) {\n if (j == searchLast) {\n // missing low surrogate, fine, like String.indexOf(String)\n return false;\n }\n if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) {\n return false;\n }\n } else {\n // ch is in the Basic Multilingual Plane\n return false;\n }\n }\n }\n }\n return true;\n }\n\n /**\n *

Checks that the String does not contain certain characters.

\n *\n *

A null String will return true.\n * A null invalid character array will return true.\n * An empty String (\"\") always returns true.

\n *\n *
\n     * StringUtils.containsNone(null, *)       = true\n     * StringUtils.containsNone(*, null)       = true\n     * StringUtils.containsNone(\"\", *)         = true\n     * StringUtils.containsNone(\"ab\", \"\")      = true\n     * StringUtils.containsNone(\"abab\", \"xyz\") = true\n     * StringUtils.containsNone(\"ab1\", \"xyz\")  = true\n     * StringUtils.containsNone(\"abz\", \"xyz\")  = false\n     * 
\n *\n * @param str the String to check, may be null\n * @param invalidChars a String of invalid chars, may be null\n * @return true if it contains none of the invalid chars, or is null\n * @since 2.0\n */\n public static boolean containsNone(final String str, final String invalidChars) {\n if (str == null || invalidChars == null) {\n return true;\n }\n return StringUtils.containsNone(str, invalidChars.toCharArray());\n }\n // IndexOfAny strings\n //-----------------------------------------------------------------------\n\n /**\n *

Find the first index of any of a set of potential substrings.

\n *\n *

A null String will return -1.\n * A null or zero length search array will return -1.\n * A null search array entry will be ignored, but a search\n * array containing \"\" will return 0 if str is not\n * null. This method uses {@link String#indexOf(String)}.

\n *\n *
\n     * StringUtils.indexOfAny(null, *)                     = -1\n     * StringUtils.indexOfAny(*, null)                     = -1\n     * StringUtils.indexOfAny(*, [])                       = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"ab\",\"cd\"])   = 2\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"cd\",\"ab\"])   = 2\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"])   = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"zab\",\"aby\"]) = 1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"\"])          = 0\n     * StringUtils.indexOfAny(\"\", [\"\"])                    = 0\n     * StringUtils.indexOfAny(\"\", [\"a\"])                   = -1\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStrs the Strings to search for, may be null\n * @return the first index of any of the searchStrs in str, -1 if no match\n */\n public static int indexOfAny(final String str, final String[] searchStrs) {\n if (str == null || searchStrs == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int sz = searchStrs.length;\n // String's can't have a MAX_VALUEth index.\n int ret = Integer.MAX_VALUE;\n int tmp = 0;\n for (int i = 0; i < sz; i++) {\n String search = searchStrs[i];\n if (search == null) {\n continue;\n }\n tmp = str.indexOf(search);\n if (tmp == StringUtils.INDEX_NOT_FOUND) {\n continue;\n }\n if (tmp < ret) {\n ret = tmp;\n }\n }\n return ret == Integer.MAX_VALUE ? StringUtils.INDEX_NOT_FOUND : ret;\n }\n\n /**\n *

Find the latest index of any of a set of potential substrings.

\n *\n *

A null String will return -1.\n * A null search array will return -1.\n * A null or zero length search array entry will be ignored,\n * but a search array containing \"\" will return the length of str\n * if str is not null. This method uses {@link String#indexOf(String)}

\n *\n *
\n     * StringUtils.lastIndexOfAny(null, *)                   = -1\n     * StringUtils.lastIndexOfAny(*, null)                   = -1\n     * StringUtils.lastIndexOfAny(*, [])                     = -1\n     * StringUtils.lastIndexOfAny(*, [null])                 = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"ab\",\"cd\"]) = 6\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"cd\",\"ab\"]) = 6\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"]) = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"]) = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"\"])   = 10\n     * 
\n *\n * @param str the String to check, may be null\n * @param searchStrs the Strings to search for, may be null\n * @return the last index of any of the Strings, -1 if no match\n */\n public static int lastIndexOfAny(final String str, final String[] searchStrs) {\n if (str == null || searchStrs == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int sz = searchStrs.length;\n int ret = StringUtils.INDEX_NOT_FOUND;\n int tmp = 0;\n for (int i = 0; i < sz; i++) {\n String search = searchStrs[i];\n if (search == null) {\n continue;\n }\n tmp = str.lastIndexOf(search);\n if (tmp > ret) {\n ret = tmp;\n }\n }\n return ret;\n }\n // Substring\n //-----------------------------------------------------------------------\n\n /**\n *

Gets a substring from the specified String avoiding exceptions.

\n *\n *

A negative start position can be used to start n\n * characters from the end of the String.

\n *\n *

A null String will return null.\n * An empty (\"\") String will return \"\".

\n *\n *
\n     * StringUtils.substring(null, *)   = null\n     * StringUtils.substring(\"\", *)     = \"\"\n     * StringUtils.substring(\"abc\", 0)  = \"abc\"\n     * StringUtils.substring(\"abc\", 2)  = \"c\"\n     * StringUtils.substring(\"abc\", 4)  = \"\"\n     * StringUtils.substring(\"abc\", -2) = \"bc\"\n     * StringUtils.substring(\"abc\", -4) = \"abc\"\n     * 
\n *\n * @param str the String to get the substring from, may be null\n * @param start the position to start from, negative means\n * count back from the end of the String by this many characters\n * @return substring from start position, null if null String input\n */\n public static String substring(final String str, int start) {\n if (str == null) {\n return null;\n }\n // handle negatives, which means last n characters\n if (start < 0) {\n start = str.length() + start; // remember start is negative\n }\n if (start < 0) {\n start = 0;\n }\n if (start > str.length()) {\n return StringUtils.EMPTY;\n }\n return str.substring(start);\n }\n\n /**\n *

Gets a substring from the specified String avoiding exceptions.

\n *\n *

A negative start position can be used to start/end n\n * characters from the end of the String.

\n *\n *

The returned substring starts with the character in the start\n * position and ends before the end position. All position counting is\n * zero-based -- i.e., to start at the beginning of the string use\n * start = 0. Negative start and end positions can be used to\n * specify offsets relative to the end of the String.

\n *\n *

If start is not strictly to the left of end, \"\"\n * is returned.

\n *\n *
\n     * StringUtils.substring(null, *, *)    = null\n     * StringUtils.substring(\"\", * ,  *)    = \"\";\n     * StringUtils.substring(\"abc\", 0, 2)   = \"ab\"\n     * StringUtils.substring(\"abc\", 2, 0)   = \"\"\n     * StringUtils.substring(\"abc\", 2, 4)   = \"c\"\n     * StringUtils.substring(\"abc\", 4, 6)   = \"\"\n     * StringUtils.substring(\"abc\", 2, 2)   = \"\"\n     * StringUtils.substring(\"abc\", -2, -1) = \"b\"\n     * StringUtils.substring(\"abc\", -4, 2)  = \"ab\"\n     * 
\n *\n * @param str the String to get the substring from, may be null\n * @param start the position to start from, negative means\n * count back from the end of the String by this many characters\n * @param end the position to end at (exclusive), negative means\n * count back from the end of the String by this many characters\n * @return substring from start position to end positon,\n * null if null String input\n */\n public static String substring(final String str, int start, int end) {\n if (str == null) {\n return null;\n }\n // handle negatives\n if (end < 0) {\n end = str.length() + end; // remember end is negative\n }\n if (start < 0) {\n start = str.length() + start; // remember start is negative\n }\n // check length next\n if (end > str.length()) {\n end = str.length();\n }\n // if start is greater than end, return \"\"\n if (start > end) {\n return StringUtils.EMPTY;\n }\n if (start < 0) {\n start = 0;\n }\n if (end < 0) {\n end = 0;\n }\n return str.substring(start, end);\n }\n // Left/Right/Mid\n //-----------------------------------------------------------------------\n\n /**\n *

Gets the leftmost len characters of a String.

\n *\n *

If len characters are not available, or the\n * String is null, the String will be returned without\n * an exception. An empty String is returned if len is negative.

\n *\n *
\n     * StringUtils.left(null, *)    = null\n     * StringUtils.left(*, -ve)     = \"\"\n     * StringUtils.left(\"\", *)      = \"\"\n     * StringUtils.left(\"abc\", 0)   = \"\"\n     * StringUtils.left(\"abc\", 2)   = \"ab\"\n     * StringUtils.left(\"abc\", 4)   = \"abc\"\n     * 
\n *\n * @param str the String to get the leftmost characters from, may be null\n * @param len the length of the required String\n * @return the leftmost characters, null if null String input\n */\n public static String left(final String str, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0) {\n return StringUtils.EMPTY;\n }\n if (str.length() <= len) {\n return str;\n }\n return str.substring(0, len);\n }\n\n /**\n *

Gets the rightmost len characters of a String.

\n *\n *

If len characters are not available, or the String\n * is null, the String will be returned without an\n * an exception. An empty String is returned if len is negative.

\n *\n *
\n     * StringUtils.right(null, *)    = null\n     * StringUtils.right(*, -ve)     = \"\"\n     * StringUtils.right(\"\", *)      = \"\"\n     * StringUtils.right(\"abc\", 0)   = \"\"\n     * StringUtils.right(\"abc\", 2)   = \"bc\"\n     * StringUtils.right(\"abc\", 4)   = \"abc\"\n     * 
\n *\n * @param str the String to get the rightmost characters from, may be null\n * @param len the length of the required String\n * @return the rightmost characters, null if null String input\n */\n public static String right(final String str, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0) {\n return StringUtils.EMPTY;\n }\n if (str.length() <= len) {\n return str;\n }\n return str.substring(str.length() - len);\n }\n\n /**\n *

Gets len characters from the middle of a String.

\n *\n *

If len characters are not available, the remainder\n * of the String will be returned without an exception. If the\n * String is null, null will be returned.\n * An empty String is returned if len is negative or exceeds the\n * length of str.

\n *\n *
\n     * StringUtils.mid(null, *, *)    = null\n     * StringUtils.mid(*, *, -ve)     = \"\"\n     * StringUtils.mid(\"\", 0, *)      = \"\"\n     * StringUtils.mid(\"abc\", 0, 2)   = \"ab\"\n     * StringUtils.mid(\"abc\", 0, 4)   = \"abc\"\n     * StringUtils.mid(\"abc\", 2, 4)   = \"c\"\n     * StringUtils.mid(\"abc\", 4, 2)   = \"\"\n     * StringUtils.mid(\"abc\", -2, 2)  = \"ab\"\n     * 
\n *\n * @param str the String to get the characters from, may be null\n * @param pos the position to start from, negative treated as zero\n * @param len the length of the required String\n * @return the middle characters, null if null String input\n */\n public static String mid(final String str, int pos, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0 || pos > str.length()) {\n return StringUtils.EMPTY;\n }\n if (pos < 0) {\n pos = 0;\n }\n if (str.length() <= pos + len) {\n return str.substring(pos);\n }\n return str.substring(pos, pos + len);\n }\n // SubStringAfter/SubStringBefore\n //-----------------------------------------------------------------------\n\n /**\n *

Gets the substring before the first occurrence of a separator.\n * The separator is not returned.

\n *\n *

A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * A null separator will return the input string.

\n *\n *

If nothing is found, the string input is returned.

\n *\n *
\n     * StringUtils.substringBefore(null, *)      = null\n     * StringUtils.substringBefore(\"\", *)        = \"\"\n     * StringUtils.substringBefore(\"abc\", \"a\")   = \"\"\n     * StringUtils.substringBefore(\"abcba\", \"b\") = \"a\"\n     * StringUtils.substringBefore(\"abc\", \"c\")   = \"ab\"\n     * StringUtils.substringBefore(\"abc\", \"d\")   = \"abc\"\n     * StringUtils.substringBefore(\"abc\", \"\")    = \"\"\n     * StringUtils.substringBefore(\"abc\", null)  = \"abc\"\n     * 
\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring before the first occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringBefore(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || separator == null) {\n return str;\n }\n if (separator.length() == 0) {\n return StringUtils.EMPTY;\n }\n int pos = str.indexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n return str.substring(0, pos);\n }\n\n /**\n *

Gets the substring after the first occurrence of a separator.\n * The separator is not returned.

\n *\n *

A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * A null separator will return the empty string if the\n * input string is not null.

\n *\n *

If nothing is found, the empty string is returned.

\n *\n *
\n     * StringUtils.substringAfter(null, *)      = null\n     * StringUtils.substringAfter(\"\", *)        = \"\"\n     * StringUtils.substringAfter(*, null)      = \"\"\n     * StringUtils.substringAfter(\"abc\", \"a\")   = \"bc\"\n     * StringUtils.substringAfter(\"abcba\", \"b\") = \"cba\"\n     * StringUtils.substringAfter(\"abc\", \"c\")   = \"\"\n     * StringUtils.substringAfter(\"abc\", \"d\")   = \"\"\n     * StringUtils.substringAfter(\"abc\", \"\")    = \"abc\"\n     * 
\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring after the first occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringAfter(final String str, final String separator) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (separator == null) {\n return StringUtils.EMPTY;\n }\n int pos = str.indexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return StringUtils.EMPTY;\n }\n return str.substring(pos + separator.length());\n }\n\n /**\n *

Gets the substring before the last occurrence of a separator.\n * The separator is not returned.

\n *\n *

A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * An empty or null separator will return the input string.

\n *\n *

If nothing is found, the string input is returned.

\n *\n *
\n     * StringUtils.substringBeforeLast(null, *)      = null\n     * StringUtils.substringBeforeLast(\"\", *)        = \"\"\n     * StringUtils.substringBeforeLast(\"abcba\", \"b\") = \"abc\"\n     * StringUtils.substringBeforeLast(\"abc\", \"c\")   = \"ab\"\n     * StringUtils.substringBeforeLast(\"a\", \"a\")     = \"\"\n     * StringUtils.substringBeforeLast(\"a\", \"z\")     = \"a\"\n     * StringUtils.substringBeforeLast(\"a\", null)    = \"a\"\n     * StringUtils.substringBeforeLast(\"a\", \"\")      = \"a\"\n     * 
\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring before the last occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringBeforeLast(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(separator)) {\n return str;\n }\n int pos = str.lastIndexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n return str.substring(0, pos);\n }\n\n /**\n *

Gets the substring after the last occurrence of a separator.\n * The separator is not returned.

\n *\n *

A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * An empty or null separator will return the empty string if\n * the input string is not null.

\n *\n *

If nothing is found, the empty string is returned.

\n *\n *
\n     * StringUtils.substringAfterLast(null, *)      = null\n     * StringUtils.substringAfterLast(\"\", *)        = \"\"\n     * StringUtils.substringAfterLast(*, \"\")        = \"\"\n     * StringUtils.substringAfterLast(*, null)      = \"\"\n     * StringUtils.substringAfterLast(\"abc\", \"a\")   = \"bc\"\n     * StringUtils.substringAfterLast(\"abcba\", \"b\") = \"a\"\n     * StringUtils.substringAfterLast(\"abc\", \"c\")   = \"\"\n     * StringUtils.substringAfterLast(\"a\", \"a\")     = \"\"\n     * StringUtils.substringAfterLast(\"a\", \"z\")     = \"\"\n     * 
\n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring after the last occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringAfterLast(final String str, final String separator) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (StringUtils.isEmpty(separator)) {\n return StringUtils.EMPTY;\n }\n int pos = str.lastIndexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND || pos == str.length() - separator.length()) {\n return StringUtils.EMPTY;\n }\n return str.substring(pos + separator.length());\n }\n // Substring between\n //-----------------------------------------------------------------------\n\n /**\n *

Gets the String that is nested in between two instances of the\n * same String.

\n *\n *

A null input String returns null.\n * A null tag returns null.

\n *\n *
\n     * StringUtils.substringBetween(null, *)            = null\n     * StringUtils.substringBetween(\"\", \"\")             = \"\"\n     * StringUtils.substringBetween(\"\", \"tag\")          = null\n     * StringUtils.substringBetween(\"tagabctag\", null)  = null\n     * StringUtils.substringBetween(\"tagabctag\", \"\")    = \"\"\n     * StringUtils.substringBetween(\"tagabctag\", \"tag\") = \"abc\"\n     * 
\n *\n * @param str the String containing the substring, may be null\n * @param tag the String before and after the substring, may be null\n * @return the substring, null if no match\n * @since 2.0\n */\n public static String substringBetween(final String str, final String tag) {\n return StringUtils.substringBetween(str, tag, tag);\n }\n\n /**\n *

Gets the String that is nested in between two Strings.\n * Only the first match is returned.

\n *\n *

A null input String returns null.\n * A null open/close returns null (no match).\n * An empty (\"\") open and close returns an empty string.

\n *\n *
\n     * StringUtils.substringBetween(\"wx[b]yz\", \"[\", \"]\") = \"b\"\n     * StringUtils.substringBetween(null, *, *)          = null\n     * StringUtils.substringBetween(*, null, *)          = null\n     * StringUtils.substringBetween(*, *, null)          = null\n     * StringUtils.substringBetween(\"\", \"\", \"\")          = \"\"\n     * StringUtils.substringBetween(\"\", \"\", \"]\")         = null\n     * StringUtils.substringBetween(\"\", \"[\", \"]\")        = null\n     * StringUtils.substringBetween(\"yabcz\", \"\", \"\")     = \"\"\n     * StringUtils.substringBetween(\"yabcz\", \"y\", \"z\")   = \"abc\"\n     * StringUtils.substringBetween(\"yabczyabcz\", \"y\", \"z\")   = \"abc\"\n     * 
\n *\n * @param str the String containing the substring, may be null\n * @param open the String before the substring, may be null\n * @param close the String after the substring, may be null\n * @return the substring, null if no match\n * @since 2.0\n */\n public static String substringBetween(final String str, final String open, final String close) {\n if (str == null || open == null || close == null) {\n return null;\n }\n int start = str.indexOf(open);\n if (start != StringUtils.INDEX_NOT_FOUND) {\n int end = str.indexOf(close, start + open.length());\n if (end != StringUtils.INDEX_NOT_FOUND) {\n return str.substring(start + open.length(), end);\n }\n }\n return null;\n }\n\n /**\n *

Searches a String for substrings delimited by a start and end tag,\n * returning all matching substrings in an array.

\n *\n *

A null input String returns null.\n * A null open/close returns null (no match).\n * An empty (\"\") open/close returns null (no match).

\n *\n *
\n     * StringUtils.substringsBetween(\"[a][b][c]\", \"[\", \"]\") = [\"a\",\"b\",\"c\"]\n     * StringUtils.substringsBetween(null, *, *)            = null\n     * StringUtils.substringsBetween(*, null, *)            = null\n     * StringUtils.substringsBetween(*, *, null)            = null\n     * StringUtils.substringsBetween(\"\", \"[\", \"]\")          = []\n     * 
\n *\n * @param str the String containing the substrings, null returns null, empty returns empty\n * @param open the String identifying the start of the substring, empty returns null\n * @param close the String identifying the end of the substring, empty returns null\n * @return a String Array of substrings, or null if no match\n * @since 2.3\n */\n public static String[] substringsBetween(final String str, final String open, final String close) {\n if (str == null || StringUtils.isEmpty(open) || StringUtils.isEmpty(close)) {\n return null;\n }\n int strLen = str.length();\n if (strLen == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n int closeLen = close.length();\n int openLen = open.length();\n List list = new ArrayList();\n int pos = 0;\n while (pos < strLen - closeLen) {\n int start = str.indexOf(open, pos);\n if (start < 0) {\n break;\n }\n start += openLen;\n int end = str.indexOf(close, start);\n if (end < 0) {\n break;\n }\n list.add(str.substring(start, end));\n pos = end + closeLen;\n }\n if (list.isEmpty()) {\n return null;\n }\n return list.toArray(new String[list.size()]);\n }\n // Splitting\n //-----------------------------------------------------------------------\n\n /**\n *

Splits the provided text into an array, using whitespace as the separator. but keep separator.

\n *\n *
\n     * StringUtils.splitKeep(null)          = null\n     * StringUtils.splitKeep(\"\")            = []\n     * StringUtils.splitKeep(\"a b c\", \" \")  = [\"a\", \" \", \"b\", \" \", \"c\"]\n     * StringUtils.splitKeep(\"abc def\", \" \")= [\"abc\", \" \", \"def\"]\n     * StringUtils.splitKeep(\" abc \", \" \")  = [\" \", \"abc\", \" \"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] splitKeep(String str, char separatorChar) {\n return splitKeep(str, String.valueOf(separatorChar));\n }\n\n /**\n *

Splits the provided text into an array, using whitespace as the separator. but keep separator.

\n *\n *
\n     * StringUtils.splitKeep(null)          = null\n     * StringUtils.splitKeep(\"\")            = []\n     * StringUtils.splitKeep(\"a b c\", \" \")  = [\"a\", \" \", \"b\", \" \", \"c\"]\n     * StringUtils.splitKeep(\"abc def\", \" \")= [\"abc\", \" \", \"def\"]\n     * StringUtils.splitKeep(\" abc \", \" \")  = [\" \", \"abc\", \" \"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] splitKeep(String str, String separatorStr) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n int CHARS = separatorStr.length();\n if (CHARS == 0) {\n throw new IllegalArgumentException(\"chars must be > 0\");\n }\n int lastIndex = 0;\n ArrayList dat = new ArrayList<>();\n while (true) {\n int lookIndex = str.indexOf(separatorStr, lastIndex);\n if (lookIndex == -1) {\n String substring = str.substring(lastIndex);\n if (substring.length() > 0) {\n dat.add(substring);\n }\n break;\n } else {\n if (lastIndex != lookIndex) {\n String term = str.substring(lastIndex, lookIndex);\n dat.add(term);\n }\n dat.add(separatorStr);\n lastIndex = lookIndex + CHARS;\n }\n }\n return dat.toArray(new String[0]);\n }\n\n /**\n *

Splits the provided text into an array, using whitespace as the\n * separator.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.split(null)       = null\n     * StringUtils.split(\"\")         = []\n     * StringUtils.split(\"abc def\")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\") = [\"abc\", \"def\"]\n     * StringUtils.split(\" abc \")    = [\"abc\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str) {\n return StringUtils.split(str, null, -1);\n }\n\n /**\n *

Splits the provided text into an array, separator specified.\n * This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"a.b.c\", '.')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.split(\"a..b.c\", '.')   = [\"a\", \"b\", \"c\"]\n     * StringUtils.split(\"a:b:c\", '.')    = [\"a:b:c\"]\n     * StringUtils.split(\"a b c\", ' ')    = [\"a\", \"b\", \"c\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChar the character used as the delimiter\n * @return an array of parsed Strings, null if null String input\n * @since 2.0\n */\n public static String[] split(final String str, final char separatorChar) {\n return StringUtils.splitWorker(str, separatorChar, false);\n }\n\n /**\n *

Splits the provided text into an array, separators specified.\n * This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *
\n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"abc def\", null) = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc def\", \" \")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\", \" \") = [\"abc\", \"def\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\") = [\"ab\", \"cd\", \"ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str, final String separatorChars) {\n return StringUtils.splitWorker(str, separatorChars, -1, false);\n }\n\n /**\n *

Splits the provided text into an array with a maximum length,\n * separators specified.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *

If more than max delimited substrings are found, the last\n * returned string includes all characters after the first max - 1\n * returned strings (including separator characters).

\n *\n *
\n     * StringUtils.split(null, *, *)            = null\n     * StringUtils.split(\"\", *, *)              = []\n     * StringUtils.split(\"ab de fg\", null, 0)   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab   de fg\", null, 0) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\", 0)    = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\", 2)    = [\"ab\", \"cd:ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str, final String separatorChars, final int max) {\n return StringUtils.splitWorker(str, separatorChars, max, false);\n }\n\n /**\n *

Splits the provided text into an array, separator string specified.

\n *\n *

The separator(s) will not be included in the returned String array.\n * Adjacent separators are treated as one separator.

\n *\n *

A null input String returns null.\n * A null separator splits on whitespace.

\n *\n *
\n     * StringUtils.splitByWholeSeparator(null, *)               = null\n     * StringUtils.splitByWholeSeparator(\"\", *)                 = []\n     * StringUtils.splitByWholeSeparator(\"ab de fg\", null)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab   de fg\", null)    = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab:cd:ef\", \":\")       = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\") = [\"ab\", \"cd\", \"ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String was input\n */\n public static String[] splitByWholeSeparator(final String str, final String separator) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, -1, false);\n }\n\n /**\n *

Splits the provided text into an array, separator string specified.\n * Returns a maximum of max substrings.

\n *\n *

The separator(s) will not be included in the returned String array.\n * Adjacent separators are treated as one separator.

\n *\n *

A null input String returns null.\n * A null separator splits on whitespace.

\n *\n *
\n     * StringUtils.splitByWholeSeparator(null, *, *)               = null\n     * StringUtils.splitByWholeSeparator(\"\", *, *)                 = []\n     * StringUtils.splitByWholeSeparator(\"ab de fg\", null, 0)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab   de fg\", null, 0)    = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab:cd:ef\", \":\", 2)       = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\", 5) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\", 2) = [\"ab\", \"cd-!-ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @return an array of parsed Strings, null if null String was input\n */\n public static String[] splitByWholeSeparator(final String str, final String separator, final int max) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, max, false);\n }\n\n /**\n *

Splits the provided text into an array, separator string specified.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separator splits on whitespace.

\n *\n *
\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *)               = null\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"\", *)                 = []\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab de fg\", null)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab   de fg\", null)    = [\"ab\", \"\", \"\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab:cd:ef\", \":\")       = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\") = [\"ab\", \"cd\", \"ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String was input\n * @since 2.4\n */\n public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, -1, true);\n }\n\n /**\n *

Splits the provided text into an array, separator string specified.\n * Returns a maximum of max substrings.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separator splits on whitespace.

\n *\n *
\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *)               = null\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"\", *, *)                 = []\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab de fg\", null, 0)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab   de fg\", null, 0)    = [\"ab\", \"\", \"\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab:cd:ef\", \":\", 2)       = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\", 5) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\", 2) = [\"ab\", \"cd-!-ef\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @return an array of parsed Strings, null if null String was input\n * @since 2.4\n */\n public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator, final int max) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, max, true);\n }\n\n /**\n * Performs the logic for the splitByWholeSeparatorPreserveAllTokens methods.\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n private static String[] splitByWholeSeparatorWorker(final String str, final String separator, final int max, final boolean preserveAllTokens) {\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n if (separator == null || StringUtils.EMPTY.equals(separator)) {\n // Split on whitespace.\n return StringUtils.splitWorker(str, null, max, preserveAllTokens);\n }\n int separatorLength = separator.length();\n ArrayList substrings = new ArrayList<>();\n int numberOfSubstrings = 0;\n int beg = 0;\n int end = 0;\n while (end < len) {\n end = str.indexOf(separator, beg);\n if (end > -1) {\n if (end > beg) {\n numberOfSubstrings += 1;\n if (numberOfSubstrings == max) {\n end = len;\n substrings.add(str.substring(beg));\n } else {\n // The following is OK, because String.substring( beg, end ) excludes\n // the character at the position 'end'.\n substrings.add(str.substring(beg, end));\n // Set the starting point for the next search.\n // The following is equivalent to beg = end + (separatorLength - 1) + 1,\n // which is the right calculation:\n beg = end + separatorLength;\n }\n } else {\n // We found a consecutive occurrence of the separator, so skip it.\n if (preserveAllTokens) {\n numberOfSubstrings += 1;\n if (numberOfSubstrings == max) {\n end = len;\n substrings.add(str.substring(beg));\n } else {\n substrings.add(StringUtils.EMPTY);\n }\n }\n beg = end + separatorLength;\n }\n } else {\n // String.substring( beg ) goes from 'beg' to the end of the String.\n substrings.add(str.substring(beg));\n end = len;\n }\n }\n return substrings.toArray(new String[0]);\n }\n // -----------------------------------------------------------------------\n\n /**\n *

Splits the provided text into an array, using whitespace as the\n * separator, preserving all tokens, including empty tokens created by\n * adjacent separators. This is an alternative to using StringTokenizer.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.splitPreserveAllTokens(null)       = null\n     * StringUtils.splitPreserveAllTokens(\"\")         = []\n     * StringUtils.splitPreserveAllTokens(\"abc def\")  = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc  def\") = [\"abc\", \"\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\" abc \")    = [\"\", \"abc\", \"\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str) {\n return StringUtils.splitWorker(str, null, -1, true);\n }\n\n /**\n *

Splits the provided text into an array, separator specified,\n * preserving all tokens, including empty tokens created by adjacent\n * separators. This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.splitPreserveAllTokens(null, *)         = null\n     * StringUtils.splitPreserveAllTokens(\"\", *)           = []\n     * StringUtils.splitPreserveAllTokens(\"a.b.c\", '.')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a..b.c\", '.')   = [\"a\", \"\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a:b:c\", '.')    = [\"a:b:c\"]\n     * StringUtils.splitPreserveAllTokens(\"a\\tb\\nc\", null) = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c\", ' ')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c \", ' ')   = [\"a\", \"b\", \"c\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c  \", ' ')   = [\"a\", \"b\", \"c\", \"\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\" a b c\", ' ')   = [\"\", a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"  a b c\", ' ')  = [\"\", \"\", a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\" a b c \", ' ')  = [\"\", a\", \"b\", \"c\", \"\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChar the character used as the delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final char separatorChar) {\n return StringUtils.splitWorker(str, separatorChar, true);\n }\n\n /**\n * Performs the logic for the split and\n * splitPreserveAllTokens methods that do not return a\n * maximum array length.\n *\n * @param str the String to parse, may be null\n * @param separatorChar the separate character\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n */\n private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n List list = new ArrayList<>();\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n while (i < len) {\n if (str.charAt(i) == separatorChar) {\n if (match || preserveAllTokens) {\n list.add(str.substring(start, i));\n match = false;\n lastMatch = true;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[0]);\n }\n\n /**\n *

Splits the provided text into an array, separators specified,\n * preserving all tokens, including empty tokens created by adjacent\n * separators. This is an alternative to using StringTokenizer.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *
\n     * StringUtils.splitPreserveAllTokens(null, *)           = null\n     * StringUtils.splitPreserveAllTokens(\"\", *)             = []\n     * StringUtils.splitPreserveAllTokens(\"abc def\", null)   = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc def\", \" \")    = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc  def\", \" \")   = [\"abc\", \"\", def\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\")   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef:\", \":\")  = [\"ab\", \"cd\", \"ef\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef::\", \":\") = [\"ab\", \"cd\", \"ef\", \"\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"ab::cd:ef\", \":\")  = [\"ab\", \"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\":cd:ef\", \":\")     = [\"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"::cd:ef\", \":\")    = [\"\", \"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\":cd:ef:\", \":\")    = [\"\", cd\", \"ef\", \"\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final String separatorChars) {\n return StringUtils.splitWorker(str, separatorChars, -1, true);\n }\n\n /**\n *

Splits the provided text into an array with a maximum length,\n * separators specified, preserving all tokens, including empty tokens\n * created by adjacent separators.

\n *\n *

The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * Adjacent separators are treated as one separator.

\n *\n *

A null input String returns null.\n * A null separatorChars splits on whitespace.

\n *\n *

If more than max delimited substrings are found, the last\n * returned string includes all characters after the first max - 1\n * returned strings (including separator characters).

\n *\n *
\n     * StringUtils.splitPreserveAllTokens(null, *, *)            = null\n     * StringUtils.splitPreserveAllTokens(\"\", *, *)              = []\n     * StringUtils.splitPreserveAllTokens(\"ab de fg\", null, 0)   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 0) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\", 0)    = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\", 2)    = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 2) = [\"ab\", \"  de fg\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 3) = [\"ab\", \"\", \" de fg\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 4) = [\"ab\", \"\", \"\", \"de fg\"]\n     * 
\n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) {\n return StringUtils.splitWorker(str, separatorChars, max, true);\n }\n\n /**\n * Performs the logic for the split and\n * splitPreserveAllTokens methods that return a maximum array\n * length.\n *\n * @param str the String to parse, may be null\n * @param separatorChars the separate character\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit.\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n */\n private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n // Direct code is quicker than StringTokenizer.\n // Also, StringTokenizer uses isSpace() not isWhitespace()\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n List list = new ArrayList<>();\n int sizePlus1 = 1;\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n if (separatorChars == null) {\n // Null separator means use whitespace\n while (i < len) {\n if (Character.isWhitespace(str.charAt(i))) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else if (separatorChars.length() == 1) {\n // Optimise 1 character case\n char sep = separatorChars.charAt(0);\n while (i < len) {\n if (str.charAt(i) == sep) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else {\n // standard case\n while (i < len) {\n if (separatorChars.indexOf(str.charAt(i)) >= 0) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[0]);\n }\n\n /**\n *

Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens.\n *

\n     * StringUtils.splitByCharacterType(null)         = null\n     * StringUtils.splitByCharacterType(\"\")           = []\n     * StringUtils.splitByCharacterType(\"ab de fg\")   = [\"ab\", \" \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterType(\"ab   de fg\") = [\"ab\", \"   \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterType(\"ab:cd:ef\")   = [\"ab\", \":\", \"cd\", \":\", \"ef\"]\n     * StringUtils.splitByCharacterType(\"number5\")    = [\"number\", \"5\"]\n     * StringUtils.splitByCharacterType(\"fooBar\")     = [\"foo\", \"B\", \"ar\"]\n     * StringUtils.splitByCharacterType(\"foo200Bar\")  = [\"foo\", \"200\", \"B\", \"ar\"]\n     * StringUtils.splitByCharacterType(\"ASFRules\")   = [\"ASFR\", \"ules\"]\n     * 
\n * @param str the String to split, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n public static String[] splitByCharacterType(final String str) {\n return StringUtils.splitByCharacterType(str, false);\n }\n\n /**\n *

Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens, with the\n * following exception: the character of type\n * Character.UPPERCASE_LETTER, if any, immediately\n * preceding a token of type Character.LOWERCASE_LETTER\n * will belong to the following token rather than to the preceding, if any,\n * Character.UPPERCASE_LETTER token.\n *

\n     * StringUtils.splitByCharacterTypeCamelCase(null)         = null\n     * StringUtils.splitByCharacterTypeCamelCase(\"\")           = []\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab de fg\")   = [\"ab\", \" \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab   de fg\") = [\"ab\", \"   \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab:cd:ef\")   = [\"ab\", \":\", \"cd\", \":\", \"ef\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"number5\")    = [\"number\", \"5\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"fooBar\")     = [\"foo\", \"Bar\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"foo200Bar\")  = [\"foo\", \"200\", \"Bar\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ASFRules\")   = [\"ASF\", \"Rules\"]\n     * 
\n * @param str the String to split, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n public static String[] splitByCharacterTypeCamelCase(final String str) {\n return StringUtils.splitByCharacterType(str, true);\n }\n\n /**\n *

Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens, with the\n * following exception: if camelCase is true,\n * the character of type Character.UPPERCASE_LETTER, if any,\n * immediately preceding a token of type Character.LOWERCASE_LETTER\n * will belong to the following token rather than to the preceding, if any,\n * Character.UPPERCASE_LETTER token.\n * @param str the String to split, may be null\n * @param camelCase whether to use so-called \"camel-case\" for letter types\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n private static String[] splitByCharacterType(final String str, final boolean camelCase) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n char[] c = str.toCharArray();\n List list = new ArrayList();\n int tokenStart = 0;\n int currentType = Character.getType(c[tokenStart]);\n for (int pos = tokenStart + 1; pos < c.length; pos++) {\n int type = Character.getType(c[pos]);\n if (type == currentType) {\n continue;\n }\n if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) {\n int newTokenStart = pos - 1;\n if (newTokenStart != tokenStart) {\n list.add(new String(c, tokenStart, newTokenStart - tokenStart));\n tokenStart = newTokenStart;\n }\n } else {\n list.add(new String(c, tokenStart, pos - tokenStart));\n tokenStart = pos;\n }\n currentType = type;\n }\n list.add(new String(c, tokenStart, c.length - tokenStart));\n return list.toArray(new String[0]);\n }\n // Joining\n //-----------------------------------------------------------------------\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No separator is added to the joined String.\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null)            = null\n     * StringUtils.join([])              = \"\"\n     * StringUtils.join([null])          = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"]) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"]) = \"a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array) {\n return StringUtils.join(array, null);\n }\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No delimiter is added before or after the list.\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null, *)               = null\n     * StringUtils.join([], *)                 = \"\"\n     * StringUtils.join([null], *)             = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], ';')  = \"a;b;c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ';')  = \";;a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array, final char separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array, separator, 0, array.length);\n }\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No delimiter is added before or after the list.\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null, *)               = null\n     * StringUtils.join([], *)                 = \"\"\n     * StringUtils.join([null], *)             = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], ';')  = \"a;b;c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ';')  = \";;a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use\n * @param startIndex the first index to start joining from. It is\n * an error to pass in an end index past the end of the array\n * @param endIndex the index to stop joining from (exclusive). It is\n * an error to pass in an end index past the end of the array\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) {\n if (array == null) {\n return null;\n }\n int bufSize = endIndex - startIndex;\n if (bufSize <= 0) {\n return StringUtils.EMPTY;\n }\n bufSize *= (array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1;\n StringBuilder buf = new StringBuilder(bufSize);\n for (int i = startIndex; i < endIndex; i++) {\n if (i > startIndex) {\n buf.append(separator);\n }\n if (array[i] != null) {\n buf.append(array[i]);\n }\n }\n return buf.toString();\n }\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No delimiter is added before or after the list.\n * A null separator is the same as an empty String (\"\").\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null, *)                = null\n     * StringUtils.join([], *)                  = \"\"\n     * StringUtils.join([null], *)              = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"--\")  = \"a--b--c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null)  = \"abc\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"\")    = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ',')   = \",,a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use, null treated as \"\"\n * @return the joined String, null if null array input\n */\n public static String join(final Object[] array, final String separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array, separator, 0, array.length);\n }\n\n /**\n *

Joins the elements of the provided array into a single String\n * containing the provided list of elements.

\n *\n *

No delimiter is added before or after the list.\n * A null separator is the same as an empty String (\"\").\n * Null objects or empty strings within the array are represented by\n * empty strings.

\n *\n *
\n     * StringUtils.join(null, *)                = null\n     * StringUtils.join([], *)                  = \"\"\n     * StringUtils.join([null], *)              = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"--\")  = \"a--b--c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null)  = \"abc\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"\")    = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ',')   = \",,a\"\n     * 
\n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use, null treated as \"\"\n * @param startIndex the first index to start joining from. It is\n * an error to pass in an end index past the end of the array\n * @param endIndex the index to stop joining from (exclusive). It is\n * an error to pass in an end index past the end of the array\n * @return the joined String, null if null array input\n */\n public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {\n if (array == null) {\n return null;\n }\n if (separator == null) {\n separator = StringUtils.EMPTY;\n }\n // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))\n // (Assuming that all Strings are roughly equally long)\n int bufSize = endIndex - startIndex;\n if (bufSize <= 0) {\n return StringUtils.EMPTY;\n }\n bufSize *= (array[startIndex] == null ? 16 : array[startIndex].toString().length()) + separator.length();\n StringBuilder buf = new StringBuilder(bufSize);\n for (int i = startIndex; i < endIndex; i++) {\n if (i > startIndex) {\n buf.append(separator);\n }\n if (array[i] != null) {\n buf.append(array[i]);\n }\n }\n return buf.toString();\n }\n // Delete\n //-----------------------------------------------------------------------\n\n /**\n *

Deletes all whitespaces from a String as defined by\n * {@link Character#isWhitespace(char)}.

\n *\n *
\n     * StringUtils.deleteWhitespace(null)         = null\n     * StringUtils.deleteWhitespace(\"\")           = \"\"\n     * StringUtils.deleteWhitespace(\"abc\")        = \"abc\"\n     * StringUtils.deleteWhitespace(\"   ab  c  \") = \"abc\"\n     * 
\n *\n * @param str the String to delete whitespace from, may be null\n * @return the String without whitespaces, null if null String input\n */\n public static String deleteWhitespace(final String str) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n int sz = str.length();\n char[] chs = new char[sz];\n int count = 0;\n for (int i = 0; i < sz; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n chs[count++] = str.charAt(i);\n }\n }\n if (count == sz) {\n return str;\n }\n return new String(chs, 0, count);\n }\n // Remove\n //-----------------------------------------------------------------------\n\n /**\n *

Removes a substring only if it is at the begining of a source string,\n * otherwise returns the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

\n *\n *
\n     * StringUtils.removeStart(null, *)      = null\n     * StringUtils.removeStart(\"\", *)        = \"\"\n     * StringUtils.removeStart(*, null)      = *\n     * StringUtils.removeStart(\"www.domain.com\", \"www.\")   = \"domain.com\"\n     * StringUtils.removeStart(\"domain.com\", \"www.\")       = \"domain.com\"\n     * StringUtils.removeStart(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeStart(\"abc\", \"\")    = \"abc\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String removeStart(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (str.startsWith(remove)) {\n return str.substring(remove.length());\n }\n return str;\n }\n\n /**\n *

Case insensitive removal of a substring if it is at the begining of a source string,\n * otherwise returns the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

\n *\n *
\n     * StringUtils.removeStartIgnoreCase(null, *)      = null\n     * StringUtils.removeStartIgnoreCase(\"\", *)        = \"\"\n     * StringUtils.removeStartIgnoreCase(*, null)      = *\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"www.\")   = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"WWW.\")   = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"domain.com\", \"www.\")       = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"abc\", \"\")    = \"abc\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for (case insensitive) and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.4\n */\n public static String removeStartIgnoreCase(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (StringUtils.startsWithIgnoreCase(str, remove)) {\n return str.substring(remove.length());\n }\n return str;\n }\n\n /**\n *

Removes a substring only if it is at the end of a source string,\n * otherwise returns the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

\n *\n *
\n     * StringUtils.removeEnd(null, *)      = null\n     * StringUtils.removeEnd(\"\", *)        = \"\"\n     * StringUtils.removeEnd(*, null)      = *\n     * StringUtils.removeEnd(\"www.domain.com\", \".com.\")  = \"www.domain.com\"\n     * StringUtils.removeEnd(\"www.domain.com\", \".com\")   = \"www.domain\"\n     * StringUtils.removeEnd(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeEnd(\"abc\", \"\")    = \"abc\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String removeEnd(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (str.endsWith(remove)) {\n return str.substring(0, str.length() - remove.length());\n }\n return str;\n }\n\n /**\n *

Case insensitive removal of a substring if it is at the end of a source string,\n * otherwise returns the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

\n *\n *
\n     * StringUtils.removeEndIgnoreCase(null, *)      = null\n     * StringUtils.removeEndIgnoreCase(\"\", *)        = \"\"\n     * StringUtils.removeEndIgnoreCase(*, null)      = *\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".com.\")  = \"www.domain.com\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".com\")   = \"www.domain\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeEndIgnoreCase(\"abc\", \"\")    = \"abc\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".COM\") = \"www.domain\")\n     * StringUtils.removeEndIgnoreCase(\"www.domain.COM\", \".com\") = \"www.domain\")\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for (case insensitive) and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.4\n */\n public static String removeEndIgnoreCase(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (StringUtils.endsWithIgnoreCase(str, remove)) {\n return str.substring(0, str.length() - remove.length());\n }\n return str;\n }\n\n /**\n *

Removes all occurrences of a substring from within the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null remove string will return the source string.\n * An empty (\"\") remove string will return the source string.

\n *\n *
\n     * StringUtils.remove(null, *)        = null\n     * StringUtils.remove(\"\", *)          = \"\"\n     * StringUtils.remove(*, null)        = *\n     * StringUtils.remove(*, \"\")          = *\n     * StringUtils.remove(\"queued\", \"ue\") = \"qd\"\n     * StringUtils.remove(\"queued\", \"zz\") = \"queued\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String remove(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n return StringUtils.replace(str, remove, StringUtils.EMPTY, -1);\n }\n\n /**\n *

Removes all occurrences of a character from within the source string.

\n *\n *

A null source string will return null.\n * An empty (\"\") source string will return the empty string.

\n *\n *
\n     * StringUtils.remove(null, *)       = null\n     * StringUtils.remove(\"\", *)         = \"\"\n     * StringUtils.remove(\"queued\", 'u') = \"qeed\"\n     * StringUtils.remove(\"queued\", 'z') = \"queued\"\n     * 
\n *\n * @param str the source String to search, may be null\n * @param remove the char to search for and remove, may be null\n * @return the substring with the char removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String remove(final String str, final char remove) {\n if (StringUtils.isEmpty(str) || str.indexOf(remove) == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n char[] chars = str.toCharArray();\n int pos = 0;\n for (int i = 0; i < chars.length; i++) {\n if (chars[i] != remove) {\n chars[pos++] = chars[i];\n }\n }\n return new String(chars, 0, pos);\n }\n // Replacing\n //-----------------------------------------------------------------------\n\n /**\n *

Replaces a String with another String inside a larger String, once.

\n *\n *

A null reference passed to this method is a no-op.

\n *\n *
\n     * StringUtils.replaceOnce(null, *, *)        = null\n     * StringUtils.replaceOnce(\"\", *, *)          = \"\"\n     * StringUtils.replaceOnce(\"any\", null, *)    = \"any\"\n     * StringUtils.replaceOnce(\"any\", *, null)    = \"any\"\n     * StringUtils.replaceOnce(\"any\", \"\", *)      = \"any\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", null)  = \"aba\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", \"\")    = \"ba\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", \"z\")   = \"zba\"\n     * 
\n *\n * @see #replace(String text, String searchString, String replacement, int max)\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace with, may be null\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replaceOnce(final String text, final String searchString, final String replacement) {\n return StringUtils.replace(text, searchString, replacement, 1);\n }\n\n /**\n *

Replaces all occurrences of a String within another String.

\n *\n *

A null reference passed to this method is a no-op.

\n *\n *
\n     * StringUtils.replace(null, *, *)        = null\n     * StringUtils.replace(\"\", *, *)          = \"\"\n     * StringUtils.replace(\"any\", null, *)    = \"any\"\n     * StringUtils.replace(\"any\", *, null)    = \"any\"\n     * StringUtils.replace(\"any\", \"\", *)      = \"any\"\n     * StringUtils.replace(\"aba\", \"a\", null)  = \"aba\"\n     * StringUtils.replace(\"aba\", \"a\", \"\")    = \"b\"\n     * StringUtils.replace(\"aba\", \"a\", \"z\")   = \"zbz\"\n     * 
\n *\n * @see #replace(String text, String searchString, String replacement, int max)\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace it with, may be null\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replace(final String text, final String searchString, final String replacement) {\n return StringUtils.replace(text, searchString, replacement, -1);\n }\n\n /**\n *

Replaces a String with another String inside a larger String,\n * for the first max values of the search String.

\n *\n *

A null reference passed to this method is a no-op.

\n *\n *
\n     * StringUtils.replace(null, *, *, *)         = null\n     * StringUtils.replace(\"\", *, *, *)           = \"\"\n     * StringUtils.replace(\"any\", null, *, *)     = \"any\"\n     * StringUtils.replace(\"any\", *, null, *)     = \"any\"\n     * StringUtils.replace(\"any\", \"\", *, *)       = \"any\"\n     * StringUtils.replace(\"any\", *, *, 0)        = \"any\"\n     * StringUtils.replace(\"abaa\", \"a\", null, -1) = \"abaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"\", -1)   = \"b\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 0)   = \"abaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 1)   = \"zbaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 2)   = \"zbza\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", -1)  = \"zbzz\"\n     * 
\n *\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace it with, may be null\n * @param max maximum number of values to replace, or -1 if no maximum\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replace(final String text, final String searchString, final String replacement, int max) {\n if (StringUtils.isEmpty(text) || StringUtils.isEmpty(searchString) || replacement == null || max == 0) {\n return text;\n }\n int start = 0;\n int end = text.indexOf(searchString, start);\n if (end == StringUtils.INDEX_NOT_FOUND) {\n return text;\n }\n int replLength = searchString.length();\n int increase = replacement.length() - replLength;\n increase = Math.max(increase, 0);\n increase *= max < 0 ? 16 : Math.min(max, 64);\n StringBuilder buf = new StringBuilder(text.length() + increase);\n while (end != StringUtils.INDEX_NOT_FOUND) {\n buf.append(text.substring(start, end)).append(replacement);\n start = end + replLength;\n if (--max == 0) {\n break;\n }\n end = text.indexOf(searchString, start);\n }\n buf.append(text.substring(start));\n return buf.toString();\n }\n\n /**\n *

\n * Replaces all occurrences of Strings within another String.\n *

\n *\n *

\n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored. This will not repeat. For repeating replaces, call the\n * overloaded method.\n *

\n *\n *
\n     *  StringUtils.replaceEach(null, *, *)        = null\n     *  StringUtils.replaceEach(\"\", *, *)          = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0]) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null)  = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"})  = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"})  = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"})  = \"wcte\"\n     *  (example of how it does not repeat)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"})  = \"dcte\"\n     * 
\n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) {\n return StringUtils.replaceEach(text, searchList, replacementList, false, 0);\n }\n\n /**\n *

\n * Replaces all occurrences of Strings within another String.\n *

\n *\n *

\n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored. This will not repeat. For repeating replaces, call the\n * overloaded method.\n *

\n *\n *
\n     *  StringUtils.replaceEach(null, *, *, *) = null\n     *  StringUtils.replaceEach(\"\", *, *, *) = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0], *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"}, *) = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"}, *) = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"}, *) = \"wcte\"\n     *  (example of how it repeats)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, false) = \"dcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, true) = \"tcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, true) = IllegalArgumentException\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, false) = \"dcabe\"\n     * 
\n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IllegalArgumentException\n * if the search is repeating and there is an endless loop due\n * to outputs of one being inputs to another\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) {\n // timeToLive should be 0 if not used or nothing to replace, else it's\n // the length of the replace array\n int timeToLive = searchList == null ? 0 : searchList.length;\n return StringUtils.replaceEach(text, searchList, replacementList, true, timeToLive);\n }\n\n /**\n *

\n * Replaces all occurrences of Strings within another String.\n *

\n *\n *

\n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored.\n *

\n *\n *
\n     *  StringUtils.replaceEach(null, *, *, *) = null\n     *  StringUtils.replaceEach(\"\", *, *, *) = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0], *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"}, *) = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"}, *) = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"}, *) = \"wcte\"\n     *  (example of how it repeats)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, false) = \"dcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, true) = \"tcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, *) = IllegalArgumentException\n     * 
\n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @param repeat if true, then replace repeatedly\n * until there are no more possible replacements or timeToLive < 0\n * @param timeToLive\n * if less than 0 then there is a circular reference and endless\n * loop\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IllegalArgumentException\n * if the search is repeating and there is an endless loop due\n * to outputs of one being inputs to another\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n private static String replaceEach(final String text, final String[] searchList, final String[] replacementList, final boolean repeat, final int timeToLive) {\n // mchyzer Performance note: This creates very few new objects (one major goal)\n // let me know if there are performance requests, we can create a harness to measure\n if (text == null || text.length() == 0 || searchList == null || searchList.length == 0 || replacementList == null || replacementList.length == 0) {\n return text;\n }\n // if recursing, this shouldnt be less than 0\n if (timeToLive < 0) {\n throw new IllegalStateException(\"TimeToLive of \" + timeToLive + \" is less than 0: \" + text);\n }\n int searchLength = searchList.length;\n int replacementLength = replacementList.length;\n // make sure lengths are ok, these need to be equal\n if (searchLength != replacementLength) {\n throw new IllegalArgumentException(\"Search and Replace array lengths don't match: \" + searchLength + \" vs \" + replacementLength);\n }\n // keep track of which still have matches\n boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];\n // index on index that the match was found\n int textIndex = -1;\n int replaceIndex = -1;\n int tempIndex = -1;\n // index of replace array that will replace the search string found\n // NOTE: logic duplicated below START\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) {\n continue;\n }\n tempIndex = text.indexOf(searchList[i]);\n // see if we need to keep searching for this\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n // NOTE: logic mostly below END\n // no search strings found, we are done\n if (textIndex == -1) {\n return text;\n }\n int start = 0;\n // get a good guess on the size of the result buffer so it doesnt have to double if it goes over a bit\n int increase = 0;\n // count the replacement text elements that are larger than their corresponding text being replaced\n for (int i = 0; i < searchList.length; i++) {\n if (searchList[i] == null || replacementList[i] == null) {\n continue;\n }\n int greater = replacementList[i].length() - searchList[i].length();\n if (greater > 0) {\n increase += 3 * greater; // assume 3 matches\n }\n }\n // have upper-bound at 20% increase, then let Java take over\n increase = Math.min(increase, text.length() / 5);\n StringBuilder buf = new StringBuilder(text.length() + increase);\n while (textIndex != -1) {\n for (int i = start; i < textIndex; i++) {\n buf.append(text.charAt(i));\n }\n buf.append(replacementList[replaceIndex]);\n start = textIndex + searchList[replaceIndex].length();\n textIndex = -1;\n replaceIndex = -1;\n tempIndex = -1;\n // find the next earliest match\n // NOTE: logic mostly duplicated above START\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) {\n continue;\n }\n tempIndex = text.indexOf(searchList[i], start);\n // see if we need to keep searching for this\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n // NOTE: logic duplicated above END\n }\n int textLength = text.length();\n for (int i = start; i < textLength; i++) {\n buf.append(text.charAt(i));\n }\n String result = buf.toString();\n if (!repeat) {\n return result;\n }\n return StringUtils.replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);\n }\n // Replace, character based\n //-----------------------------------------------------------------------\n\n /**\n *

Replaces all occurrences of a character in a String with another.\n * This is a null-safe version of {@link String#replace(char, char)}.

\n *\n *

A null string input returns null.\n * An empty (\"\") string input returns an empty string.

\n *\n *
\n     * StringUtils.replaceChars(null, *, *)        = null\n     * StringUtils.replaceChars(\"\", *, *)          = \"\"\n     * StringUtils.replaceChars(\"abcba\", 'b', 'y') = \"aycya\"\n     * StringUtils.replaceChars(\"abcba\", 'z', 'y') = \"abcba\"\n     * 
\n *\n * @param str String to replace characters in, may be null\n * @param searchChar the character to search for, may be null\n * @param replaceChar the character to replace, may be null\n * @return modified String, null if null string input\n * @since 2.0\n */\n public static String replaceChars(final String str, final char searchChar, final char replaceChar) {\n if (str == null) {\n return null;\n }\n return str.replace(searchChar, replaceChar);\n }\n\n /**\n *

Replaces multiple characters in a String in one go.\n * This method can also be used to delete characters.

\n *\n *

For example:
\n * replaceChars("hello", "ho", "jy") = jelly.

\n *\n *

A null string input returns null.\n * An empty (\"\") string input returns an empty string.\n * A null or empty set of search characters returns the input string.

\n *\n *

The length of the search characters should normally equal the length\n * of the replace characters.\n * If the search characters is longer, then the extra search characters\n * are deleted.\n * If the search characters is shorter, then the extra replace characters\n * are ignored.

\n *\n *
\n     * StringUtils.replaceChars(null, *, *)           = null\n     * StringUtils.replaceChars(\"\", *, *)             = \"\"\n     * StringUtils.replaceChars(\"abc\", null, *)       = \"abc\"\n     * StringUtils.replaceChars(\"abc\", \"\", *)         = \"abc\"\n     * StringUtils.replaceChars(\"abc\", \"b\", null)     = \"ac\"\n     * StringUtils.replaceChars(\"abc\", \"b\", \"\")       = \"ac\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"yz\")  = \"ayzya\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"y\")   = \"ayya\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"yzx\") = \"ayzya\"\n     * 
\n *\n * @param str String to replace characters in, may be null\n * @param searchChars a set of characters to search for, may be null\n * @param replaceChars a set of characters to replace, may be null\n * @return modified String, null if null string input\n * @since 2.0\n */\n public static String replaceChars(final String str, final String searchChars, String replaceChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return str;\n }\n if (replaceChars == null) {\n replaceChars = StringUtils.EMPTY;\n }\n boolean modified = false;\n int replaceCharsLength = replaceChars.length();\n int strLength = str.length();\n StringBuilder buf = new StringBuilder(strLength);\n for (int i = 0; i < strLength; i++) {\n char ch = str.charAt(i);\n int index = searchChars.indexOf(ch);\n if (index >= 0) {\n modified = true;\n if (index < replaceCharsLength) {\n buf.append(replaceChars.charAt(index));\n }\n } else {\n buf.append(ch);\n }\n }\n if (modified) {\n return buf.toString();\n }\n return str;\n }\n // Overlay\n //-----------------------------------------------------------------------\n\n /**\n *

Overlays part of a String with another String.

\n *\n *

A null string input returns null.\n * A negative index is treated as zero.\n * An index greater than the string length is treated as the string length.\n * The start index is always the smaller of the two indices.

\n *\n *
\n     * StringUtils.overlay(null, *, *, *)            = null\n     * StringUtils.overlay(\"\", \"abc\", 0, 0)          = \"abc\"\n     * StringUtils.overlay(\"abcdef\", null, 2, 4)     = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"\", 2, 4)       = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"\", 4, 2)       = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 2, 4)   = \"abzzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 4, 2)   = \"abzzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", -1, 4)  = \"zzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 2, 8)   = \"abzzzz\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", -2, -3) = \"zzzzabcdef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 8, 10)  = \"abcdefzzzz\"\n     * 
\n *\n * @param str the String to do overlaying in, may be null\n * @param overlay the String to overlay, may be null\n * @param start the position to start overlaying at\n * @param end the position to stop overlaying before\n * @return overlayed String, null if null String input\n * @since 2.0\n */\n public static String overlay(final String str, String overlay, int start, int end) {\n if (str == null) {\n return null;\n }\n if (overlay == null) {\n overlay = StringUtils.EMPTY;\n }\n int len = str.length();\n if (start < 0) {\n start = 0;\n }\n if (start > len) {\n start = len;\n }\n if (end < 0) {\n end = 0;\n }\n if (end > len) {\n end = len;\n }\n if (start > end) {\n int temp = start;\n start = end;\n end = temp;\n }\n return str.substring(0, start) + overlay + str.substring(end);\n }\n // Chomping\n //-----------------------------------------------------------------------\n\n /**\n *

Removes one newline from end of a String if it's there,\n * otherwise leave it alone. A newline is "\\n",\n * "\\r", or "\\r\\n".

\n *\n *

NOTE: This method changed in 2.0.\n * It now more closely matches Perl chomp.

\n *\n *
\n     * StringUtils.chomp(null)          = null\n     * StringUtils.chomp(\"\")            = \"\"\n     * StringUtils.chomp(\"abc \\r\")      = \"abc \"\n     * StringUtils.chomp(\"abc\\n\")       = \"abc\"\n     * StringUtils.chomp(\"abc\\r\\n\")     = \"abc\"\n     * StringUtils.chomp(\"abc\\r\\n\\r\\n\") = \"abc\\r\\n\"\n     * StringUtils.chomp(\"abc\\n\\r\")     = \"abc\\n\"\n     * StringUtils.chomp(\"abc\\n\\rabc\")  = \"abc\\n\\rabc\"\n     * StringUtils.chomp(\"\\r\")          = \"\"\n     * StringUtils.chomp(\"\\n\")          = \"\"\n     * StringUtils.chomp(\"\\r\\n\")        = \"\"\n     * 
\n *\n * @param str the String to chomp a newline from, may be null\n * @return String without newline, null if null String input\n */\n public static String chomp(final String str) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (str.length() == 1) {\n char ch = str.charAt(0);\n if (ch == CharUtils.CR || ch == CharUtils.LF) {\n return StringUtils.EMPTY;\n }\n return str;\n }\n int lastIdx = str.length() - 1;\n char last = str.charAt(lastIdx);\n if (last == CharUtils.LF) {\n if (str.charAt(lastIdx - 1) == CharUtils.CR) {\n lastIdx--;\n }\n } else if (last != CharUtils.CR) {\n lastIdx++;\n }\n return str.substring(0, lastIdx);\n }\n\n /**\n *

Removes separator from the end of\n * str if it's there, otherwise leave it alone.

\n *\n *

NOTE: This method changed in version 2.0.\n * It now more closely matches Perl chomp.\n * For the previous behavior, use {@link #substringBeforeLast(String, String)}.\n * This method uses {@link String#endsWith(String)}.

\n *\n *
\n     * StringUtils.chomp(null, *)         = null\n     * StringUtils.chomp(\"\", *)           = \"\"\n     * StringUtils.chomp(\"foobar\", \"bar\") = \"foo\"\n     * StringUtils.chomp(\"foobar\", \"baz\") = \"foobar\"\n     * StringUtils.chomp(\"foo\", \"foo\")    = \"\"\n     * StringUtils.chomp(\"foo \", \"foo\")   = \"foo \"\n     * StringUtils.chomp(\" foo\", \"foo\")   = \" \"\n     * StringUtils.chomp(\"foo\", \"foooo\")  = \"foo\"\n     * StringUtils.chomp(\"foo\", \"\")       = \"foo\"\n     * StringUtils.chomp(\"foo\", null)     = \"foo\"\n     * 
\n *\n * @param str the String to chomp from, may be null\n * @param separator separator String, may be null\n * @return String without trailing separator, null if null String input\n */\n public static String chomp(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || separator == null) {\n return str;\n }\n if (str.endsWith(separator)) {\n return str.substring(0, str.length() - separator.length());\n }\n return str;\n }\n // Chopping\n //-----------------------------------------------------------------------\n\n /**\n *

Remove the last character from a String.

\n *\n *

If the String ends in \\r\\n, then remove both\n * of them.

\n *\n *
\n     * StringUtils.chop(null)          = null\n     * StringUtils.chop(\"\")            = \"\"\n     * StringUtils.chop(\"abc \\r\")      = \"abc \"\n     * StringUtils.chop(\"abc\\n\")       = \"abc\"\n     * StringUtils.chop(\"abc\\r\\n\")     = \"abc\"\n     * StringUtils.chop(\"abc\")         = \"ab\"\n     * StringUtils.chop(\"abc\\nabc\")    = \"abc\\nab\"\n     * StringUtils.chop(\"a\")           = \"\"\n     * StringUtils.chop(\"\\r\")          = \"\"\n     * StringUtils.chop(\"\\n\")          = \"\"\n     * StringUtils.chop(\"\\r\\n\")        = \"\"\n     * 
\n *\n * @param str the String to chop last character from, may be null\n * @return String without last character, null if null String input\n */\n public static String chop(final String str) {\n if (str == null) {\n return null;\n }\n int strLen = str.length();\n if (strLen < 2) {\n return StringUtils.EMPTY;\n }\n int lastIdx = strLen - 1;\n String ret = str.substring(0, lastIdx);\n char last = str.charAt(lastIdx);\n if (last == CharUtils.LF) {\n if (ret.charAt(lastIdx - 1) == CharUtils.CR) {\n return ret.substring(0, lastIdx - 1);\n }\n }\n return ret;\n }\n // Padding\n //-----------------------------------------------------------------------\n\n /**\n *

Repeat a String repeat times to form a\n * new String.

\n *\n *
\n     * StringUtils.repeat(null, 2) = null\n     * StringUtils.repeat(\"\", 0)   = \"\"\n     * StringUtils.repeat(\"\", 2)   = \"\"\n     * StringUtils.repeat(\"a\", 3)  = \"aaa\"\n     * StringUtils.repeat(\"ab\", 2) = \"abab\"\n     * StringUtils.repeat(\"a\", -2) = \"\"\n     * 
\n *\n * @param character the Character to to repeat, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n */\n public static String repeat(final char character, final int repeat) {\n return repeat(character + \"\", repeat);\n }\n\n /**\n *

Repeat a String repeat times to form a\n * new String.

\n *\n *
\n     * StringUtils.repeat(null, 2) = null\n     * StringUtils.repeat(\"\", 0)   = \"\"\n     * StringUtils.repeat(\"\", 2)   = \"\"\n     * StringUtils.repeat(\"a\", 3)  = \"aaa\"\n     * StringUtils.repeat(\"ab\", 2) = \"abab\"\n     * StringUtils.repeat(\"a\", -2) = \"\"\n     * 
\n *\n * @param str the String to repeat, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n */\n public static String repeat(final String str, final int repeat) {\n // Performance tuned for 2.0 (JDK1.4)\n if (str == null) {\n return null;\n }\n if (repeat <= 0) {\n return StringUtils.EMPTY;\n }\n int inputLength = str.length();\n if (repeat == 1 || inputLength == 0) {\n return str;\n }\n if (inputLength == 1 && repeat <= StringUtils.PAD_LIMIT) {\n return StringUtils.padding(repeat, str.charAt(0));\n }\n int outputLength = inputLength * repeat;\n switch (inputLength) {\n case 1:\n char ch = str.charAt(0);\n char[] output1 = new char[outputLength];\n for (int i = repeat - 1; i >= 0; i--) {\n output1[i] = ch;\n }\n return new String(output1);\n case 2:\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n char[] output2 = new char[outputLength];\n for (int i = repeat * 2 - 2; i >= 0; i--, i--) {\n output2[i] = ch0;\n output2[i + 1] = ch1;\n }\n return new String(output2);\n default:\n StringBuilder buf = new StringBuilder(outputLength);\n for (int i = 0; i < repeat; i++) {\n buf.append(str);\n }\n return buf.toString();\n }\n }\n\n /**\n *

Repeat a String repeat times to form a\n * new String, with a String separator injected each time.

\n *\n *
\n     * StringUtils.repeat(null, null, 2) = null\n     * StringUtils.repeat(null, \"x\", 2)  = null\n     * StringUtils.repeat(\"\", null, 0)   = \"\"\n     * StringUtils.repeat(\"\", \"\", 2)     = \"\"\n     * StringUtils.repeat(\"\", \"x\", 3)    = \"xxx\"\n     * StringUtils.repeat(\"?\", \", \", 3)  = \"?, ?, ?\"\n     * 
\n *\n * @param str the String to repeat, may be null\n * @param separator the String to inject, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n * @since 2.5\n */\n public static String repeat(final String str, final String separator, final int repeat) {\n if (str == null || separator == null) {\n return StringUtils.repeat(str, repeat);\n } else {\n // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it\n String result = StringUtils.repeat(str + separator, repeat);\n return StringUtils.removeEnd(result, separator);\n }\n }\n\n /**\n *

Returns padding using the specified delimiter repeated\n * to a given length.

\n *\n *
\n     * StringUtils.padding(0, 'e')  = \"\"\n     * StringUtils.padding(3, 'e')  = \"eee\"\n     * StringUtils.padding(-2, 'e') = IndexOutOfBoundsException\n     * 
\n *\n *

Note: this method doesn't not support padding with\n * Unicode Supplementary Characters\n * as they require a pair of chars to be represented.\n * If you are needing to support full I18N of your applications\n * consider using {@link #repeat(String, int)} instead.\n *

\n *\n * @param repeat number of times to repeat delim\n * @param padChar character to repeat\n * @return String with repeated character\n * @throws IndexOutOfBoundsException if repeat < 0\n * @see #repeat(String, int)\n */\n private static String padding(final int repeat, final char padChar) throws IndexOutOfBoundsException {\n if (repeat < 0) {\n throw new IndexOutOfBoundsException(\"Cannot pad a negative amount: \" + repeat);\n }\n final char[] buf = new char[repeat];\n Arrays.fill(buf, padChar);\n return new String(buf);\n }\n\n /**\n *

Right pad a String with spaces (' ').

\n *\n *

The String is padded to the size of size.

\n *\n *
\n     * StringUtils.rightPad(null, *)   = null\n     * StringUtils.rightPad(\"\", 3)     = \"   \"\n     * StringUtils.rightPad(\"bat\", 3)  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5)  = \"bat  \"\n     * StringUtils.rightPad(\"bat\", 1)  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1) = \"bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String rightPad(final String str, final int size) {\n return StringUtils.rightPad(str, size, ' ');\n }\n\n /**\n *

Right pad a String with a specified character.

\n *\n *

The String is padded to the size of size.

\n *\n *
\n     * StringUtils.rightPad(null, *, *)     = null\n     * StringUtils.rightPad(\"\", 3, 'z')     = \"zzz\"\n     * StringUtils.rightPad(\"bat\", 3, 'z')  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, 'z')  = \"batzz\"\n     * StringUtils.rightPad(\"bat\", 1, 'z')  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1, 'z') = \"bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padChar the character to pad with\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n * @since 2.0\n */\n public static String rightPad(final String str, final int size, final char padChar) {\n if (str == null) {\n return null;\n }\n int pads = size - str.length();\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (pads > StringUtils.PAD_LIMIT) {\n return StringUtils.rightPad(str, size, String.valueOf(padChar));\n }\n return str.concat(StringUtils.padding(pads, padChar));\n }\n\n /**\n *

Right pad a String with a specified String.

\n *\n *

The String is padded to the size of size.

\n *\n *
\n     * StringUtils.rightPad(null, *, *)      = null\n     * StringUtils.rightPad(\"\", 3, \"z\")      = \"zzz\"\n     * StringUtils.rightPad(\"bat\", 3, \"yz\")  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, \"yz\")  = \"batyz\"\n     * StringUtils.rightPad(\"bat\", 8, \"yz\")  = \"batyzyzy\"\n     * StringUtils.rightPad(\"bat\", 1, \"yz\")  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1, \"yz\") = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, null)  = \"bat  \"\n     * StringUtils.rightPad(\"bat\", 5, \"\")    = \"bat  \"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padStr the String to pad with, null or empty treated as single space\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String rightPad(final String str, final int size, String padStr) {\n if (str == null) {\n return null;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int padLen = padStr.length();\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (padLen == 1 && pads <= StringUtils.PAD_LIMIT) {\n return StringUtils.rightPad(str, size, padStr.charAt(0));\n }\n if (pads == padLen) {\n return str.concat(padStr);\n } else if (pads < padLen) {\n return str.concat(padStr.substring(0, pads));\n } else {\n char[] padding = new char[pads];\n char[] padChars = padStr.toCharArray();\n for (int i = 0; i < pads; i++) {\n padding[i] = padChars[i % padLen];\n }\n return str.concat(new String(padding));\n }\n }\n\n /**\n *

Left pad a String with spaces (' ').

\n *\n *

The String is padded to the size of size.

\n *\n *
\n     * StringUtils.leftPad(null, *)   = null\n     * StringUtils.leftPad(\"\", 3)     = \"   \"\n     * StringUtils.leftPad(\"bat\", 3)  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5)  = \"  bat\"\n     * StringUtils.leftPad(\"bat\", 1)  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1) = \"bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String leftPad(final String str, final int size) {\n return StringUtils.leftPad(str, size, ' ');\n }\n\n /**\n *

Left pad a String with a specified character.

\n *\n *

Pad to a size of size.

\n *\n *
\n     * StringUtils.leftPad(null, *, *)     = null\n     * StringUtils.leftPad(\"\", 3, 'z')     = \"zzz\"\n     * StringUtils.leftPad(\"bat\", 3, 'z')  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, 'z')  = \"zzbat\"\n     * StringUtils.leftPad(\"bat\", 1, 'z')  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1, 'z') = \"bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padChar the character to pad with\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n * @since 2.0\n */\n public static String leftPad(final String str, final int size, final char padChar) {\n if (str == null) {\n return null;\n }\n int pads = size - str.length();\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (pads > StringUtils.PAD_LIMIT) {\n return StringUtils.leftPad(str, size, String.valueOf(padChar));\n }\n return StringUtils.padding(pads, padChar).concat(str);\n }\n\n /**\n *

Left pad a String with a specified String.

\n *\n *

Pad to a size of size.

\n *\n *
\n     * StringUtils.leftPad(null, *, *)      = null\n     * StringUtils.leftPad(\"\", 3, \"z\")      = \"zzz\"\n     * StringUtils.leftPad(\"bat\", 3, \"yz\")  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, \"yz\")  = \"yzbat\"\n     * StringUtils.leftPad(\"bat\", 8, \"yz\")  = \"yzyzybat\"\n     * StringUtils.leftPad(\"bat\", 1, \"yz\")  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1, \"yz\") = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, null)  = \"  bat\"\n     * StringUtils.leftPad(\"bat\", 5, \"\")    = \"  bat\"\n     * 
\n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padStr the String to pad with, null or empty treated as single space\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String leftPad(final String str, final int size, String padStr) {\n if (str == null) {\n return null;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int padLen = padStr.length();\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (padLen == 1 && pads <= StringUtils.PAD_LIMIT) {\n return StringUtils.leftPad(str, size, padStr.charAt(0));\n }\n if (pads == padLen) {\n return padStr.concat(str);\n } else if (pads < padLen) {\n return padStr.substring(0, pads).concat(str);\n } else {\n char[] padding = new char[pads];\n char[] padChars = padStr.toCharArray();\n for (int i = 0; i < pads; i++) {\n padding[i] = padChars[i % padLen];\n }\n return new String(padding).concat(str);\n }\n }\n\n /**\n * Gets a String's length or 0 if the String is null.\n *\n * @param str\n * a String or null\n * @return String length or 0 if the String is null.\n * @since 2.4\n */\n public static int length(final String str) {\n return str == null ? 0 : str.length();\n }\n // Centering\n //-----------------------------------------------------------------------\n\n /**\n *

Centers a String in a larger String of size size\n * using the space character (' ').

\n *\n *

If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

\n *\n *

Equivalent to center(str, size, \" \").

\n *\n *
\n     * StringUtils.center(null, *)   = null\n     * StringUtils.center(\"\", 4)     = \"    \"\n     * StringUtils.center(\"ab\", -1)  = \"ab\"\n     * StringUtils.center(\"ab\", 4)   = \" ab \"\n     * StringUtils.center(\"abcd\", 2) = \"abcd\"\n     * StringUtils.center(\"a\", 4)    = \" a  \"\n     * 
\n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @return centered String, null if null String input\n */\n public static String center(final String str, final int size) {\n return StringUtils.center(str, size, ' ');\n }\n\n /**\n *

Centers a String in a larger String of size size.\n * Uses a supplied character as the value to pad the String with.

\n *\n *

If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

\n *\n *
\n     * StringUtils.center(null, *, *)     = null\n     * StringUtils.center(\"\", 4, ' ')     = \"    \"\n     * StringUtils.center(\"ab\", -1, ' ')  = \"ab\"\n     * StringUtils.center(\"ab\", 4, ' ')   = \" ab\"\n     * StringUtils.center(\"abcd\", 2, ' ') = \"abcd\"\n     * StringUtils.center(\"a\", 4, ' ')    = \" a  \"\n     * StringUtils.center(\"a\", 4, 'y')    = \"yayy\"\n     * 
\n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @param padChar the character to pad the new String with\n * @return centered String, null if null String input\n * @since 2.0\n */\n public static String center(String str, final int size, final char padChar) {\n if (str == null || size <= 0) {\n return str;\n }\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str;\n }\n str = StringUtils.leftPad(str, strLen + pads / 2, padChar);\n str = StringUtils.rightPad(str, size, padChar);\n return str;\n }\n\n /**\n *

Centers a String in a larger String of size size.\n * Uses a supplied String as the value to pad the String with.

\n *\n *

If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

\n *\n *
\n     * StringUtils.center(null, *, *)     = null\n     * StringUtils.center(\"\", 4, \" \")     = \"    \"\n     * StringUtils.center(\"ab\", -1, \" \")  = \"ab\"\n     * StringUtils.center(\"ab\", 4, \" \")   = \" ab\"\n     * StringUtils.center(\"abcd\", 2, \" \") = \"abcd\"\n     * StringUtils.center(\"a\", 4, \" \")    = \" a  \"\n     * StringUtils.center(\"a\", 4, \"yz\")   = \"yayz\"\n     * StringUtils.center(\"abc\", 7, null) = \"  abc  \"\n     * StringUtils.center(\"abc\", 7, \"\")   = \"  abc  \"\n     * 
\n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @param padStr the String to pad the new String with, must not be null or empty\n * @return centered String, null if null String input\n * @throws IllegalArgumentException if padStr is null or empty\n */\n public static String center(String str, final int size, String padStr) {\n if (str == null || size <= 0) {\n return str;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str;\n }\n str = StringUtils.leftPad(str, strLen + pads / 2, padStr);\n str = StringUtils.rightPad(str, size, padStr);\n return str;\n }\n // Case conversion\n //-----------------------------------------------------------------------\n\n /**\n *

Converts a String to upper case as per {@link String#toUpperCase()}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.upperCase(null)  = null\n     * StringUtils.upperCase(\"\")    = \"\"\n     * StringUtils.upperCase(\"aBc\") = \"ABC\"\n     * 
\n *\n *

Note: As described in the documentation for {@link String#toUpperCase()},\n * the result of this method is affected by the current locale.\n * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}\n * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

\n *\n * @param str the String to upper case, may be null\n * @return the upper cased String, null if null String input\n */\n public static String upperCase(final String str) {\n if (str == null) {\n return null;\n }\n return str.toUpperCase();\n }\n\n /**\n *

Converts a String to upper case as per {@link String#toUpperCase(Locale)}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.upperCase(null, Locale.ENGLISH)  = null\n     * StringUtils.upperCase(\"\", Locale.ENGLISH)    = \"\"\n     * StringUtils.upperCase(\"aBc\", Locale.ENGLISH) = \"ABC\"\n     * 
\n *\n * @param str the String to upper case, may be null\n * @param locale the locale that defines the case transformation rules, must not be null\n * @return the upper cased String, null if null String input\n * @since 2.5\n */\n public static String upperCase(final String str, final Locale locale) {\n if (str == null) {\n return null;\n }\n return str.toUpperCase(locale);\n }\n\n /**\n *

Converts a String to lower case as per {@link String#toLowerCase()}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.lowerCase(null)  = null\n     * StringUtils.lowerCase(\"\")    = \"\"\n     * StringUtils.lowerCase(\"aBc\") = \"abc\"\n     * 
\n *\n *

Note: As described in the documentation for {@link String#toLowerCase()},\n * the result of this method is affected by the current locale.\n * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}\n * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

\n *\n * @param str the String to lower case, may be null\n * @return the lower cased String, null if null String input\n */\n public static String lowerCase(final String str) {\n if (str == null) {\n return null;\n }\n return str.toLowerCase();\n }\n\n /**\n *

Converts a String to lower case as per {@link String#toLowerCase(Locale)}.

\n *\n *

A null input String returns null.

\n *\n *
\n     * StringUtils.lowerCase(null, Locale.ENGLISH)  = null\n     * StringUtils.lowerCase(\"\", Locale.ENGLISH)    = \"\"\n     * StringUtils.lowerCase(\"aBc\", Locale.ENGLISH) = \"abc\"\n     * 
\n *\n * @param str the String to lower case, may be null\n * @param locale the locale that defines the case transformation rules, must not be null\n * @return the lower cased String, null if null String input\n * @since 2.5\n */\n public static String lowerCase(final String str, final Locale locale) {\n if (str == null) {\n return null;\n }\n return str.toLowerCase(locale);\n }\n\n /**\n *

Capitalizes a String changing the first letter to title case as\n * per {@link Character#toTitleCase(char)}. No other letters are changed.

\n *\n * A null input String returns null.

\n *\n *
\n     * StringUtils.capitalize(null)  = null\n     * StringUtils.capitalize(\"\")    = \"\"\n     * StringUtils.capitalize(\"cat\") = \"Cat\"\n     * StringUtils.capitalize(\"cAt\") = \"CAt\"\n     * 
\n *\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null String input\n * @see #uncapitalize(String)\n * @since 2.0\n */\n public static String capitalize(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n return Character.toTitleCase(str.charAt(0)) + str.substring(1);\n }\n\n /**\n *

Uncapitalizes a String changing the first letter to title case as\n * per {@link Character#toLowerCase(char)}. No other letters are changed.

\n *\n * A null input String returns null.

\n *\n *
\n     * StringUtils.uncapitalize(null)  = null\n     * StringUtils.uncapitalize(\"\")    = \"\"\n     * StringUtils.uncapitalize(\"Cat\") = \"cat\"\n     * StringUtils.uncapitalize(\"CAT\") = \"cAT\"\n     * 
\n *\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null String input\n * @see #capitalize(String)\n * @since 2.0\n */\n public static String uncapitalize(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n return Character.toLowerCase(str.charAt(0)) + str.substring(1);\n }\n\n /**\n *

Swaps the case of a String changing upper and title case to\n * lower case, and lower case to upper case.

\n *\n *
    \n *
  • Upper case character converts to Lower case
  • \n *
  • Title case character converts to Lower case
  • \n *
  • Lower case character converts to Upper case
  • \n *
\n *\n * A null input String returns null.

\n *\n *
\n     * StringUtils.swapCase(null)                 = null\n     * StringUtils.swapCase(\"\")                   = \"\"\n     * StringUtils.swapCase(\"The dog has a BONE\") = \"tHE DOG HAS A bone\"\n     * 
\n *\n *

NOTE: This method changed in Lang version 2.0.\n * It no longer performs a word based algorithm.\n * If you only use ASCII, you will notice no change.\n * That functionality is available in WordUtils.

\n *\n * @param str the String to swap case, may be null\n * @return the changed String, null if null String input\n */\n public static String swapCase(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n StringBuilder buffer = new StringBuilder(strLen);\n char ch = 0;\n for (int i = 0; i < strLen; i++) {\n ch = str.charAt(i);\n if (Character.isUpperCase(ch)) {\n ch = Character.toLowerCase(ch);\n } else if (Character.isTitleCase(ch)) {\n ch = Character.toLowerCase(ch);\n } else if (Character.isLowerCase(ch)) {\n ch = Character.toUpperCase(ch);\n }\n buffer.append(ch);\n }\n return buffer.toString();\n }\n // Count matches\n //-----------------------------------------------------------------------\n\n /**\n *

Counts how many times the substring appears in the larger String.

\n *\n *

A null or empty (\"\") String input returns 0.

\n *\n *
\n     * StringUtils.countMatches(null, *)       = 0\n     * StringUtils.countMatches(\"\", *)         = 0\n     * StringUtils.countMatches(\"abba\", null)  = 0\n     * StringUtils.countMatches(\"abba\", \"\")    = 0\n     * StringUtils.countMatches(\"abba\", \"a\")   = 2\n     * StringUtils.countMatches(\"abba\", \"ab\")  = 1\n     * StringUtils.countMatches(\"abba\", \"xxx\") = 0\n     * 
\n *\n * @param str the String to check, may be null\n * @param sub the substring to count, may be null\n * @return the number of occurrences, 0 if either String is null\n */\n public static int countMatches(final String str, final String sub) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(sub)) {\n return 0;\n }\n int count = 0;\n int idx = 0;\n while ((idx = str.indexOf(sub, idx)) != StringUtils.INDEX_NOT_FOUND) {\n count++;\n idx += sub.length();\n }\n return count;\n }\n // Character Tests\n //-----------------------------------------------------------------------\n\n /**\n *

Checks if the String contains only unicode letters.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAlpha(null)   = false\n     * StringUtils.isAlpha(\"\")     = true\n     * StringUtils.isAlpha(\"  \")   = false\n     * StringUtils.isAlpha(\"abc\")  = true\n     * StringUtils.isAlpha(\"ab2c\") = false\n     * StringUtils.isAlpha(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains letters, and is non-null\n */\n public static boolean isAlpha(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetter(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode letters and\n * space (' ').

\n *\n *

null will return false\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAlphaSpace(null)   = false\n     * StringUtils.isAlphaSpace(\"\")     = true\n     * StringUtils.isAlphaSpace(\"  \")   = true\n     * StringUtils.isAlphaSpace(\"abc\")  = true\n     * StringUtils.isAlphaSpace(\"ab c\") = true\n     * StringUtils.isAlphaSpace(\"ab2c\") = false\n     * StringUtils.isAlphaSpace(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains letters and space,\n * and is non-null\n */\n public static boolean isAlphaSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetter(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode letters or digits.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAlphanumeric(null)   = false\n     * StringUtils.isAlphanumeric(\"\")     = true\n     * StringUtils.isAlphanumeric(\"  \")   = false\n     * StringUtils.isAlphanumeric(\"abc\")  = true\n     * StringUtils.isAlphanumeric(\"ab c\") = false\n     * StringUtils.isAlphanumeric(\"ab2c\") = true\n     * StringUtils.isAlphanumeric(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains letters or digits,\n * and is non-null\n */\n public static boolean isAlphanumeric(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetterOrDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode letters, digits\n * or space (' ').

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAlphanumeric(null)   = false\n     * StringUtils.isAlphanumeric(\"\")     = true\n     * StringUtils.isAlphanumeric(\"  \")   = true\n     * StringUtils.isAlphanumeric(\"abc\")  = true\n     * StringUtils.isAlphanumeric(\"ab c\") = true\n     * StringUtils.isAlphanumeric(\"ab2c\") = true\n     * StringUtils.isAlphanumeric(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains letters, digits or space,\n * and is non-null\n */\n public static boolean isAlphanumericSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetterOrDigit(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the string contains only ASCII printable characters.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isAsciiPrintable(null)     = false\n     * StringUtils.isAsciiPrintable(\"\")       = true\n     * StringUtils.isAsciiPrintable(\" \")      = true\n     * StringUtils.isAsciiPrintable(\"Ceki\")   = true\n     * StringUtils.isAsciiPrintable(\"ab2c\")   = true\n     * StringUtils.isAsciiPrintable(\"!ab-c~\") = true\n     * StringUtils.isAsciiPrintable(\"\\u0020\") = true\n     * StringUtils.isAsciiPrintable(\"\\u0021\") = true\n     * StringUtils.isAsciiPrintable(\"\\u007e\") = true\n     * StringUtils.isAsciiPrintable(\"\\u007f\") = false\n     * StringUtils.isAsciiPrintable(\"Ceki G\\u00fclc\\u00fc\") = false\n     * 
\n *\n * @param str the string to check, may be null\n * @return true if every character is in the range\n * 32 thru 126\n * @since 2.1\n */\n public static boolean isAsciiPrintable(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!CharUtils.isAsciiPrintable(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode digits.\n * A decimal point is not a unicode digit and returns false.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isNumeric(null)   = false\n     * StringUtils.isNumeric(\"\")     = true\n     * StringUtils.isNumeric(\"  \")   = false\n     * StringUtils.isNumeric(\"123\")  = true\n     * StringUtils.isNumeric(\"12 3\") = false\n     * StringUtils.isNumeric(\"ab2c\") = false\n     * StringUtils.isNumeric(\"12-3\") = false\n     * StringUtils.isNumeric(\"12.3\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains digits, and is non-null\n */\n public static boolean isNumeric(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only unicode digits or space\n * (' ').\n * A decimal point is not a unicode digit and returns false.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isNumeric(null)   = false\n     * StringUtils.isNumeric(\"\")     = true\n     * StringUtils.isNumeric(\"  \")   = true\n     * StringUtils.isNumeric(\"123\")  = true\n     * StringUtils.isNumeric(\"12 3\") = true\n     * StringUtils.isNumeric(\"ab2c\") = false\n     * StringUtils.isNumeric(\"12-3\") = false\n     * StringUtils.isNumeric(\"12.3\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains digits or space,\n * and is non-null\n */\n public static boolean isNumericSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only whitespace.

\n *\n *

null will return false.\n * An empty String (length()=0) will return true.

\n *\n *
\n     * StringUtils.isWhitespace(null)   = false\n     * StringUtils.isWhitespace(\"\")     = true\n     * StringUtils.isWhitespace(\"  \")   = true\n     * StringUtils.isWhitespace(\"abc\")  = false\n     * StringUtils.isWhitespace(\"ab2c\") = false\n     * StringUtils.isWhitespace(\"ab-c\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains whitespace, and is non-null\n * @since 2.0\n */\n public static boolean isWhitespace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only lowercase characters.

\n *\n *

null will return false.\n * An empty String (length()=0) will return false.

\n *\n *
\n     * StringUtils.isAllLowerCase(null)   = false\n     * StringUtils.isAllLowerCase(\"\")     = false\n     * StringUtils.isAllLowerCase(\"  \")   = false\n     * StringUtils.isAllLowerCase(\"abc\")  = true\n     * StringUtils.isAllLowerCase(\"abC\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains lowercase characters, and is non-null\n * @since 2.5\n */\n public static boolean isAllLowerCase(final String str) {\n if (str == null || StringUtils.isEmpty(str)) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLowerCase(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

Checks if the String contains only uppercase characters.

\n *\n *

null will return false.\n * An empty String (length()=0) will return false.

\n *\n *
\n     * StringUtils.isAllUpperCase(null)   = false\n     * StringUtils.isAllUpperCase(\"\")     = false\n     * StringUtils.isAllUpperCase(\"  \")   = false\n     * StringUtils.isAllUpperCase(\"ABC\")  = true\n     * StringUtils.isAllUpperCase(\"aBC\") = false\n     * 
\n *\n * @param str the String to check, may be null\n * @return true if only contains uppercase characters, and is non-null\n * @since 2.5\n */\n public static boolean isAllUpperCase(final String str) {\n if (str == null || StringUtils.isEmpty(str)) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isUpperCase(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n // Defaults\n //-----------------------------------------------------------------------\n\n /**\n *

Returns either the passed in String,\n * or if the String is null, an empty String (\"\").

\n *\n *
\n     * StringUtils.defaultString(null)  = \"\"\n     * StringUtils.defaultString(\"\")    = \"\"\n     * StringUtils.defaultString(\"bat\") = \"bat\"\n     * 
\n *\n * @see ObjectUtils#toString(Object)\n * @see String#valueOf(Object)\n * @param str the String to check, may be null\n * @return the passed in String, or the empty String if it\n * was null\n */\n public static String defaultString(final String str) {\n return str == null ? StringUtils.EMPTY : str;\n }\n\n /**\n *

Returns either the passed in String, or if the String is\n * null, the value of defaultStr.

\n *\n *
\n     * StringUtils.defaultString(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultString(\"\", \"NULL\")    = \"\"\n     * StringUtils.defaultString(\"bat\", \"NULL\") = \"bat\"\n     * 
\n *\n * @see ObjectUtils#toString(Object, String)\n * @see String#valueOf(Object)\n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is null, may be null\n * @return the passed in String, or the default if it was null\n */\n public static String defaultString(final String str, final String defaultStr) {\n return str == null ? defaultStr : str;\n }\n\n /**\n *

Returns either the passed in String, or if the String is\n * whitespace, empty (\"\") or null, the value of defaultStr.

\n *\n *
\n     * StringUtils.defaultIfBlank(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultIfBlank(\"\", \"NULL\")    = \"NULL\"\n     * StringUtils.defaultIfBlank(\" \", \"NULL\")   = \"NULL\"\n     * StringUtils.defaultIfBlank(\"bat\", \"NULL\") = \"bat\"\n     * StringUtils.defaultIfBlank(\"\", null)      = null\n     * 
\n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is whitespace, empty (\"\") or null, may be null\n * @return the passed in String, or the default\n * @see StringUtils#defaultString(String, String)\n * @since 2.6\n */\n public static String defaultIfBlank(final String str, final String defaultStr) {\n return StringUtils.isBlank(str) ? defaultStr : str;\n }\n\n /**\n *

Returns either the passed in String, or if the String is\n * empty or null, the value of defaultStr.

\n *\n *
\n     * StringUtils.defaultIfEmpty(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultIfEmpty(\"\", \"NULL\")    = \"NULL\"\n     * StringUtils.defaultIfEmpty(\"bat\", \"NULL\") = \"bat\"\n     * StringUtils.defaultIfEmpty(\"\", null)      = null\n     * 
\n *\n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is empty (\"\") or null, may be null\n * @return the passed in String, or the default\n * @see StringUtils#defaultString(String, String)\n */\n public static String defaultIfEmpty(final String str, final String defaultStr) {\n return StringUtils.isEmpty(str) ? defaultStr : str;\n }\n // Reversing\n //-----------------------------------------------------------------------\n\n /**\n *

Reverses a String as per {@link StringBuilder#reverse()}.

\n *\n *

A null String returns null.

\n *\n *
\n     * StringUtils.reverse(null)  = null\n     * StringUtils.reverse(\"\")    = \"\"\n     * StringUtils.reverse(\"bat\") = \"tab\"\n     * 
\n *\n * @param str the String to reverse, may be null\n * @return the reversed String, null if null String input\n */\n public static String reverse(final String str) {\n if (str == null) {\n return null;\n }\n return new StringBuilder(str).reverse().toString();\n }\n\n /**\n *

Reverses a String that is delimited by a specific character.

\n *\n *

The Strings between the delimiters are not reversed.\n * Thus java.lang.String becomes String.lang.java (if the delimiter\n * is '.').

\n *\n *
\n     * StringUtils.reverseDelimited(null, *)      = null\n     * StringUtils.reverseDelimited(\"\", *)        = \"\"\n     * StringUtils.reverseDelimited(\"a.b.c\", 'x') = \"a.b.c\"\n     * StringUtils.reverseDelimited(\"a.b.c\", \".\") = \"c.b.a\"\n     * 
\n *\n * @param str the String to reverse, may be null\n * @param separatorChar the separator character to use\n * @return the reversed String, null if null String input\n * @since 2.0\n */\n public static String reverseDelimited(final String str, final char separatorChar) {\n if (str == null) {\n return null;\n }\n // could implement manually, but simple way is to reuse other,\n // probably slower, methods.\n String[] strs = StringUtils.split(str, separatorChar);\n ArrayUtils.reverse(strs);\n return StringUtils.join(strs, separatorChar);\n }\n // Abbreviating\n //-----------------------------------------------------------------------\n\n /**\n *

Abbreviates a String using ellipses. This will turn\n * \"Now is the time for all good men\" into \"Now is the time for...\"

\n *\n *

Specifically:\n *

    \n *
  • If str is less than maxWidth characters\n * long, return it.
  • \n *
  • Else abbreviate it to (substring(str, 0, max-3) + \"...\").
  • \n *
  • If maxWidth is less than 4, throw an\n * IllegalArgumentException.
  • \n *
  • In no case will it return a String of length greater than\n * maxWidth.
  • \n *
\n *

\n *\n *
\n     * StringUtils.abbreviate(null, *)      = null\n     * StringUtils.abbreviate(\"\", 4)        = \"\"\n     * StringUtils.abbreviate(\"abcdefg\", 6) = \"abc...\"\n     * StringUtils.abbreviate(\"abcdefg\", 7) = \"abcdefg\"\n     * StringUtils.abbreviate(\"abcdefg\", 8) = \"abcdefg\"\n     * StringUtils.abbreviate(\"abcdefg\", 4) = \"a...\"\n     * StringUtils.abbreviate(\"abcdefg\", 3) = IllegalArgumentException\n     * 
\n *\n * @param str the String to check, may be null\n * @param maxWidth maximum length of result String, must be at least 4\n * @return abbreviated String, null if null String input\n * @throws IllegalArgumentException if the width is too small\n * @since 2.0\n */\n public static String abbreviate(final String str, final int maxWidth) {\n return StringUtils.abbreviate(str, 0, maxWidth);\n }\n\n /**\n *

Abbreviates a String using ellipses. This will turn\n * \"Now is the time for all good men\" into \"...is the time for...\"

\n *\n *

Works like abbreviate(String, int), but allows you to specify\n * a \"left edge\" offset. Note that this left edge is not necessarily going to\n * be the leftmost character in the result, or the first character following the\n * ellipses, but it will appear somewhere in the result.\n *\n *

In no case will it return a String of length greater than\n * maxWidth.

\n *\n *
\n     * StringUtils.abbreviate(null, *, *)                = null\n     * StringUtils.abbreviate(\"\", 0, 4)                  = \"\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", -1, 10) = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 0, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 1, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 4, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 5, 10)  = \"...fghi...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 6, 10)  = \"...ghij...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 8, 10)  = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 10, 10) = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 12, 10) = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghij\", 0, 3)        = IllegalArgumentException\n     * StringUtils.abbreviate(\"abcdefghij\", 5, 6)        = IllegalArgumentException\n     * 
\n *\n * @param str the String to check, may be null\n * @param offset left edge of source String\n * @param maxWidth maximum length of result String, must be at least 4\n * @return abbreviated String, null if null String input\n * @throws IllegalArgumentException if the width is too small\n * @since 2.0\n */\n public static String abbreviate(final String str, int offset, final int maxWidth) {\n if (str == null) {\n return null;\n }\n if (maxWidth < 4) {\n throw new IllegalArgumentException(\"Minimum abbreviation width is 4\");\n }\n if (str.length() <= maxWidth) {\n return str;\n }\n if (offset > str.length()) {\n offset = str.length();\n }\n if (str.length() - offset < maxWidth - 3) {\n offset = str.length() - (maxWidth - 3);\n }\n if (offset <= 4) {\n return str.substring(0, maxWidth - 3) + \"...\";\n }\n if (maxWidth < 7) {\n throw new IllegalArgumentException(\"Minimum abbreviation width with offset is 7\");\n }\n if (offset + maxWidth - 3 < str.length()) {\n return \"...\" + StringUtils.abbreviate(str.substring(offset), maxWidth - 3);\n }\n return \"...\" + str.substring(str.length() - (maxWidth - 3));\n }\n\n /**\n *

Abbreviates a String to the length passed, replacing the middle characters with the supplied\n * replacement String.

\n *\n *

This abbreviation only occurs if the following criteria is met:\n *

    \n *
  • Neither the String for abbreviation nor the replacement String are null or empty
  • \n *
  • The length to truncate to is less than the length of the supplied String
  • \n *
  • The length to truncate to is greater than 0
  • \n *
  • The abbreviated String will have enough room for the length supplied replacement String\n * and the first and last characters of the supplied String for abbreviation
  • \n *
\n * Otherwise, the returned String will be the same as the supplied String for abbreviation.\n *

\n *\n *
\n     * StringUtils.abbreviateMiddle(null, null, 0)      = null\n     * StringUtils.abbreviateMiddle(\"abc\", null, 0)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abc\", \".\", 0)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abc\", \".\", 3)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abcdef\", \".\", 4)     = \"ab.f\"\n     * 
\n *\n * @param str the String to abbreviate, may be null\n * @param middle the String to replace the middle characters with, may be null\n * @param length the length to abbreviate str to.\n * @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation.\n * @since 2.5\n */\n public static String abbreviateMiddle(final String str, final String middle, final int length) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(middle)) {\n return str;\n }\n if (length >= str.length() || length < middle.length() + 2) {\n return str;\n }\n int targetSting = length - middle.length();\n int startOffset = targetSting / 2 + targetSting % 2;\n int endOffset = str.length() - targetSting / 2;\n return str.substring(0, startOffset) + middle + str.substring(endOffset);\n }\n // Difference\n //-----------------------------------------------------------------------\n\n /**\n *

Compares two Strings, and returns the portion where they differ.\n * (More precisely, return the remainder of the second String,\n * starting from where it's different from the first.)

\n *\n *

For example,\n * difference(\"i am a machine\", \"i am a robot\") -> \"robot\".

\n *\n *
\n     * StringUtils.difference(null, null) = null\n     * StringUtils.difference(\"\", \"\") = \"\"\n     * StringUtils.difference(\"\", \"abc\") = \"abc\"\n     * StringUtils.difference(\"abc\", \"\") = \"\"\n     * StringUtils.difference(\"abc\", \"abc\") = \"\"\n     * StringUtils.difference(\"ab\", \"abxyz\") = \"xyz\"\n     * StringUtils.difference(\"abcde\", \"abxyz\") = \"xyz\"\n     * StringUtils.difference(\"abcde\", \"xyz\") = \"xyz\"\n     * 
\n *\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return the portion of str2 where it differs from str1; returns the\n * empty String if they are equal\n * @since 2.0\n */\n public static String difference(final String str1, final String str2) {\n if (str1 == null) {\n return str2;\n }\n if (str2 == null) {\n return str1;\n }\n int at = StringUtils.indexOfDifference(str1, str2);\n if (at == StringUtils.INDEX_NOT_FOUND) {\n return StringUtils.EMPTY;\n }\n return str2.substring(at);\n }\n\n /**\n *

Compares two Strings, and returns the index at which the\n * Strings begin to differ.

\n *\n *

For example,\n * indexOfDifference(\"i am a machine\", \"i am a robot\") -> 7

\n *\n *
\n     * StringUtils.indexOfDifference(null, null) = -1\n     * StringUtils.indexOfDifference(\"\", \"\") = -1\n     * StringUtils.indexOfDifference(\"\", \"abc\") = 0\n     * StringUtils.indexOfDifference(\"abc\", \"\") = 0\n     * StringUtils.indexOfDifference(\"abc\", \"abc\") = -1\n     * StringUtils.indexOfDifference(\"ab\", \"abxyz\") = 2\n     * StringUtils.indexOfDifference(\"abcde\", \"abxyz\") = 2\n     * StringUtils.indexOfDifference(\"abcde\", \"xyz\") = 0\n     * 
\n *\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return the index where str2 and str1 begin to differ; -1 if they are equal\n * @since 2.0\n */\n public static int indexOfDifference(final String str1, final String str2) {\n if (str1 != null && str1.equals(str2)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (str1 == null || str2 == null) {\n return 0;\n }\n int i;\n for (i = 0; i < str1.length() && i < str2.length(); ++i) {\n if (str1.charAt(i) != str2.charAt(i)) {\n break;\n }\n }\n if (i < str2.length() || i < str1.length()) {\n return i;\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

Compares all Strings in an array and returns the index at which the\n * Strings begin to differ.

\n *\n *

For example,\n * indexOfDifference(new String[] {\"i am a machine\", \"i am a robot\"}) -> 7

\n *\n *
\n     * StringUtils.indexOfDifference(null) = -1\n     * StringUtils.indexOfDifference(new String[] {}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"abc\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {null, null}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"\", \"\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"\", null}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", null, null}) = 0\n     * StringUtils.indexOfDifference(new String[] {null, null, \"abc\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"\", \"abc\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"abc\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"a\"}) = 1\n     * StringUtils.indexOfDifference(new String[] {\"ab\", \"abxyz\"}) = 2\n     * StringUtils.indexOfDifference(new String[] {\"abcde\", \"abxyz\"}) = 2\n     * StringUtils.indexOfDifference(new String[] {\"abcde\", \"xyz\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"xyz\", \"abcde\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"i am a machine\", \"i am a robot\"}) = 7\n     * 
\n *\n * @param strs array of strings, entries may be null\n * @return the index where the strings begin to differ; -1 if they are all equal\n * @since 2.4\n */\n public static int indexOfDifference(final String[] strs) {\n if (strs == null || strs.length <= 1) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n boolean anyStringNull = false;\n boolean allStringsNull = true;\n int arrayLen = strs.length;\n int shortestStrLen = Integer.MAX_VALUE;\n int longestStrLen = 0;\n // find the min and max string lengths; this avoids checking to make\n // sure we are not exceeding the length of the string each time through\n // the bottom loop.\n for (int i = 0; i < arrayLen; i++) {\n if (strs[i] == null) {\n anyStringNull = true;\n shortestStrLen = 0;\n } else {\n allStringsNull = false;\n shortestStrLen = Math.min(strs[i].length(), shortestStrLen);\n longestStrLen = Math.max(strs[i].length(), longestStrLen);\n }\n }\n // handle lists containing all nulls or all empty strings\n if (allStringsNull || longestStrLen == 0 && !anyStringNull) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n // handle lists containing some nulls or some empty strings\n if (shortestStrLen == 0) {\n return 0;\n }\n // find the position with the first difference across all strings\n int firstDiff = -1;\n for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {\n char comparisonChar = strs[0].charAt(stringPos);\n for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {\n if (strs[arrayPos].charAt(stringPos) != comparisonChar) {\n firstDiff = stringPos;\n break;\n }\n }\n if (firstDiff != -1) {\n break;\n }\n }\n if (firstDiff == -1 && shortestStrLen != longestStrLen) {\n // we compared all of the characters up to the length of the\n // shortest string and didn't find a match, but the string lengths\n // vary, so return the length of the shortest string.\n return shortestStrLen;\n }\n return firstDiff;\n }\n\n /**\n *

Compares all Strings in an array and returns the initial sequence of\n * characters that is common to all of them.

\n *\n *

For example,\n * getCommonPrefix(new String[] {\"i am a machine\", \"i am a robot\"}) -> \"i am a \"

\n *\n *
\n     * StringUtils.getCommonPrefix(null) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\"}) = \"abc\"\n     * StringUtils.getCommonPrefix(new String[] {null, null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", \"\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", null, null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {null, null, \"abc\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", \"abc\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"abc\"}) = \"abc\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"a\"}) = \"a\"\n     * StringUtils.getCommonPrefix(new String[] {\"ab\", \"abxyz\"}) = \"ab\"\n     * StringUtils.getCommonPrefix(new String[] {\"abcde\", \"abxyz\"}) = \"ab\"\n     * StringUtils.getCommonPrefix(new String[] {\"abcde\", \"xyz\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"xyz\", \"abcde\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"i am a machine\", \"i am a robot\"}) = \"i am a \"\n     * 
\n *\n * @param strs array of String objects, entries may be null\n * @return the initial sequence of characters that are common to all Strings\n * in the array; empty String if the array is null, the elements are all null\n * or if there is no common prefix.\n * @since 2.4\n */\n public static String getCommonPrefix(final String[] strs) {\n if (strs == null || strs.length == 0) {\n return StringUtils.EMPTY;\n }\n int smallestIndexOfDiff = StringUtils.indexOfDifference(strs);\n if (smallestIndexOfDiff == StringUtils.INDEX_NOT_FOUND) {\n // all strings were identical\n if (strs[0] == null) {\n return StringUtils.EMPTY;\n }\n return strs[0];\n } else if (smallestIndexOfDiff == 0) {\n // there were no common initial characters\n return StringUtils.EMPTY;\n } else {\n // we found a common initial character sequence\n return strs[0].substring(0, smallestIndexOfDiff);\n }\n }\n // Misc\n //-----------------------------------------------------------------------\n\n /**\n *

Find the Levenshtein distance between two Strings.

\n *\n *

This is the number of changes needed to change one String into\n * another, where each change is a single character modification (deletion,\n * insertion or substitution).

\n *\n *

The previous implementation of the Levenshtein distance algorithm\n * was from http://www.merriampark.com/ld.htm

\n *\n *

Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError\n * which can occur when my Java implementation is used with very large strings.
\n * This implementation of the Levenshtein distance algorithm\n * is from http://www.merriampark.com/ldjava.htm

\n *\n *
\n     * StringUtils.getLevenshteinDistance(null, *)             = IllegalArgumentException\n     * StringUtils.getLevenshteinDistance(*, null)             = IllegalArgumentException\n     * StringUtils.getLevenshteinDistance(\"\",\"\")               = 0\n     * StringUtils.getLevenshteinDistance(\"\",\"a\")              = 1\n     * StringUtils.getLevenshteinDistance(\"aaapppp\", \"\")       = 7\n     * StringUtils.getLevenshteinDistance(\"frog\", \"fog\")       = 1\n     * StringUtils.getLevenshteinDistance(\"fly\", \"ant\")        = 3\n     * StringUtils.getLevenshteinDistance(\"elephant\", \"hippo\") = 7\n     * StringUtils.getLevenshteinDistance(\"hippo\", \"elephant\") = 7\n     * StringUtils.getLevenshteinDistance(\"hippo\", \"zzzzzzzz\") = 8\n     * StringUtils.getLevenshteinDistance(\"hello\", \"hallo\")    = 1\n     * 
\n *\n * @param s the first String, must not be null\n * @param t the second String, must not be null\n * @return result distance\n * @throws IllegalArgumentException if either String input null\n */\n public static int getLevenshteinDistance(String s, String t) {\n if (s == null || t == null) {\n throw new IllegalArgumentException(\"Strings must not be null\");\n }\n /*\n The difference between this impl. and the previous is that, rather\n than creating and retaining a matrix of size s.length()+1 by t.length()+1,\n we maintain two single-dimensional arrays of length s.length()+1. The first, d,\n is the 'current working' distance array that maintains the newest distance cost\n counts as we iterate through the characters of String s. Each time we increment\n the index of String t we are comparing, d is copied to p, the second int[]. Doing so\n allows us to retain the previous cost counts as required by the algorithm (taking\n the minimum of the cost count to the left, up one, and diagonally up and to the left\n of the current cost count being calculated). (Note that the arrays aren't really\n copied anymore, just switched...this is clearly much better than cloning an array\n or doing a System.arraycopy() each time through the outer loop.)\n\n Effectively, the difference between the two implementations is this one does not\n cause an out of memory condition when calculating the LD over two very large strings.\n */\n int n = s.length(); // length of s\n int m = t.length(); // length of t\n if (n == 0) {\n return m;\n } else if (m == 0) {\n return n;\n }\n if (n > m) {\n // swap the input strings to consume less memory\n String tmp = s;\n s = t;\n t = tmp;\n n = m;\n m = t.length();\n }\n int[] p = new int[n + 1]; //'previous' cost array, horizontally\n int[] d = new int[n + 1]; // cost array, horizontally\n int[] _d; //placeholder to assist in swapping p and d\n // indexes into strings s and t\n int i; // iterates through s\n int j; // iterates through t\n char t_j; // jth character of t\n int cost; // cost\n for (i = 0; i <= n; i++) {\n p[i] = i;\n }\n for (j = 1; j <= m; j++) {\n t_j = t.charAt(j - 1);\n d[0] = j;\n for (i = 1; i <= n; i++) {\n cost = s.charAt(i - 1) == t_j ? 0 : 1;\n // minimum of cell to the left+1, to the top+1, diagonally left and up +cost\n d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);\n }\n // copy current distance counts to 'previous row' distance counts\n _d = p;\n p = d;\n d = _d;\n }\n // our last action in the above loop was to switch d and p, so p now\n // actually has the most recent cost counts\n return p[n];\n }\n // startsWith\n //-----------------------------------------------------------------------\n\n /**\n *

Check if a String starts with a specified prefix.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

\n *\n *
\n     * StringUtils.startsWith(null, null)      = true\n     * StringUtils.startsWith(null, \"abc\")     = false\n     * StringUtils.startsWith(\"abcdef\", null)  = false\n     * StringUtils.startsWith(\"abcdef\", \"abc\") = true\n     * StringUtils.startsWith(\"ABCDEF\", \"abc\") = false\n     * 
\n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @return true if the String starts with the prefix, case sensitive, or\n * both null\n * @since 2.4\n */\n public static boolean startsWith(final String str, final String prefix) {\n return StringUtils.startsWith(str, prefix, false);\n }\n\n /**\n *

Case insensitive check if a String starts with a specified prefix.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case insensitive.

\n *\n *
\n     * StringUtils.startsWithIgnoreCase(null, null)      = true\n     * StringUtils.startsWithIgnoreCase(null, \"abc\")     = false\n     * StringUtils.startsWithIgnoreCase(\"abcdef\", null)  = false\n     * StringUtils.startsWithIgnoreCase(\"abcdef\", \"abc\") = true\n     * StringUtils.startsWithIgnoreCase(\"ABCDEF\", \"abc\") = true\n     * 
\n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @return true if the String starts with the prefix, case insensitive, or\n * both null\n * @since 2.4\n */\n public static boolean startsWithIgnoreCase(final String str, final String prefix) {\n return StringUtils.startsWith(str, prefix, true);\n }\n\n /**\n *

Check if a String starts with a specified prefix (optionally case insensitive).

\n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @param ignoreCase inidicates whether the compare should ignore case\n * (case insensitive) or not.\n * @return true if the String starts with the prefix or\n * both null\n */\n private static boolean startsWith(final String str, final String prefix, final boolean ignoreCase) {\n if (str == null || prefix == null) {\n return str == null && prefix == null;\n }\n if (prefix.length() > str.length()) {\n return false;\n }\n return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());\n }\n\n /**\n *

Check if a String starts with any of an array of specified strings.

\n *\n *
\n     * StringUtils.startsWithAny(null, null)      = false\n     * StringUtils.startsWithAny(null, new String[] {\"abc\"})  = false\n     * StringUtils.startsWithAny(\"abcxyz\", null)     = false\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {\"\"}) = false\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {\"abc\"}) = true\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {null, \"xyz\", \"abc\"}) = true\n     * 
\n *\n * @see #startsWith(String, String)\n * @param string the String to check, may be null\n * @param searchStrings the Strings to find, may be null or empty\n * @return true if the String starts with any of the the prefixes, case insensitive, or\n * both null\n * @since 2.5\n */\n public static boolean startsWithAny(final String string, final String[] searchStrings) {\n if (StringUtils.isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {\n return false;\n }\n for (String searchString : searchStrings) {\n if (StringUtils.startsWith(string, searchString)) {\n return true;\n }\n }\n return false;\n }\n // endsWith\n //-----------------------------------------------------------------------\n\n /**\n *

Check if a String ends with a specified suffix.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

\n *\n *
\n     * StringUtils.endsWith(null, null)      = true\n     * StringUtils.endsWith(null, \"def\")     = false\n     * StringUtils.endsWith(\"abcdef\", null)  = false\n     * StringUtils.endsWith(\"abcdef\", \"def\") = true\n     * StringUtils.endsWith(\"ABCDEF\", \"def\") = false\n     * StringUtils.endsWith(\"ABCDEF\", \"cde\") = false\n     * 
\n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @return true if the String ends with the suffix, case sensitive, or\n * both null\n * @since 2.4\n */\n public static boolean endsWith(final String str, final String suffix) {\n return StringUtils.endsWith(str, suffix, false);\n }\n\n /**\n *

Case insensitive check if a String ends with a specified suffix.

\n *\n *

nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case insensitive.

\n *\n *
\n     * StringUtils.endsWithIgnoreCase(null, null)      = true\n     * StringUtils.endsWithIgnoreCase(null, \"def\")     = false\n     * StringUtils.endsWithIgnoreCase(\"abcdef\", null)  = false\n     * StringUtils.endsWithIgnoreCase(\"abcdef\", \"def\") = true\n     * StringUtils.endsWithIgnoreCase(\"ABCDEF\", \"def\") = true\n     * StringUtils.endsWithIgnoreCase(\"ABCDEF\", \"cde\") = false\n     * 
\n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @return true if the String ends with the suffix, case insensitive, or\n * both null\n * @since 2.4\n */\n public static boolean endsWithIgnoreCase(final String str, final String suffix) {\n return StringUtils.endsWith(str, suffix, true);\n }\n\n /**\n *

Check if a String ends with a specified suffix (optionally case insensitive).

\n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @param ignoreCase inidicates whether the compare should ignore case\n * (case insensitive) or not.\n * @return true if the String starts with the prefix or\n * both null\n */\n private static boolean endsWith(final String str, final String suffix, final boolean ignoreCase) {\n if (str == null || suffix == null) {\n return str == null && suffix == null;\n }\n if (suffix.length() > str.length()) {\n return false;\n }\n int strOffset = str.length() - suffix.length();\n return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());\n }\n\n /**\n *

\n * Similar to http://www.w3.org/TR/xpath/#function-normalize\n * -space\n *

\n *

\n * The function returns the argument string with whitespace normalized by using\n * {@link #trim(String)} to remove leading and trailing whitespace\n * and then replacing sequences of whitespace characters by a single space.\n *

\n * In XML Whitespace characters are the same as those allowed by the S production, which is S ::= (#x20 | #x9 | #xD | #xA)+\n *

\n * See Java's {@link Character#isWhitespace(char)} for which characters are considered whitespace.\n *

\n * The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also\n * normalize. Additonally {@link #trim(String)} removes control characters (char <= 32) from both\n * ends of this String.\n *

\n *\n * @see Character#isWhitespace(char)\n * @see #trim(String)\n * @see \n * http://www.w3.org/TR/xpath/#function-normalize-space\n * @param str the source String to normalize whitespaces from, may be null\n * @return the modified string with whitespace normalized, null if null String input\n *\n * @since 2.6\n */\n public static String normalizeSpace(String str) {\n str = StringUtils.strip(str);\n if (str == null || str.length() <= 2) {\n return str;\n }\n StringBuilder b = new StringBuilder(str.length());\n for (int i = 0; i < str.length(); i++) {\n char c = str.charAt(i);\n if (Character.isWhitespace(c)) {\n if (i > 0 && !Character.isWhitespace(str.charAt(i - 1))) {\n b.append(' ');\n }\n } else {\n b.append(c);\n }\n }\n return b.toString();\n }\n\n /**\n *

Check if a String ends with any of an array of specified strings.

\n *\n *
\n     * StringUtils.endsWithAny(null, null)      = false\n     * StringUtils.endsWithAny(null, new String[] {\"abc\"})  = false\n     * StringUtils.endsWithAny(\"abcxyz\", null)     = false\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {\"\"}) = true\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {\"xyz\"}) = true\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {null, \"xyz\", \"abc\"}) = true\n     * 
\n *\n * @param string the String to check, may be null\n * @param searchStrings the Strings to find, may be null or empty\n * @return true if the String ends with any of the the prefixes, case insensitive, or\n * both null\n * @since 2.6\n */\n public static boolean endsWithAny(final String string, final String[] searchStrings) {\n if (StringUtils.isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {\n return false;\n }\n for (String searchString : searchStrings) {\n if (StringUtils.endsWith(string, searchString)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 转换首字母大写。\n *
\n     * StringUtils.firstCharToUpperCase(null)      = null\n     * StringUtils.firstCharToUpperCase(\"\")        = \"\"\n     * StringUtils.firstCharToUpperCase(\"abc\")     = \"Abc\"\n     * StringUtils.firstCharToUpperCase(\"Abc\")     = \"Abc\"\n     * StringUtils.firstCharToUpperCase(\"ABC\")     = \"ABC\"\n     * 
\n */\n public static String firstCharToUpperCase(final String value) {\n if (StringUtils.isBlank(value)) {\n return value;\n }\n StringBuilder sb = new StringBuilder(value);\n char firstChar = sb.charAt(0);\n sb.delete(0, 1);\n sb.insert(0, (char) (firstChar >= 97 ? firstChar - 32 : firstChar));\n return sb.toString();\n }\n\n /**\n * 转换首字母小写。\n *
\n     * StringUtils.firstCharToLowerCase(null)      = null\n     * StringUtils.firstCharToLowerCase(\"\")        = \"\"\n     * StringUtils.firstCharToLowerCase(\"abc\")     = \"abc\"\n     * StringUtils.firstCharToLowerCase(\"Abc\")     = \"abc\"\n     * StringUtils.firstCharToLowerCase(\"ABC\")     = \"aBC\"\n     * 
\n */\n public static String firstCharToLowerCase(final String value) {\n if (StringUtils.isBlank(value)) {\n return value;\n }\n StringBuilder sb = new StringBuilder(value);\n char firstChar = sb.charAt(0);\n sb.delete(0, 1);\n sb.insert(0, (char) (firstChar <= 90 ? firstChar + 32 : firstChar));\n return sb.toString();\n }\n\n /**\n * 执行字符串匹配。\n *
\n     * StringUtils.equalsBlankIgnoreCase(null,\"\")         = true\n     * StringUtils.equalsBlankIgnoreCase(\"\",\"\")           = true\n     * StringUtils.equalsBlankIgnoreCase(\" \",\"\")          = true\n     * StringUtils.equalsBlankIgnoreCase(\" \",null)        = true\n     * StringUtils.equalsBlankIgnoreCase(\"bob\",\"\")        = false\n     * StringUtils.equalsBlankIgnoreCase(\"  bob  \",\"bob\") = true\n     * 
\n */\n public static boolean equalsBlankIgnoreCase(final String str1, final String str2) {\n return StringUtils.equalsIgnoreCase(StringUtils.trimToEmpty(str1), StringUtils.trimToEmpty(str2));\n }\n\n /* ------------------------------------------------------------ */\n private static final char[] escapes = new char[32];\n\n static {\n Arrays.fill(escapes, (char) 0xFFFF);\n escapes['\\b'] = 'b';\n escapes['\\t'] = 't';\n escapes['\\n'] = 'n';\n escapes['\\f'] = 'f';\n escapes['\\r'] = 'r';\n }\n\n /** Quote a string into an Appendable.\n * The characters \", \\, \\n, \\r, \\t, \\f and \\b are escaped\n * @param input The String to quote.\n */\n public static String quote(String input) {\n StringBuilder buffer = new StringBuilder();\n quote(buffer, input);\n return buffer.toString();\n }\n\n public static void quote(Appendable buffer, String input) {\n try {\n buffer.append('\"');\n for (int i = 0; i < input.length(); ++i) {\n char c = input.charAt(i);\n if (c >= 32) {\n if (c == '\"' || c == '\\\\')\n buffer.append('\\\\');\n buffer.append(c);\n } else {\n char escape = escapes[c];\n if (escape == 0xFFFF) {\n // Unicode escape\n buffer.append('\\\\').append('u').append('0').append('0');\n if (c < 0x10)\n buffer.append('0');\n buffer.append(Integer.toString(c, 16));\n } else {\n buffer.append('\\\\').append(escape);\n }\n }\n }\n buffer.append('\"');\n } catch (IOException x) {\n throw new RuntimeException(x);\n }\n }\n\n /** Object to String ,when null object then null else return toString(); */\n public static String toString(Object object) {\n return (object == null) ? null : object.toString();\n }\n}", "file_name": "StringUtils.java", "human_label": "Convert object to string if the object is not null. Otherwise, null is returned.", "level": "self_contained", "lineno": "6133", "name": "toString", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636767581a6d9265ec017fc4", "all_context": "{ \"class_level\" : \"log2(int n);\\n\", \"repo_level\" : \"\" }", "class_name": "MathUtil", "code": "public static long factorial(int n){\n long multi=1;\n for (int i=1; i <= n; i++) {\n multi=multi * i;\n }\n return multi;\n}\n", "docstring": "/** \n * Calculate the factorial of $n$.\n * @param n the input number\n * @return the factorial\n */\n", "end_lineno": "41", "file_content": "/*\n * (C) Copyright 2005-2021, by Assaf Lehr and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.util;\n\n/**\n * Math Utilities.\n * \n * @author Assaf Lehr\n */\npublic class MathUtil\n{\n\n /**\n * Calculate the factorial of $n$.\n * \n * @param n the input number\n * @return the factorial\n */\n public static long factorial(int n)\n {\n long multi = 1;\n for (int i = 1; i <= n; i++) {\n multi = multi * i;\n }\n return multi;\n }\n\n /**\n * Calculate the floor of the binary logarithm of $n$.\n *\n * @param n the input number\n * @return the binary logarithm\n */\n public static int log2(int n)\n {\n // returns 0 for n=0\n int log = 0;\n if ((n & 0xffff0000) != 0) {\n n >>>= 16;\n log = 16;\n }\n if (n >= 256) {\n n >>>= 8;\n log += 8;\n }\n if (n >= 16) {\n n >>>= 4;\n log += 4;\n }\n if (n >= 4) {\n n >>>= 2;\n log += 2;\n }\n return log + (n >>> 1);\n }\n}\n", "file_name": "MathUtil.java", "human_label": "Calculate the factorial of the given number.", "level": "self_contained", "lineno": "28", "name": "factorial", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "org.jgrapht.util", "project": "jgrapht-master" }, { "_id": "636767511a6d9265ec017eb6", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.alg.interfaces.*;\\nimport org.jgrapht.alg.util.*;\\nimport org.jgrapht.graph.*;\\nimport org.jgrapht.util.*;\\nimport java.lang.reflect.*;\\nimport java.util.*;\\nimport java.util.function.*;\\nboolean DEBUG;\\nboolean PRINT_CASES;\\nGraph graph;\\nint n;\\nEmbedding embedding;\\nGraph kuratowskiSubdivision;\\nList nodes;\\nList dfsTreeRoots;\\nList componentRoots;\\nList stack;\\nNode failedV;\\nboolean tested;\\nboolean planar;\\nNode current;\\nEdge prevEdge;\\nboolean backtrack;\\nV current;\\nV parent;\\nE parentEdge;\\nNode parent;\\nNode parentNext;\\nNode child;\\nNode childPrev;\\nint vIn;\\nint vOut;\\nNode prev;\\nE graphEdge;\\nNode source;\\nNode target;\\nint sign;\\nboolean embedded;\\nboolean shortCircuit;\\nV graphVertex;\\nboolean rootVertex;\\nint dfsIndex;\\nint height;\\nint lowpoint;\\nint leastAncestor;\\nint visited;\\nint backEdgeFlag;\\nint boundaryHeight;\\nboolean marked;\\nEdge parentEdge;\\nEdge edgeToEmbed;\\nNode initialComponentRoot;\\nNode[] outerFaceNeighbors;\\nDoublyLinkedList separatedDfsChildList;\\nDoublyLinkedList pertinentRoots;\\nList treeEdges;\\nList downEdges;\\nList backEdges;\\nDoublyLinkedList.ListNode listNode;\\nDoublyLinkedList embedded;\\nBoyerMyrvoldPlanarityInspector(Graph graph);\\norientDfs(Map vertexMap,V startGraphVertex,int currentDfsIndex);\\norient();\\nsortVertices();\\nlazyTestPlanarity();\\nmergeBiconnectedComponent();\\nembedBackEdge(Node root,int entryDir,Edge edge,Node childPrev);\\nembedShortCircuit(Node componentRoot,int entryDir,OuterFaceCirculator circulator);\\nwalkDown(Node componentRoot);\\nwalkUp(Node start,Node end,Edge edge);\\nlazyComputeEmbedding();\\nprintBiconnectedComponent(Node node);\\nprintState();\\nselectOnOuterFace(Predicate predicate,Node start,Node stop,int dir);\\ngetActiveSuccessorOnOuterFace(Node start,Node v,int dir);\\ngetExternallyActiveSuccessorOnOuterFace(Node start,Node stop,Node v,int dir);\\ngetComponentRoot(Node node);\\naddPathEdges(Set edges,Edge startEdge,Node stop);\\naddPathEdges(Set edges,Node start,Node stop);\\nsearchEdge(Node current,int heightMax);\\nsearchEdge(Node current,int heightMax,Edge forbiddenEdge);\\nsearchEdge(Node current,Predicate isNeeded);\\nsearchSubtreeDfs(Node start,Predicate isNeeded);\\nhighest(Node a,Node b);\\nlowest(Node a,Node b);\\nsetBoundaryDepth(Node componentRoot,Node w,int dir,int delta);\\nclearVisited();\\nfindPathDfs(Node start,Edge startPrev,Predicate canGo,Predicate isFinish,List edges);\\nfindHighestObstructingPath(Node componentRoot,Node w);\\nfinish(Set subdivision);\\naddBoundaryEdges(Set edges,Node componentRoot);\\nkuratowskiCleanUp();\\ncleanUpDfs(Node dfsTreeRoot);\\nfixBoundaryOrder(Node componentRoot);\\nremoveUp(Node start,Node end,int dir,Set edges);\\ngetNextOnPath(Node w,Edge backEdge);\\nfindPathToV(List path,Node v);\\nfirstStrictlyHigher(Node a,Node b,Node c);\\ncheckComponentForFailedEdge(Node componentRoot,Node v);\\nfindFailedEdge(Node v);\\nlazyExtractKuratowskiSubdivision();\\nisPlanar();\\ngetEmbedding();\\ngetKuratowskiSubdivision();\\nSearchInfo(Node current,Edge prevEdge,boolean backtrack);\\nOrientDfsStackInfo(V current,V parent,E parentEdge,boolean backtrack);\\nMergeInfo(Node parent,Node parentNext,Node child,Node childPrev,int vIn,int vOut);\\nisInverted();\\ntoString();\\nOuterFaceCirculator(Node current,Node prev);\\nhasNext();\\nnext();\\nedgeToNext();\\ngetCurrent();\\ngetPrev();\\ntoExistingNode(Node node);\\nEdge(Node source,Node target);\\nEdge(E graphEdge,Node source);\\nEdge(E graphEdge,Node source,Node target);\\nisIncidentTo(Node node);\\ngetOpposite(Node node);\\nNode(V graphVertex,int dfsIndex,int height,Node initialComponentRoot,Edge parentEdge);\\nNode(int dfsIndex,Edge parentEdge);\\nNode(V graphVertex,int dfsIndex,Edge parentEdge,boolean rootVertex);\\nisVisitedWrtTo(Node node);\\nisPertinentWrtTo(Node node);\\nhasBackEdgeWrtTo(Node node);\\nisExternallyActiveWrtTo(Node node);\\nisRootVertex();\\nisInternallyActiveWrtTo(Node node);\\nisInactiveWrtTo(Node node);\\nisActiveWrtTo(Node node);\\niterator(int direction);\\nremoveShortCircuitEdges();\\ngetParent();\\ncheckIsAdjacent(Node node);\\nswapNeighbors();\\nsubstitute(Node node,Node newNeighbor);\\nsubstituteAnother(Node node,Node newNeighbor);\\nhasRootNeighbor();\\nnextOnOuterFace(Node prev);\\nembedBackEdge(Edge edge,Node prev);\\nmergeChildEdges(DoublyLinkedList edges,int vIn,int vOut,Node parentNext,Edge parentEdge);\\ntoString(boolean full);\\ncreateNewNode(Map vertexMap,V graphVertex,E edge,Node parent,int dfsIndex);\\n\", \"repo_level\" : \"\" }", "class_name": "BoyerMyrvoldPlanarityInspector", "code": "private OuterFaceCirculator selectOnOuterFace(Predicate predicate,Node start,Node stop,int dir){\n OuterFaceCirculator circulator=start.iterator(dir);\n Node current=circulator.next();\n while (current != stop && !predicate.test(current)) {\n current=circulator.next();\n }\n return circulator;\n}\n", "docstring": "/** \n * Either finds and returns a circulator to the node on the boundary of the component, which satisfies the {@code predicate} or returns a circulator to the {@code stop} node.\n * @param predicate the condition the desired node should satisfy\n * @param start the node to start the search from\n * @param stop the node to end the search with\n * @param dir the direction to start the traversal in\n * @return a circulator to the node satisfying the {@code predicate} or to the {@code stop} node\n */\n", "end_lineno": "687", "file_content": "/*\n * (C) Copyright 2018-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.planar;\n\nimport org.jgrapht.*;\nimport org.jgrapht.alg.interfaces.*;\nimport org.jgrapht.alg.util.*;\nimport org.jgrapht.graph.*;\nimport org.jgrapht.util.*;\n\nimport java.lang.reflect.*;\nimport java.util.*;\nimport java.util.function.*;\n\n/**\n * An implementation of the Boyer-Myrvold planarity testing algorithm. This class determines whether\n * an input graph is planar or not. If the graph is planar, the algorithm provides a\n * combinatorial\n * embedding of the graph, which is represented as a clockwise ordering of the edges of the\n * graph. Otherwise, the algorithm provides a\n * Kuratowski\n * subgraph as a certificate. Both embedding of the graph and Kuratowski subdivision are\n * computed lazily, meaning that the call to the {@link BoyerMyrvoldPlanarityInspector#isPlanar()}\n * does spend time only on the planarity testing. All of the operations of this algorithm (testing,\n * embedding and Kuratowski subgraph extraction) run in linear time.\n *

\n * A planar graph is a graph, which can be\n * drawn in two-dimensional space without any of its edges crossing. According to the\n * Kuratowski theorem, a graph is\n * planar if and only if it doesn't contain a subdivision of the $K_{3,3}$ or $K_{5}$ graphs.\n *

\n * The Boyer-Myrvold planarity testing algorithm was originally described in: Boyer, John amp;\n * Myrvold, Wendy. (2004). On the Cutting Edge: Simplified O(n) Planarity by Edge Addition. J. Graph\n * Algorithms Appl.. 8. 241-273. 10.7155/jgaa.00091. . We refer to this paper for the complete\n * description of the Boyer-Myrvold algorithm\n *\n * @param the graph vertex type\n * @param the graph edge type\n * @author Timofey Chudakov\n */\npublic class BoyerMyrvoldPlanarityInspector\n implements\n PlanarityTestingAlgorithm\n{\n /**\n * Whether to print debug messages\n */\n private static final boolean DEBUG = false;\n /**\n * Whether to print Kuratowski case distinction messages\n */\n private static final boolean PRINT_CASES = false;\n /**\n * The graph we're testing planarity of\n */\n private Graph graph;\n /**\n * The number of vertices in the {@code graph}\n */\n private int n;\n /**\n * The resulting combinatorial embedding. This value is computed only after the first call to\n * the {@link BoyerMyrvoldPlanarityInspector#getEmbedding()}\n */\n private Embedding embedding;\n /**\n * The subgraph of the {@code graph}, which is a Kuratowski subdivision. This subgraph certifies\n * the nonplanarity of the graph.\n */\n private Graph kuratowskiSubdivision;\n /**\n * List of the vertices of the {@code graph} in their internal representation. After the\n * orientation of the {@code graph} and edge sorting, nodes in this list are sorted according to\n * their dfs indexes\n */\n private List nodes;\n /**\n * List of the dfs tree roots of the {@code graph}. This list has length more than 1 if the\n * input {@code graph} isn't connected\n */\n private List dfsTreeRoots;\n /**\n * List of the virtual biconnected component roots. Initially, a virtual biconnected component\n * root is created for every node in the {@code graph}, except for the dfs roots. These\n * component roots don't belong to the {@code graph}. At each step of the algorithm, every\n * biconnected component has its own unique component root.\n */\n private List componentRoots;\n /**\n * The stack containing merge information for every consecutive pair of biconnected components\n * on the path to the back edge source. After all the biconnected components are merged, this\n * stack is cleared\n */\n private List stack;\n /**\n * The node $v$, which has an unembedded back edge incident to it.\n */\n private Node failedV;\n /**\n * Whether the planarity of the {@code graph} has been tested already\n */\n private boolean tested;\n /**\n * Whether the graph is planar or not. Is valid, if {@code tested} is {@code true}\n */\n private boolean planar;\n\n /**\n * Creates new instance of the planarity testing algorithm for the {@code graph}. The input\n * graph can't be null.\n *\n * @param graph the graph to test the planarity of\n */\n public BoyerMyrvoldPlanarityInspector(Graph graph)\n {\n this.graph = Objects.requireNonNull(graph, \"Graph can't be null\");\n this.n = graph.vertexSet().size();\n this.nodes = new ArrayList<>(n);\n this.dfsTreeRoots = new ArrayList<>();\n this.componentRoots = new ArrayList<>(n);\n this.stack = new ArrayList<>();\n }\n\n /**\n * Creates a new node by converting the {@code graphVertex} to the internal node representation.\n *\n * @param vertexMap the map from vertices of the {@code graph} to their internal representation\n * @param graphVertex the vertex of the {@code graph} we're processing\n * @param edge the parent edge of the {@code graphVertex}, is {@code null} for dfs tree roots\n * @param parent the parent node of the {@code graphVertex}\n * @param dfsIndex the dfs index of the {@code graphVertex}\n * @return the newly created node\n */\n private Node createNewNode(\n Map vertexMap, V graphVertex, E edge, Node parent, int dfsIndex)\n {\n Node child;\n if (parent == null) {\n child = new Node(graphVertex, dfsIndex, 0, null, null);\n child.outerFaceNeighbors[0] = child.outerFaceNeighbors[1] = child;\n dfsTreeRoots.add(child);\n } else {\n Edge treeEdge = new Edge(edge, parent);\n Node componentRoot = new Node(parent.dfsIndex, treeEdge);\n child = new Node(graphVertex, dfsIndex, parent.height + 1, componentRoot, treeEdge);\n treeEdge.target = child;\n\n componentRoots.add(componentRoot);\n\n parent.treeEdges.add(treeEdge);\n\n child.outerFaceNeighbors[0] = child.outerFaceNeighbors[1] = componentRoot;\n componentRoot.outerFaceNeighbors[0] = componentRoot.outerFaceNeighbors[1] = child;\n }\n nodes.add(child);\n vertexMap.put(graphVertex, child);\n return child;\n }\n\n /**\n * Orients the input graph according to its dfs traversal by creating a dfs tree. Computes the\n * least ancestors and lowpoints of the nodes\n *\n * @param vertexMap the map from {@code graph} vertices to their internal representatives\n * @param startGraphVertex the node to start the traversal from (this is a dfs tree root).\n * @param currentDfsIndex the dfs index of the {@code startGraphVertex}\n * @return the {@code currentDfsIndex} + number of nodes in the traversed subtree\n */\n private int orientDfs(Map vertexMap, V startGraphVertex, int currentDfsIndex)\n {\n List stack = new ArrayList<>();\n stack.add(new OrientDfsStackInfo(startGraphVertex, null, null, false));\n while (!stack.isEmpty()) {\n OrientDfsStackInfo info = stack.remove(stack.size() - 1);\n\n if (info.backtrack) {\n Node current = vertexMap.get(info.current);\n current.leastAncestor = current.lowpoint = current.dfsIndex;\n for (Edge backEdge : current.backEdges) {\n current.leastAncestor =\n Math.min(current.leastAncestor, backEdge.target.dfsIndex);\n }\n for (Edge treeEdge : current.treeEdges) {\n current.lowpoint = Math.min(current.lowpoint, treeEdge.target.lowpoint);\n }\n current.lowpoint = Math.min(current.lowpoint, current.leastAncestor);\n } else {\n if (vertexMap.containsKey(info.current)) {\n // other dfs branch has reached this vertex earlier\n continue;\n }\n stack.add(new OrientDfsStackInfo(info.current, info.parent, info.parentEdge, true));\n Node current = createNewNode(\n vertexMap, info.current, info.parentEdge, vertexMap.get(info.parent),\n currentDfsIndex);\n ++currentDfsIndex;\n for (E e : graph.edgesOf(info.current)) {\n V opposite = Graphs.getOppositeVertex(graph, e, info.current);\n if (vertexMap.containsKey(opposite)) {\n // back edge or parent edge\n Node oppositeNode = vertexMap.get(opposite);\n if (opposite.equals(info.parent)) {\n continue;\n }\n Edge backEdge = new Edge(e, current, oppositeNode);\n oppositeNode.downEdges.add(backEdge);\n current.backEdges.add(backEdge);\n } else {\n // possible tree edge\n stack.add(new OrientDfsStackInfo(opposite, current.graphVertex, e, false));\n }\n }\n }\n }\n return currentDfsIndex;\n }\n\n /**\n * Iteratively start an orienting dfs from every {@code graph} vertex that hasn't been visited\n * yet. After orienting the graph, sorts the nodes by their lowpoints and adds them to the\n * {@code separatedDfsChildList}\n */\n private void orient()\n {\n Map visited = new HashMap<>();\n int currentDfsIndex = 0;\n for (V vertex : graph.vertexSet()) {\n if (!visited.containsKey(vertex)) {\n currentDfsIndex = orientDfs(visited, vertex, currentDfsIndex);\n }\n }\n sortVertices();\n }\n\n /**\n * Performs sorting of the vertices by their lowpoints and adding them to the\n * {@code separatedDfsChildList}\n */\n private void sortVertices()\n {\n List> sorted = new ArrayList<>(Collections.nCopies(n, null));\n for (Node node : nodes) {\n int lowpoint = node.lowpoint;\n if (sorted.get(lowpoint) == null) {\n sorted.set(lowpoint, new ArrayList<>());\n }\n sorted.get(lowpoint).add(node);\n }\n int i = 0;\n for (List list : sorted) {\n if (i >= n) {\n break;\n }\n if (list != null) {\n for (Node node : list) {\n nodes.set(i++, node);\n if (node.parentEdge != null) {\n node.listNode =\n node.parentEdge.source.separatedDfsChildList.addElementLast(node);\n }\n }\n }\n }\n }\n\n /**\n * Lazily tests the planarity of the graph. The implementation below is close to the code\n * presented in the original paper\n *\n * @return true if the graph is planar, false otherwise\n */\n private boolean lazyTestPlanarity()\n {\n if (!tested) {\n tested = true;\n\n orient();\n if (DEBUG) {\n printState();\n System.out.println(\"Start testing planarity\");\n }\n for (int currentNode = n - 1; currentNode >= 0; currentNode--) {\n Node current = nodes.get(currentNode);\n if (DEBUG) {\n System.out.printf(\"Current vertex is %s\\n\", current.toString(false));\n }\n for (Edge downEdge : current.downEdges) {\n walkUp(downEdge.source, current, downEdge);\n }\n for (Edge treeEdge : current.treeEdges) {\n walkDown(treeEdge.target.initialComponentRoot);\n }\n\n for (Edge downEdge : current.downEdges) {\n if (!downEdge.embedded) {\n failedV = current;\n return planar = false;\n }\n }\n }\n planar = true;\n }\n return planar;\n }\n\n /**\n * Merges the last two biconnected components using the info stored on top of the stack. The key\n * goal of this method is to merge the outer faces of the two components and to merge the\n * embedded edges of the child component root with the embedded edges of the component parent\n * node.\n */\n private void mergeBiconnectedComponent()\n {\n MergeInfo info = stack.get(stack.size() - 1);\n stack.remove(stack.size() - 1);\n if (DEBUG) {\n System.out.printf(\"\\nMerging biconnected component, info: %s\\n\", info.toString());\n }\n Node virtualRoot = info.child;\n if (info.isInverted()) {\n virtualRoot.swapNeighbors();\n }\n Node root = info.parent;\n Node virtualRootChild = virtualRoot.parentEdge.target;\n\n root.pertinentRoots.removeNode(virtualRoot.listNode);\n root.separatedDfsChildList.removeNode(virtualRootChild.listNode);\n\n root\n .mergeChildEdges(\n virtualRoot.embedded, info.vIn, info.vOut, info.parentNext, virtualRoot.parentEdge);\n\n root.substituteAnother(info.parentNext, info.childPrev);\n info.childPrev.substitute(virtualRoot, root);\n virtualRoot.outerFaceNeighbors[0] = virtualRoot.outerFaceNeighbors[1] = null;\n }\n\n /**\n * Embeds the back edge {@code edge} into the list of embedded edges of the source and the\n * virtual target of the edge such that the {@code childPrev} belongs to the new inner face.\n * This method also takes care of modifying the boundary of the outer face accordingly\n *\n * @param root the component root\n * @param entryDir the component entry direction\n * @param edge the edge to embed\n * @param childPrev the neighbor of the source of the edge that should belong to the inner face\n * @return a circulator starting from the edge's source\n */\n private OuterFaceCirculator embedBackEdge(Node root, int entryDir, Edge edge, Node childPrev)\n {\n if (DEBUG) {\n System.out.printf(\"Embedding back edge %s\\n\", edge.toString());\n }\n assert !edge.embedded;\n if (entryDir == 0) {\n root.embedded.addLast(edge);\n } else {\n root.embedded.addFirst(edge);\n }\n Node child = edge.source;\n child.embedBackEdge(edge, childPrev);\n child.edgeToEmbed = null;\n child.backEdgeFlag = n;\n edge.embedded = true;\n\n child.substitute(childPrev, root);\n root.outerFaceNeighbors[entryDir] = child;\n Node next = child.nextOnOuterFace(root);\n return new OuterFaceCirculator(next, child);\n }\n\n /**\n * Embeds a short-circuit edge from the {@code componentRoot} to the current node of the\n * {@code circulator}. Changes the outer face accordingly\n *\n * @param componentRoot the component root\n * @param entryDir the direction used to enter the component\n * @param circulator a circulator to the source of the new edge\n */\n private void embedShortCircuit(Node componentRoot, int entryDir, OuterFaceCirculator circulator)\n {\n Node current = circulator.getCurrent(), prev = circulator.getPrev();\n Edge shortCircuit = new Edge(current, componentRoot.getParent());\n if (entryDir == 0) {\n componentRoot.embedded.addLast(shortCircuit);\n componentRoot.outerFaceNeighbors[0] = current;\n } else {\n componentRoot.embedded.addFirst(shortCircuit);\n componentRoot.outerFaceNeighbors[1] = current;\n }\n current.embedBackEdge(shortCircuit, prev);\n current.substitute(prev, componentRoot);\n if (DEBUG) {\n System.out.printf(\"Embedding short circuit edge: %s\\n\", shortCircuit.toString());\n printState();\n }\n }\n\n /**\n * The walkdown procedure from the original paper. Either embeds all of the back edges in the\n * subtree rooted at the child of the {@code componentRoot} or identifies the back edges which\n * can be used to extract a Kuratowski subdivision. Iteratively traverses the tree of the\n * biconnected component and descends only to the pertinent components. This procedure is also\n * responsible for embedding short-circuit edges to make the algorithm run in linear time in the\n * worst case.\n *\n * @param componentRoot the root of the component to start the walkdown from\n */\n private void walkDown(Node componentRoot)\n {\n if (DEBUG) {\n System.out.printf(\"\\nStart walk down on node %s\\n\", componentRoot.toString(true));\n }\n for (int componentEntryDir = 0; componentEntryDir < 2 && stack.isEmpty();\n componentEntryDir++)\n {\n if (DEBUG) {\n System.out.println(\"\\nNew traversal direction = \" + componentEntryDir);\n }\n int currentComponentEntryDir = componentEntryDir;\n OuterFaceCirculator circulator = componentRoot.iterator(currentComponentEntryDir);\n for (Node current = circulator.next(); current != componentRoot;) {\n if (DEBUG) {\n System.out.printf(\"Current = %s\\n\", current.toString());\n }\n if (current.hasBackEdgeWrtTo(componentRoot)) {\n Node childPrev = circulator.getPrev();\n while (!stack.isEmpty()) {\n mergeBiconnectedComponent();\n if (DEBUG) {\n printState();\n }\n }\n circulator = embedBackEdge(\n componentRoot, componentEntryDir, current.edgeToEmbed, childPrev);\n if (DEBUG) {\n printState();\n printBiconnectedComponent(current);\n }\n }\n if (!current.pertinentRoots.isEmpty()) {\n int parentComponentEntryDir = currentComponentEntryDir;\n Node root = current.pertinentRoots.getFirst();\n\n if (DEBUG) {\n System.out.printf(\"Descending to the root = %s\\n\", root.toString());\n }\n OuterFaceCirculator ccwCirculator =\n getActiveSuccessorOnOuterFace(root, componentRoot, 0);\n Node ccwActiveNode = ccwCirculator.getCurrent();\n OuterFaceCirculator cwCirculator =\n getActiveSuccessorOnOuterFace(root, componentRoot, 1);\n Node cwActiveNode = cwCirculator.getCurrent();\n\n if (ccwActiveNode.isInternallyActiveWrtTo(componentRoot)) {\n currentComponentEntryDir = 0;\n } else if (cwActiveNode.isInternallyActiveWrtTo(componentRoot)) {\n currentComponentEntryDir = 1;\n } else if (ccwActiveNode.isPertinentWrtTo(componentRoot)) {\n currentComponentEntryDir = 0;\n } else {\n currentComponentEntryDir = 1;\n }\n\n if (currentComponentEntryDir == 0) {\n stack\n .add(\n new MergeInfo(\n current, circulator.next(), root, root.outerFaceNeighbors[1],\n parentComponentEntryDir, currentComponentEntryDir));\n current = ccwActiveNode;\n circulator = ccwCirculator;\n\n if (!cwActiveNode.hasRootNeighbor()) {\n embedShortCircuit(root, 1, cwCirculator);\n }\n } else {\n stack\n .add(\n new MergeInfo(\n current, circulator.next(), root, root.outerFaceNeighbors[0],\n parentComponentEntryDir, currentComponentEntryDir));\n current = cwActiveNode;\n circulator = cwCirculator;\n\n if (!ccwActiveNode.hasRootNeighbor()) {\n embedShortCircuit(root, 0, ccwCirculator);\n }\n }\n\n } else if (current.isInactiveWrtTo(componentRoot)) {\n current = circulator.next();\n } else {\n // current vertex is externally active\n if (DEBUG) {\n System.out.println(\"Current vertex is externally active, stop\\n\");\n }\n if (!current.hasRootNeighbor() && stack.isEmpty()) {\n embedShortCircuit(componentRoot, componentEntryDir, circulator);\n }\n break;\n }\n }\n }\n }\n\n /**\n * The walkup procedure from the original paper. Identifies the pertinent subgraph of the graph\n * by going up the dfs tree from the {@code start} node to the {@code end} node using the edge\n * {@code edge}\n *\n * @param start the node to start the walkup from\n * @param end the node currently processed by the main loop of the algorithm\n * @param edge a back edge to embed\n */\n private void walkUp(Node start, Node end, Edge edge)\n {\n if (DEBUG) {\n System.out.printf(\"\\nStart walk up on edge = %s\\n\", edge.toString());\n }\n int visited = end.dfsIndex;\n\n start.backEdgeFlag = visited;\n start.edgeToEmbed = edge;\n\n Node x = start.outerFaceNeighbors[0], y = start.outerFaceNeighbors[1], xPrev = start,\n yPrev = start;\n start.visited = visited;\n while (x != end && !x.isVisitedWrtTo(end) && !y.isVisitedWrtTo(end)) {\n if (DEBUG) {\n System.out.printf(\"Current x = %s\\nCurrent y = %s\\n\", x.toString(), y.toString());\n }\n x.visited = y.visited = visited;\n\n Node root = null;\n if (x.isRootVertex()) {\n root = x;\n } else if (y.isRootVertex()) {\n root = y;\n }\n if (root != null) {\n if (DEBUG) {\n System.out.printf(\"Found root = %s\\n\", root.toString());\n }\n Node rootChild = root.parentEdge.target;\n Node newStart = root.parentEdge.source;\n if (newStart != end) {\n if (rootChild.lowpoint < end.dfsIndex) {\n // the component in externally active\n root.listNode = newStart.pertinentRoots.addElementLast(root);\n } else {\n // the component is internally active\n root.listNode = newStart.pertinentRoots.addElementFirst(root);\n }\n } else {\n break;\n }\n newStart.visited = visited;\n xPrev = yPrev = newStart;\n x = newStart.outerFaceNeighbors[0];\n y = newStart.outerFaceNeighbors[1];\n\n } else {\n Node t = x;\n x = x.nextOnOuterFace(xPrev);\n xPrev = t;\n\n t = y;\n y = y.nextOnOuterFace(yPrev);\n yPrev = t;\n }\n }\n }\n\n /**\n * Lazily computes a combinatorial embedding of the {@code graph} by removing all the\n * short-circuit edges and properly orienting the edges around the nodes.\n *\n * @return a combinatorial embedding of the {@code graph}\n */\n private Embedding lazyComputeEmbedding()\n {\n lazyTestPlanarity();\n if (!planar) {\n throw new IllegalArgumentException(\n \"Input graph is not planar, can't compute graph embedding\");\n }\n if (embedding == null) {\n for (Node dfsTreeRoot : dfsTreeRoots) {\n cleanUpDfs(dfsTreeRoot);\n }\n Map> embeddingMap = new HashMap<>();\n for (Node node : nodes) {\n for (Node child : node.separatedDfsChildList) {\n Node virtualRoot = child.initialComponentRoot;\n node.embedded.append(virtualRoot.embedded);\n }\n List embeddedEdges = new ArrayList<>(node.embedded.size());\n for (Edge edge : node.embedded) {\n embeddedEdges.add(edge.graphEdge);\n }\n embeddingMap.put(node.graphVertex, embeddedEdges);\n }\n embedding = new EmbeddingImpl<>(graph, embeddingMap);\n }\n return embedding;\n }\n\n /**\n * Method for debug purposes, prints the boundary the {@code node} belongs to\n *\n * @param node a node on the outer face\n */\n private void printBiconnectedComponent(Node node)\n {\n StringBuilder builder = new StringBuilder(node.toString(false));\n OuterFaceCirculator circulator = node.iterator(0);\n Node current = circulator.next();\n Node stop = current;\n do {\n builder.append(\" -> \").append(current.toString(false));\n current = circulator.next();\n } while (current != stop);\n System.out.println(\"Biconnected component after merge: \" + builder.toString());\n }\n\n /**\n * Method for debug purposes, prints the state of the algorithm\n */\n private void printState()\n {\n System.out.println(\"\\nPrinting state:\");\n System.out.println(\"Dfs roots: \" + dfsTreeRoots);\n System.out.println(\"Nodes:\");\n for (Node node : nodes) {\n System.out.println(node.toString(true));\n }\n System.out.println(\"Virtual nodes:\");\n for (Node node : componentRoots) {\n System.out.println(node.toString(true));\n }\n List inverted = new ArrayList<>();\n for (Node node : nodes) {\n for (Edge edge : node.treeEdges) {\n if (edge.sign < 0) {\n inverted.add(edge);\n }\n }\n }\n System.out.println(\"Inverted edges = \" + inverted);\n }\n\n /**\n * Either finds and returns a circulator to the node on the boundary of the component, which\n * satisfies the {@code predicate} or returns a circulator to the {@code stop} node.\n *\n * @param predicate the condition the desired node should satisfy\n * @param start the node to start the search from\n * @param stop the node to end the search with\n * @param dir the direction to start the traversal in\n * @return a circulator to the node satisfying the {@code predicate} or to the {@code stop} node\n */\n private OuterFaceCirculator selectOnOuterFace(\n Predicate predicate, Node start, Node stop, int dir)\n {\n OuterFaceCirculator circulator = start.iterator(dir);\n Node current = circulator.next();\n while (current != stop && !predicate.test(current)) {\n current = circulator.next();\n }\n return circulator;\n }\n\n /**\n * Returns an active node on the outer face in the direction {@code dir} starting from the\n * {@code start} node\n *\n * @param start the node to start the search from\n * @param v an ancestor of the {@code start}\n * @param dir the direction of the search\n * @return a circulator to the found node\n */\n private OuterFaceCirculator getActiveSuccessorOnOuterFace(Node start, Node v, int dir)\n {\n return selectOnOuterFace(n -> n.isActiveWrtTo(v), start, start, dir);\n }\n\n /**\n * Returns acirculator to the externally active node on the outer face between the {@code start}\n * and {@code end} nodes in the direction {@code dir}.\n *\n * @param start the node to start the search from\n * @param stop the node to end the search with\n * @param v an ancestor of the {@code start} and the {@code end}\n * @param dir the direction of the search\n * @return a circulator to the found node\n */\n private OuterFaceCirculator getExternallyActiveSuccessorOnOuterFace(\n Node start, Node stop, Node v, int dir)\n {\n return selectOnOuterFace(n -> n.isExternallyActiveWrtTo(v), start, stop, dir);\n }\n\n /**\n * Returns a component root of component the {@code node} is contained in.\n *\n * @param node a node in the partially embedded graph\n * @return a component root of the component the {@code node} belongs to\n */\n private Node getComponentRoot(Node node)\n {\n return selectOnOuterFace(Node::isRootVertex, node, node, 0).getCurrent();\n }\n\n /**\n * Adds the edges on the path from the {@code startEdge} up to the node {@code stop} to the set\n * {@code edges}\n *\n * @param edges the set to add the path edges to\n * @param startEdge the edge to start from\n * @param stop the last node on the path\n */\n private void addPathEdges(Set edges, Edge startEdge, Node stop)\n {\n edges.add(startEdge);\n Node current = startEdge.source;\n while (current != stop) {\n edges.add(current.parentEdge);\n current = current.getParent();\n }\n }\n\n /**\n * Adds the edges between the {@code start} and the {@code end} to the set {@code edges}\n *\n * @param edges the set to add the path edges to to\n * @param start the node to start from\n * @param stop the node to end with\n */\n private void addPathEdges(Set edges, Node start, Node stop)\n {\n if (start != stop) {\n addPathEdges(edges, start.parentEdge, stop);\n }\n }\n\n /**\n * Searches a back edge which target has a height smaller than {@code heightMax}\n *\n * @param current the node to start from\n * @param heightMax an upper bound on the height of the desired back edge\n * @return the desired back edge or null, if no such edge exist\n */\n private Edge searchEdge(Node current, int heightMax)\n {\n return searchEdge(current, heightMax, null);\n }\n\n /**\n * Searches a back edge which target has a height smaller than {@code heightMax}\n *\n * @param current the node to start from\n * @param heightMax an upper bound on the height of the desired back edge\n * @param forbiddenEdge an edge the desired edge should not be equal to\n * @return the desired back edge or null, if no such edge exist\n */\n private Edge searchEdge(Node current, int heightMax, Edge forbiddenEdge)\n {\n Predicate isNeeded = e -> {\n if (forbiddenEdge == e) {\n return false;\n }\n return e.target.height < heightMax;\n };\n return searchEdge(current, isNeeded);\n }\n\n /**\n * Generically searches an edge in the subtree rooted at the {@code current}, which doesn't\n * include the children of the {@code current} that have beem merged to the parent biconnected\n * component.\n *\n * @param current the node to start the searh from\n * @param isNeeded the predicate which the desired edge should satisfy\n * @return an edge which satisfies the {@code predicate}, or null if such an edge doesn't exist\n */\n private Edge searchEdge(Node current, Predicate isNeeded)\n {\n for (Node node : current.separatedDfsChildList) {\n Edge result = searchSubtreeDfs(node, isNeeded);\n if (result != null) {\n return result;\n }\n }\n for (Edge edge : current.backEdges) {\n if (isNeeded.test(edge)) {\n return edge;\n }\n }\n return null;\n }\n\n /**\n * Recursively searches all the subtree root at the node {@code start} to find an edge\n * satisfying the {@code predicate}.\n *\n * @param start the node to start the search from.\n * @param isNeeded a predicate, which the desired edge should satisfy\n * @return a desired edge, or null if no such edge exist.\n */\n private Edge searchSubtreeDfs(Node start, Predicate isNeeded)\n {\n List stack = new ArrayList<>();\n stack.add(start);\n while (!stack.isEmpty()) {\n Node current = stack.remove(stack.size() - 1);\n\n for (Edge edge : current.backEdges) {\n if (isNeeded.test(edge)) {\n return edge;\n }\n }\n for (Edge edge : current.treeEdges) {\n stack.add(edge.target);\n }\n }\n return null;\n }\n\n /**\n * Returns the highest of the two input node, i.e. the node with the greater height\n *\n * @param a a node in the dfs tree\n * @param b a node in the dfs tree\n * @return the highest of the two nodes\n */\n private Node highest(Node a, Node b)\n {\n return a.height > b.height ? a : b;\n }\n\n /**\n * Returns the lowest of the two input node, i.e. the node with the least height.\n *\n * @param a a node in the dfs tree\n * @param b a node in the dfs tree\n * @return the lowest of the two nodes\n */\n private Node lowest(Node a, Node b)\n {\n return a.height < b.height ? a : b;\n }\n\n /**\n * Iteratively sets a boundary height for the nodes on the outer face branch ending at the node\n * {@code w}.\n *\n * @param componentRoot the root of the component\n * @param w the end of the outer face branch\n * @param dir the direction to start the traversal in\n * @param delta a value in $\\{+1, -1\\}$ to set either positive or negative boundary height\n */\n private void setBoundaryDepth(Node componentRoot, Node w, int dir, int delta)\n {\n OuterFaceCirculator circulator = componentRoot.iterator(dir);\n Node current = circulator.next();\n int currentHeight = delta;\n while (current != w) {\n current.boundaryHeight = currentHeight;\n currentHeight += delta;\n current = circulator.next();\n }\n }\n\n /**\n * Clears the visited variable of all the nodes and component roots\n */\n private void clearVisited()\n {\n nodes.forEach(n -> n.visited = 0);\n componentRoots.forEach(n -> n.visited = 0);\n }\n\n /**\n * Generically searches a path from the {@code current} node to the first node satisfying the\n * {@code isFinish} predicate consisting of all the nodes satisfying the {@code canGo}\n * predicate. The key property of this method is that it searches the next edge on the path in\n * the clockwise order starting from the previous edge. The edges of the resulting path are\n * added to the {@code edges}.\n *\n * @param start the start node of the traversal\n * @param startPrev the previous edge of the start node\n * @param canGo specifies where the search can go\n * @param isFinish specifies what nodes are finish nodes\n * @param edges the list containing the resulting path\n * @return true if the search was successful, false otherwise\n */\n private boolean findPathDfs(\n Node start, Edge startPrev, Predicate canGo, Predicate isFinish,\n List edges)\n {\n List stack = new ArrayList<>();\n stack.add(new SearchInfo(start, startPrev, false));\n while (!stack.isEmpty()) {\n SearchInfo info = stack.remove(stack.size() - 1);\n if (isFinish.test(info.current)) {\n edges.add(info.prevEdge);\n edges.remove(0);\n return true;\n }\n if (info.backtrack) {\n edges.remove(edges.size() - 1);\n } else {\n if (info.current.visited != 0) {\n continue;\n }\n info.current.visited = 1;\n stack.add(new SearchInfo(info.current, info.prevEdge, true));\n edges.add(info.prevEdge);\n /*\n * The iteration is performed in the reverse order since the infos are pushed on the\n * stack and therefore will be processed in the again reverse order\n */\n Iterator iterator =\n info.current.embedded.reverseCircularIterator(info.prevEdge);\n while (iterator.hasNext()) {\n Edge currentEdge = iterator.next();\n Node opposite = currentEdge.getOpposite(info.current);\n if ((!canGo.test(opposite) || opposite.visited != 0)\n && !isFinish.test(opposite))\n {\n continue;\n }\n stack.add(new SearchInfo(opposite, currentEdge, false));\n }\n }\n }\n return false;\n }\n\n /**\n * Finds the highest obstructing path in the component rooted at {@code componentRoot}. See the\n * original paper for the definition of the obstructing path. This method heavily relies on the\n * fact that the method\n * {@link BoyerMyrvoldPlanarityInspector#findPathDfs(Node, Edge, Predicate, Predicate, List)}\n * chooses the edges in the clockwise order.\n *\n * @param componentRoot the root of the component\n * @param w the node called {@code w} in the Kuratowski subdivision extraction phase.\n * @return the edges of the desired path as a list\n */\n private List findHighestObstructingPath(Node componentRoot, Node w)\n {\n clearVisited();\n List result = new ArrayList<>();\n OuterFaceCirculator circulator = componentRoot.iterator(0);\n Node current = circulator.next();\n while (current != w) {\n if (findPathDfs(\n current, current.embedded.getFirst(), n -> !n.marked, n -> n.boundaryHeight < 0,\n result))\n {\n return result;\n }\n current = circulator.next();\n }\n return result;\n }\n\n /**\n * Finishes the Kuratowski subdivision extraction by constructing the desired subgraph\n *\n * @param subdivision the edges in the Kuratowski subdivision\n * @return the Kuratowski subgraph of the {@code graph}\n */\n private Graph finish(Set subdivision)\n {\n Set edgeSubset = new HashSet<>();\n Set vertexSubset = new HashSet<>();\n subdivision.forEach(e -> {\n edgeSubset.add(e.graphEdge);\n vertexSubset.add(e.target.graphVertex);\n vertexSubset.add(e.source.graphVertex);\n });\n kuratowskiSubdivision = new AsSubgraph<>(graph, vertexSubset, edgeSubset);\n return kuratowskiSubdivision;\n }\n\n /**\n * Adds the edges on the outer face of the component rooted at {@code componentRoot} to the set\n * {@code edges}\n *\n * @param edges the set to add the edges to\n * @param componentRoot the root of the biconnected component\n */\n private void addBoundaryEdges(Set edges, Node componentRoot)\n {\n OuterFaceCirculator circulator = componentRoot.iterator(0);\n Node current;\n do {\n Edge edge = circulator.edgeToNext();\n edge.source.marked = edge.target.marked = true;\n edges.add(edge);\n current = circulator.next();\n } while (current != componentRoot);\n }\n\n /**\n * Cleans up the dfs trees before the Kuratowski subdivision extraction phase\n */\n private void kuratowskiCleanUp()\n {\n for (Node dfsTreeRoot : dfsTreeRoots) {\n cleanUpDfs(dfsTreeRoot);\n }\n for (Node node : componentRoots) {\n if (node.outerFaceNeighbors[0] != null) {\n node.removeShortCircuitEdges();\n fixBoundaryOrder(node);\n }\n }\n }\n\n /**\n * Recursively cleans up the dfs tree rooted at the {@code dfsTreeRoot} my removing all the\n * short-circuit edges and properly orienting other embedded edges\n *\n * @param dfsTreeRoot the root of the dfs tree to clean up\n */\n private void cleanUpDfs(Node dfsTreeRoot)\n {\n List> stack = new ArrayList<>();\n stack.add(Pair.of(dfsTreeRoot, 1));\n while (!stack.isEmpty()) {\n Pair entry = stack.remove(stack.size() - 1);\n Node current = entry.getFirst();\n int sign = entry.getSecond();\n if (sign < 0) {\n current.embedded.invert();\n }\n current.removeShortCircuitEdges();\n for (Node node : current.separatedDfsChildList) {\n // all the components, that aren't merged, aren't inverted\n node.parentEdge.sign = sign;\n }\n\n for (Edge treeEdge : current.treeEdges) {\n stack.add(Pair.of(treeEdge.target, sign * treeEdge.sign));\n }\n }\n\n }\n\n /**\n * Orient the connections on the outer face of the component rooted at {@code componentRoot}\n * such that they are ordered\n *\n * @param componentRoot the root of the component to process\n */\n private void fixBoundaryOrder(Node componentRoot)\n {\n if (componentRoot.embedded.size() < 2) {\n return;\n }\n Node componentParent = componentRoot.getParent();\n Edge edgeToNext = componentRoot.embedded.getLast(),\n edgeToPrev = componentRoot.embedded.getFirst();\n Node next = edgeToNext.getOpposite(componentParent),\n prev = edgeToPrev.getOpposite(componentParent);\n\n componentRoot.outerFaceNeighbors[0] = next;\n componentRoot.outerFaceNeighbors[1] = prev;\n next.outerFaceNeighbors[1] = componentRoot;\n prev.outerFaceNeighbors[0] = componentRoot;\n Node current = componentRoot.outerFaceNeighbors[0];\n do {\n edgeToNext = current.embedded.getLast();\n edgeToPrev = current.embedded.getFirst();\n next = edgeToNext.getOpposite(current);\n prev = edgeToPrev.getOpposite(current);\n if (prev != componentParent) {\n current.outerFaceNeighbors[1] = prev;\n }\n if (next != componentParent) {\n current.outerFaceNeighbors[0] = next;\n }\n current = next;\n } while (current != componentParent);\n }\n\n /**\n * Removes the edges from the outer face from the {@code start} node to the {@code end} node in\n * the direction {@code dir} from the set {@code edges}\n *\n * @param start the start of the boundary path\n * @param end the end of the boundary path\n * @param dir the direction to take from the {@code start} node\n * @param edges the set of edges to modify\n */\n private void removeUp(Node start, Node end, int dir, Set edges)\n {\n if (start == end) {\n return;\n }\n OuterFaceCirculator circulator = start.iterator(dir);\n Node next;\n do {\n Edge edge = circulator.edgeToNext();\n edges.remove(edge);\n next = circulator.next();\n } while (next != end);\n }\n\n /**\n * Effectively is a method for finding node {@code z} in the notations of the original paper.\n * The search proceeds in the reverse order of the path from the {@code backEdge} to the node\n * {@code w}\n *\n * @param w the start of the path down\n * @param backEdge the last edge on the path\n * @return the desired node {@code z} or null if the source of the {@code backEdge} is equal to\n * {@code w}\n */\n private Node getNextOnPath(Node w, Edge backEdge)\n {\n if (backEdge.source == w) {\n return null;\n }\n Node prev = backEdge.source, current = backEdge.source.getParent();\n while (current != w) {\n prev = current;\n current = current.getParent();\n }\n return prev;\n }\n\n /**\n * Finds a path from some intermediate nodes on the path represented by the list {@code path} to\n * the node {@code v}. The path to {@code v} certainly doesn't exist if the list {@code path}\n * has size 1, because we're looking for a path from some intermediate node\n *\n * @param path the path between left and right outer face branches\n * @param v the parent of the biconnected component\n * @return the path edges in a list, which can be empty\n */\n private List findPathToV(List path, Node v)\n {\n clearVisited();\n int i = 0;\n Edge currentEdge = path.get(i);\n Node current =\n currentEdge.source.boundaryHeight != 0 ? currentEdge.target : currentEdge.source;\n List result = new ArrayList<>();\n while (i < path.size() - 1) {\n if (findPathDfs(current, currentEdge, n -> !n.marked, n -> n == v, result)) {\n return result;\n }\n ++i;\n currentEdge = path.get(i);\n current = currentEdge.getOpposite(current);\n }\n return result;\n }\n\n /**\n * Checks whether the first node {@code a} is strictly higher than nodes {@code b} and {@code c}\n *\n * @param a a node in the dfs tree\n * @param b a node in the dfs tree\n * @param c a node in the dfs tree\n * @return true if the first node in strictly higher that other node, false otherwise\n */\n private boolean firstStrictlyHigher(Node a, Node b, Node c)\n {\n return a.height > b.height && a.height > c.height;\n }\n\n /**\n * Checks whether the biconnected component rooted at {@code componentRoot} can be used to\n * extract a Kuratowski subdivision. It can be used in the case there is one externally active\n * node on each branch of the outer face and there is a pertinent node on the lower part of the\n * outer face between these two externally active nodes.\n *\n * @param componentRoot the root of the biconnected component\n * @param v an ancestor of the nodes in the biconnected component\n * @return an unembedded back edge, which target is {@code v} and which can be used to extract a\n * Kuratowski subdivision, or {@code null} is no such edge exist for this biconnected\n * component\n */\n private Edge checkComponentForFailedEdge(Node componentRoot, Node v)\n {\n OuterFaceCirculator firstDir =\n getExternallyActiveSuccessorOnOuterFace(componentRoot, componentRoot, v, 0);\n Node firstDirNode = firstDir.getCurrent();\n OuterFaceCirculator secondDir =\n getExternallyActiveSuccessorOnOuterFace(componentRoot, componentRoot, v, 1);\n Node secondDirNode = secondDir.getCurrent();\n if (firstDirNode != componentRoot && firstDirNode != secondDirNode) {\n Node current = firstDir.next();\n while (current != secondDirNode) {\n if (current.isPertinentWrtTo(v)) {\n return searchEdge(current, e -> e.target == v && !e.embedded);\n }\n current = firstDir.next();\n }\n }\n return null;\n }\n\n /**\n * Finds an unembedded back edge to {@code v}, which can be used to extract the Kuratowski\n * subdivision. If the merge stack isn't empty, the last biconnected component processed by the\n * walkdown can be used to find such an edge, because walkdown descended to that component\n * (which means that component is pertinent) and couldn't reach a pertinent node. This can only\n * happen by encountering externally active nodes on both branches of the traversal. Otherwise,\n * be have look in all the child biconnected components to find an unembedded back edge. We're\n * guided by the fact that an edge can not be embedded only in the case both traversals of the\n * walkdown could reach all off the pertinent nodes. This in turn can happen only if both\n * traversals get stuck on externally active nodes.\n *

\n * Note: not every unembedded back edge can be used to extract a Kuratowski subdivision\n *\n * @param v the vertex which has an unembedded back edge incident to it\n * @return the found unembedded back edge which can be used to extract a Kuratowski subdivision\n */\n private Edge findFailedEdge(Node v)\n {\n if (stack.isEmpty()) {\n for (Node child : v.separatedDfsChildList) {\n Node componentRoot = child.initialComponentRoot;\n Edge result = checkComponentForFailedEdge(componentRoot, v);\n if (result != null) {\n return result;\n }\n }\n return null; // should not happen in case node v has an incident unembedded back edge\n } else {\n MergeInfo info = stack.get(stack.size() - 1);\n return checkComponentForFailedEdge(info.child, v);\n }\n }\n\n /**\n * Lazily extracts a Kuratowski subdivision from the {@code graph}. The process of adding the\n * edges of the subdivision to the resulting set of edges had been made explicit for every case.\n *\n * @return a Kuratowski subgraph of the {@code graph}\n */\n private Graph lazyExtractKuratowskiSubdivision()\n {\n if (kuratowskiSubdivision == null) {\n // remove short-circuit edges and orient all embedded lists clockwise\n kuratowskiCleanUp();\n if (DEBUG) {\n printState();\n }\n Set subdivision = new HashSet<>();\n // find the needed unembedded back edge which can be used to find Kuratowski subgraph\n Edge failedEdge = findFailedEdge(failedV);\n assert failedEdge != null;\n /*\n * We're iteratively moving up traversing the outer faces of the biconnected components\n * to find externally active nodes x and y, which are on different branches of the outer\n * face. The way we're finding the nodes x and y helps us eliminate the case E_1\n * described in the original paper. This can be done because we always find the closest\n * to the node w externally active nodes x and y.\n */\n Node x, y, v = failedEdge.target, w = failedEdge.source, componentRoot;\n while (true) {\n componentRoot = getComponentRoot(w);\n x = getExternallyActiveSuccessorOnOuterFace(w, componentRoot, v, 1).getCurrent();\n y = getExternallyActiveSuccessorOnOuterFace(w, componentRoot, v, 0).getCurrent();\n if (x.isRootVertex()) {\n w = x.getParent();\n } else if (y.isRootVertex()) {\n w = y.getParent();\n } else {\n componentRoot = getComponentRoot(w);\n break;\n }\n }\n Edge xBackEdge = searchEdge(x, v.height);\n Edge yBackEdge = searchEdge(y, v.height);\n if (DEBUG) {\n System.out\n .printf(\n \"Failed v = %s, failed edge = %s\\n\", failedV.toString(false),\n failedEdge.toString());\n System.out.printf(\"x = %s, y = %s\\n\", x.toString(false), y.toString(false));\n System.out\n .printf(\n \"xBackEdge = %s, yBackEdge = %s\\n\", xBackEdge.toString(),\n yBackEdge.toString());\n }\n Node backLower = lowest(xBackEdge.target, yBackEdge.target);\n Node backHigher = highest(xBackEdge.target, yBackEdge.target);\n addPathEdges(subdivision, xBackEdge, x);\n addPathEdges(subdivision, yBackEdge, y);\n addBoundaryEdges(subdivision, componentRoot);\n\n if (componentRoot.getParent() != v) {\n // case A, v isn't a parent of the component we've found\n if (PRINT_CASES) {\n System.out.println(\"Case A\");\n }\n addPathEdges(subdivision, componentRoot.getParent(), backLower);\n addPathEdges(subdivision, failedEdge, w);\n return finish(subdivision);\n }\n // node z will be null only if the tree path from w to failedEdge is failedEdge itself\n Node z = getNextOnPath(w, failedEdge);\n Edge backEdge = null;\n if (z != null) {\n backEdge = searchSubtreeDfs(z, e -> e.target.height < v.height && e != failedEdge);\n }\n if (backEdge != null) {\n // case B\n if (PRINT_CASES) {\n System.out.println(\"Case B\");\n }\n addPathEdges(subdivision, backEdge, w);\n addPathEdges(subdivision, failedEdge, w);\n Node highest =\n highest(xBackEdge.target, highest(yBackEdge.target, backEdge.target));\n Node lowest = lowest(xBackEdge.target, lowest(yBackEdge.target, backEdge.target));\n addPathEdges(subdivision, highest, lowest);\n return finish(subdivision);\n }\n /*\n * If we failed to either case A or B, we have to find a highest obstructing path and\n * then deal with cases C - E\n */\n setBoundaryDepth(componentRoot, w, 0, 1);\n setBoundaryDepth(componentRoot, w, 1, -1);\n\n assert x.boundaryHeight > 0;\n List path = findHighestObstructingPath(componentRoot, w);\n assert !path.isEmpty();\n if (DEBUG) {\n System.out.println(\"Path = \" + path);\n }\n\n Edge firstEdge = path.get(0);\n Edge lastEdge = path.get(path.size() - 1);\n Node firstNode =\n firstEdge.source.boundaryHeight > 0 ? firstEdge.source : firstEdge.target;\n Node lastNode = lastEdge.source.boundaryHeight < 0 ? lastEdge.source : lastEdge.target;\n if (firstNode.boundaryHeight < x.boundaryHeight\n || lastNode.boundaryHeight > y.boundaryHeight)\n {\n // case C, either the first node or the last node of the path is higher than x or y\n // respectively\n if (PRINT_CASES) {\n System.out.println(\"Case C\");\n }\n Node removeStart;\n if (lastNode.boundaryHeight > y.boundaryHeight) {\n removeStart = firstNode.boundaryHeight < x.boundaryHeight ? firstNode : x;\n removeUp(removeStart, componentRoot, 1, subdivision);\n } else {\n removeUp(y, componentRoot, 0, subdivision);\n }\n addPathEdges(subdivision, failedEdge, w);\n subdivision.addAll(path);\n addPathEdges(subdivision, v, backLower);\n return finish(subdivision);\n }\n path.forEach(e -> e.source.marked = e.target.marked = true);\n List pathToV = findPathToV(path, v);\n if (!pathToV.isEmpty()) {\n // case D, we have a path to the node v\n if (PRINT_CASES) {\n System.out.println(\"Case D\");\n }\n removeUp(x, componentRoot, 1, subdivision);\n removeUp(y, componentRoot, 0, subdivision);\n subdivision.addAll(path);\n subdivision.addAll(pathToV);\n addPathEdges(subdivision, v, backLower);\n addPathEdges(subdivision, failedEdge, w);\n return finish(subdivision);\n }\n Edge externallyActive = searchEdge(w, v.height, failedEdge);\n assert externallyActive != null;\n if (DEBUG) {\n System.out.printf(\"Externally active edge = %s\\n\", externallyActive.toString());\n }\n addPathEdges(subdivision, externallyActive, w);\n if (firstStrictlyHigher(externallyActive.target, xBackEdge.target, yBackEdge.target)) {\n // case E_2, equivalent to A\n if (PRINT_CASES) {\n System.out.println(\"Case E_2\");\n }\n addPathEdges(subdivision, componentRoot.getParent(), backLower);\n } else if (firstStrictlyHigher(\n xBackEdge.target, yBackEdge.target, externallyActive.target))\n {\n // case E_2, u_x is higher\n if (PRINT_CASES) {\n System.out.println(\"Case E_2, u_x is higher\");\n }\n removeUp(componentRoot, x, 0, subdivision);\n removeUp(w, lastNode, 0, subdivision);\n subdivision.addAll(path);\n addPathEdges(subdivision, failedEdge, w);\n addPathEdges(subdivision, v, lowest(backLower, externallyActive.target));\n } else if (firstStrictlyHigher(\n yBackEdge.target, xBackEdge.target, externallyActive.target))\n {\n // case E_2, u_y is higher\n if (PRINT_CASES) {\n System.out.println(\"Case E_2, u_y is higher\");\n }\n removeUp(y, componentRoot, 0, subdivision);\n removeUp(firstNode, w, 0, subdivision);\n subdivision.addAll(path);\n addPathEdges(subdivision, failedEdge, w);\n addPathEdges(subdivision, v, lowest(backLower, externallyActive.target));\n } else if (firstNode.boundaryHeight > x.boundaryHeight) {\n // case E_4, p_x is lower than x\n if (PRINT_CASES) {\n System.out.println(\"Case E_3, p_x is lower than x\");\n }\n removeUp(w, lastNode, 0, subdivision);\n subdivision.addAll(path);\n addPathEdges(subdivision, failedEdge, w);\n addPathEdges(\n subdivision, highest(backHigher, externallyActive.target),\n lowest(backLower, externallyActive.target));\n } else if (lastNode.boundaryHeight < y.boundaryHeight) {\n // case E_4, p_y is lower than y\n if (PRINT_CASES) {\n System.out.println(\"Case E_3, p_y is lower than y\");\n }\n removeUp(firstNode, w, 0, subdivision);\n subdivision.addAll(path);\n addPathEdges(subdivision, failedEdge, w);\n addPathEdges(\n subdivision, highest(backHigher, externallyActive.target),\n lowest(backLower, externallyActive.target));\n } else {\n // case E, extracting K_5\n if (PRINT_CASES) {\n System.out.println(\"Case E, extracting K_5\");\n }\n subdivision.addAll(path);\n addPathEdges(subdivision, v, lowest(backLower, externallyActive.target));\n addPathEdges(subdivision, failedEdge, w);\n }\n return finish(subdivision);\n }\n return kuratowskiSubdivision;\n }\n\n /**\n * {@inheritDoc}\n *

\n * Only the first call to this method does the actual computation, all subsequent calls only\n * return the previously computed value.\n */\n @Override\n public boolean isPlanar()\n {\n return lazyTestPlanarity();\n }\n\n /**\n * {@inheritDoc}\n *

\n * Only the first call to this method does the actual computation, all subsequent calls only\n * return the previously computed value.\n */\n @Override\n public Embedding getEmbedding()\n {\n if (isPlanar()) {\n return lazyComputeEmbedding();\n } else {\n throw new IllegalArgumentException(\"Graph is not planar\");\n }\n }\n\n /**\n * {@inheritDoc}\n *

\n * Only the first call to this method does the actual computation, all subsequent calls only\n * return the previously computed value.\n */\n @Override\n public Graph getKuratowskiSubdivision()\n {\n if (isPlanar()) {\n throw new IllegalArgumentException(\"Graph is planar\");\n } else {\n return lazyExtractKuratowskiSubdivision();\n }\n }\n\n /**\n * Represents information needed to search a path within a biconnected component\n */\n private class SearchInfo\n {\n /**\n * The current node of the dfs traversal\n */\n Node current;\n /**\n * The edge used to go to the {@code current} vertex\n */\n Edge prevEdge;\n /**\n * Whether dfs is in a forward or a backtracking phase\n */\n boolean backtrack;\n\n /**\n * Creates a new search info\n *\n * @param current the current node of the traversal\n * @param prevEdge the edge used to go to the {@code current} vertex\n * @param backtrack whether dfs is in a forward or a backtracking phase\n */\n SearchInfo(Node current, Edge prevEdge, boolean backtrack)\n {\n this.current = current;\n this.prevEdge = prevEdge;\n this.backtrack = backtrack;\n }\n }\n\n /**\n * Represents information needed to store in the stack during the input {@code graph}\n * orientation.\n */\n private class OrientDfsStackInfo\n {\n /**\n * The current vertex of the dfs traversal\n */\n V current;\n /**\n * The parent vertex of the {@code current} vertex, which is null for dfs tree roots\n */\n V parent;\n /**\n * The edge connecting {@code parent} and {@code current} vertices\n */\n E parentEdge;\n /**\n * Whether dfs is moving forward or backtracking on the {@code current} node\n */\n boolean backtrack;\n\n /**\n * Creates new instance of the information stored on the stack during the orientation of the\n * {@code graph}\n *\n * @param current the vertex dfs is currently processing\n * @param parent the parent of the {@code current} vertex\n * @param parentEdge the edge between {@code current} and {@code parent} vertices\n * @param backtrack whether dfs is moving forward or backtracking on the {@code current}\n * vertex\n */\n OrientDfsStackInfo(V current, V parent, E parentEdge, boolean backtrack)\n {\n this.current = current;\n this.parent = parent;\n this.parentEdge = parentEdge;\n this.backtrack = backtrack;\n }\n }\n\n /**\n * The information needed to merge two consecutive biconnected components\n */\n private class MergeInfo\n {\n /**\n * The node current traversal descended from. This node belongs to the parent biconnected\n * component\n */\n Node parent;\n /**\n * The next node along the traversal of the parent biconnected component\n */\n Node parentNext;\n /**\n * The virtual root of the child biconnected component\n */\n Node child;\n /**\n * The previous node along the traversal of the child biconnected component\n */\n Node childPrev;\n /**\n * The direction used to enter the parent biconnected component.\n *

\n * Note: this value doesn't specify the direction from {@code parent} node to the\n * {@code parentNext} node, i.e. {@code parent.outerFaceNeighbors[vIn]} may not be equal to\n * the {@code parentNext}. Instead, this value specifies the direction used to start the\n * traversal from the parent's biconnected component virtual root.\n */\n int vIn;\n /**\n * The direction used to start the traversal of the child biconnected component. Since the\n * {@code child} is the component root, {@code child.outerFaceNeighbors[|1-vOut|]} is equal\n * to the {@code childPrev}\n */\n int vOut;\n\n /**\n * Creates new instance of the infromation needed to merge to biconnected components\n *\n * @param parent the node current traversal descended from\n * @param parentNext the next node along the traversal of the parent component\n * @param child the virtual root of the child biconnected component\n * @param childPrev the previous node along the traversal of the child component\n * @param vIn the direction used to enter the parent biconnected component\n * @param vOut the direction used to enter the child biconnected component\n */\n MergeInfo(Node parent, Node parentNext, Node child, Node childPrev, int vIn, int vOut)\n {\n this.parent = parent;\n this.parentNext = parentNext;\n this.child = child;\n this.childPrev = childPrev;\n this.vIn = vIn;\n this.vOut = vOut;\n }\n\n /**\n * Returns true if the traversal was inverted when descending to the child biconnected\n * component, false otherwise\n *\n * @return true if the traversal was inverted when descending to the child biconnected\n * component, false otherwise\n */\n boolean isInverted()\n {\n return vIn != vOut;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n return String\n .format(\n \"Parent dir = {%s -> %s}, child_dir = {%s -> %s}, inverted = %b, vIn = %d, vOut = %d\",\n parent.toString(false), parentNext.toString(false), childPrev.toString(false),\n child.toString(false), isInverted(), vIn, vOut);\n }\n }\n\n /**\n * A circulator over the nodes on the boundary of the biconnected component. Traverses the nodes\n * in the cyclic manner, i.e. it doesn't stop when all the nodes are traversed\n */\n private class OuterFaceCirculator\n implements\n Iterator\n {\n /**\n * The node this circulator will return next\n */\n private Node current;\n /**\n * The previous node along the traversal of the component boundary. This node is needed\n * because the component boundary nodes aren't connected in an ordered way.\n */\n private Node prev;\n\n /**\n * Creates a new instance of the circulator over the biconnected component boundary nodes.\n * The {@code prev} node is considered to be just traversed\n *\n * @param current the node this circulator will return next\n * @param prev the previous node along the traversal\n */\n OuterFaceCirculator(Node current, Node prev)\n {\n this.current = current;\n this.prev = prev;\n }\n\n /**\n * {@inheritDoc}\n *

\n * Always returns true since this is a circulator\n */\n @Override\n public boolean hasNext()\n {\n return true;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Node next()\n {\n Node t = current;\n current = current.nextOnOuterFace(prev);\n prev = t;\n return prev;\n }\n\n /**\n * Returns an edge connecting previously returned node with node, which will be returned\n * next. If either of the mentioned nodes is virtual, the edge will be incident to its real\n * counterpart.\n *\n * @return an edge from the current node to the next node\n */\n Edge edgeToNext()\n {\n Edge edge = prev.embedded.getFirst();\n Node target = toExistingNode(current);\n Node source = toExistingNode(prev);\n if (edge.getOpposite(source) == target) {\n return edge;\n } else {\n return prev.embedded.getLast();\n }\n }\n\n /**\n * Returns the node this circulator has just traversed\n *\n * @return the node this circulator has just traversed\n */\n Node getCurrent()\n {\n return prev;\n }\n\n /**\n * Returns a node adjacent to the current node along the boundary, which is not equal to the\n * next node along the traversal. If the component consist of just one real node, returns\n * the only neighbor the the current node.\n *\n * @return node before the current node along the traversal\n */\n Node getPrev()\n {\n return prev.nextOnOuterFace(current);\n }\n\n /**\n * Returns either {@code node} or its real counterpart in the case the {@code node} is a\n * component root.\n *\n * @param node the input argument\n * @return the real counterpath of the {@code node}\n */\n private Node toExistingNode(Node node)\n {\n return node.isRootVertex() ? node.getParent() : node;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n return String.format(\"%s -> %s\", prev.toString(false), current.toString(false));\n }\n }\n\n /**\n * Internal representation of the edges of the input {@code graph}.\n */\n private class Edge\n {\n /**\n * The counterpart of this edge in the {@code graph}. This value can be null if the edge was\n * created as a short-circuit edge.\n */\n E graphEdge;\n /**\n * The source node of this edge. For tree edges the {@code source} is lower than the\n * {@code target}, for back edges the {@code target} is lower (having smaller height)\n */\n Node source;\n /**\n * The target of this edge\n */\n Node target;\n /**\n * Either $+1$ or $-1$ for regular and inverted edges respectively. This value is set to\n * $-1$ to flip a biconnected component in $\\mathcal{O}(1)$ time. Note: this\n * operation doesn't flip any of the child biconnected components of this biconnected\n * component\n */\n int sign;\n /**\n * Whether the edge is embedded or not. This value is important for\n */\n boolean embedded;\n /**\n * Whether the edge is real or short-circuit. See the original paper for the definition of\n * the short-circuit edges.\n */\n boolean shortCircuit;\n\n /**\n * Creates a new short-circuit edge with no counterpart in {@code graph}. The {@code source}\n * of this edge is always a real node on the boundary of some biconnected component, and the\n * {@code target} node is the parent node of the biconnected component the source node\n * belongs to, so the edge resembles a regular back edge except for that it doesn't have a\n * counterpart in the {@code graph}\n *\n * @param source the source of the short-circuit edge\n * @param target the target of the short-circuit edge\n */\n Edge(Node source, Node target)\n {\n this(null, source, target);\n this.shortCircuit = true;\n this.embedded = true;\n }\n\n /**\n * Creates a new tree edge.\n *\n * @param graphEdge the counterpart of this edge in the {@code graph}\n * @param source the source node of this edge\n */\n Edge(E graphEdge, Node source)\n {\n this(graphEdge, source, null);\n }\n\n /**\n * Creates a new edge. This constructor is used directly for the creation of the back edges\n *\n * @param graphEdge the counterpart of this edge in the {@code graph}\n * @param source the source node of this edge\n * @param target the target node of this edge\n */\n Edge(E graphEdge, Node source, Node target)\n {\n this.graphEdge = graphEdge;\n this.source = source;\n this.target = target;\n this.sign = 1;\n }\n\n /**\n * True if this edge is incident to the node {@code node}, false otherwise\n *\n * @param node the node to test\n * @return true if this edge is incident to the node {@code node}, false otherwise\n */\n boolean isIncidentTo(Node node)\n {\n return source == node || target == node;\n }\n\n /**\n * Returns the opposite node of the {@code node}\n *\n * @param node an endpoint of this edge\n * @return the other endpoint of this edge\n */\n Node getOpposite(Node node)\n {\n assert isIncidentTo(node); // debug purpose assertion\n return source == node ? target : source;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n String formatString = \"%s -> %s\";\n if (shortCircuit) {\n formatString = \"%s ~ %s\";\n }\n return String.format(formatString, source.toString(false), target.toString(false));\n }\n }\n\n /**\n * The internal representation of the vertices of the graph. Contains necessary information to\n * perform dfs traversals, biconnected component boundary traversals, to embed edges, etc.\n */\n private class Node\n {\n /**\n * The counterpart of this node in the {@code graph}. For the component roots this value is\n * {@code null}.\n */\n V graphVertex;\n /**\n * Whether this node is a root of the biconnected component or not.\n */\n boolean rootVertex;\n /**\n * The dfs index of this node in the graph. Every node has a unique dfs index in the range\n * $[0,|V| - 1]$. This value is used to order the nodes for the embedding of the edges\n * incident to them. The index of the first dfs root is $1$\n */\n int dfsIndex;\n /**\n * The height of the node in the created dfs tree. The root of the tree has height $0$. The\n * smaller this value is, the lower the node is considered to be.\n */\n int height;\n /**\n * The least dfs index of the nodes' least ancestors in the subtree rooted at this\n * node. If the subtree doesn't contain a node with a back edge, that ends lower that this\n * node, this value is equal to the dfs index of this node.\n */\n int lowpoint;\n /**\n * The least dfs index of the nodes adjacent to this node. If the node doesn't have incident\n * back edges, this value is equal to the dfs index of the node itself.\n */\n int leastAncestor;\n /**\n * Stores some value to indicate whether this node is visited in the current context or not.\n * During the testing phase, if this value if equal to the dfs index of the currently\n * processed node $v$, then this node is visited, otherwise not. During the Kuratowski\n * subdivision extraction phase, the value of $0$ indicates that the node isn't visited,\n * otherwise, the node is considered to be visited.\n */\n int visited;\n /**\n * During the process of embedding of the down edges of the node $v$, this variable is set\n * to the dfs index of $v$ to indicate that this node has a back edge incident to $v$, which\n * needs to be embedded.\n */\n int backEdgeFlag;\n /**\n * The height of this node on the boundary of the biconnected component, which is used to\n * extract the Kuratowski subdivision. The height of the component root is $0$, the heights\n * on the left side are positive, on the right side - negative. This value is used to\n * quickly determine for two nodes on the same boundary branch which one is higher (closer\n * to the component root).\n */\n int boundaryHeight;\n /**\n * Used to mark the boundary nodes of the biconnected\n */\n boolean marked;\n /**\n * Edge to the parent node of this node in the dfs tree. For tree roots this value is\n * {@code null}\n */\n Edge parentEdge;\n /**\n * If this node has a back edge incident to the currently processed node $v$, then this\n * variable stores this edge\n */\n Edge edgeToEmbed;\n /**\n * The component root the node is created in. For dfs tree roots this value is {@code null}\n */\n Node initialComponentRoot;\n /**\n * Two neighbors on the outer face of the biconnected component. Their order is completely\n * irrelevant for the algorithm to traverse the outer face.\n */\n Node[] outerFaceNeighbors;\n /**\n * The list containing the dfs children of this node, which are in the different child\n * biconnected component, i.e. their weren't merged in the parent component.\n */\n DoublyLinkedList separatedDfsChildList;\n /**\n * The roots of the pertinent components during the processing of the node $v$. These are\n * the components that have pertinent descendant nodes, i.e. nodes incident to the node $v$\n * via a back edge\n */\n DoublyLinkedList pertinentRoots;\n /**\n * The list of tree edges incident to this node in the dfs tree. This list doesn't contain a\n * parent edge of this node\n */\n List treeEdges;\n /**\n * The list containing the edges from descendants of this node in the dfs tree. For each\n * such descendant the corresponding edge is a back edge.\n */\n List downEdges;\n /**\n * The list of back edges incident to this node.\n */\n List backEdges;\n /**\n * Stores the list node from the {@code separatedDfsChildList} of the parent node this node\n * is stored in. This enable deleting of this node from the {@code separatedDfsChildList}\n * list in $\\mathcal{O}(1)$ time\n */\n DoublyLinkedList.ListNode listNode;\n /**\n * The list of the embedded edges incident to this node in a clockwise or a counterclockwise\n * order. The order is counterclockwise if the product of the signs of the parent edges\n * along the path from the root of the component this node is contained in to this node is\n * equal to $-1$. Otherwise, the order is clockwise.\n */\n DoublyLinkedList embedded;\n\n /**\n * Creates a new real node with the specified parameters.\n *\n * @param graphVertex the counterpart of this node in the {@code graph}\n * @param dfsIndex the dfs index of this node\n * @param height the height of this node in the dfs tree\n * @param initialComponentRoot the component root of this node.\n * @param parentEdge the parent edge of this node\n */\n Node(V graphVertex, int dfsIndex, int height, Node initialComponentRoot, Edge parentEdge)\n {\n this(graphVertex, dfsIndex, parentEdge, false);\n this.height = height;\n this.initialComponentRoot = initialComponentRoot;\n }\n\n /**\n * Creates a new component root. Dfs index of the component root is equal to dfs index of\n * its parent.\n *\n * @param dfsIndex the dfs index of this node\n * @param parentEdge the parent edge of this component root\n */\n Node(int dfsIndex, Edge parentEdge)\n {\n this(null, dfsIndex, parentEdge, true);\n }\n\n /**\n * Creates a new node with the specified parameters\n *\n * @param graphVertex the vertex in the {@code graph} corresponding to this node\n * @param dfsIndex the dfs index of this node\n * @param parentEdge the parent edge of this node\n * @param rootVertex whether this is real or virtual node\n */\n Node(V graphVertex, int dfsIndex, Edge parentEdge, boolean rootVertex)\n {\n this.graphVertex = graphVertex;\n this.dfsIndex = dfsIndex;\n this.parentEdge = parentEdge;\n this.rootVertex = rootVertex;\n this.outerFaceNeighbors = TypeUtil.uncheckedCast(Array.newInstance(Node.class, 2));\n this.embedded = new DoublyLinkedList<>();\n if (parentEdge != null) {\n embedded.add(parentEdge);\n }\n this.visited = this.backEdgeFlag = n;\n if (!rootVertex) {\n separatedDfsChildList = new DoublyLinkedList<>();\n pertinentRoots = new DoublyLinkedList<>();\n treeEdges = new ArrayList<>();\n downEdges = new ArrayList<>();\n backEdges = new ArrayList<>();\n }\n }\n\n /**\n * Checks whether this node is visited in the context of processing the node {@code node}\n *\n * @param node the node that is currently been processed\n * @return true if this node is visited, false otherwise\n */\n boolean isVisitedWrtTo(Node node)\n {\n return node.dfsIndex == visited;\n }\n\n /**\n * Checks whether this node is pertinent in the context of processing the node {@code node}.\n * During the processing of the node {@code node}, a node is pertinent if it has a back edge\n * to {@code node} or it has a child biconnected component, which has a pertinent node.\n *\n * @param node the node that is currently been processed\n * @return true if this node is pertinent, false otherwise\n */\n boolean isPertinentWrtTo(Node node)\n {\n return backEdgeFlag == node.dfsIndex || !pertinentRoots.isEmpty();\n }\n\n /**\n * Checks whether this node has a back edge to the {@code node}.\n *\n * @param node the other endpoint of the edge we're looking for\n * @return true if the edge between this node and {@code node} exists, false otherwise\n */\n boolean hasBackEdgeWrtTo(Node node)\n {\n return backEdgeFlag == node.dfsIndex;\n }\n\n /**\n * Checks whether this node is externally active with respect to the {@code node}. A node is\n * externally active, if it is incident to the edge ending higher than {@code node}, or it\n * has a child biconnected component with a pertinent node\n *\n * @param node an ancestor of this node\n * @return true if this node is externally active with respect to the {@code node}, false\n * otherwise\n */\n boolean isExternallyActiveWrtTo(Node node)\n {\n return leastAncestor < node.dfsIndex || (!separatedDfsChildList.isEmpty()\n && separatedDfsChildList.getFirst().lowpoint < node.dfsIndex);\n }\n\n /**\n * Returns true if the node is a component root, false otherwise\n *\n * @return true if the node is a component root, false otherwise\n */\n boolean isRootVertex()\n {\n return rootVertex;\n }\n\n /**\n * Check whether this node is internally active. A node is internally active if it's\n * pertinent and not externally active\n *\n * @param node an ancestor of this node\n * @return true if this node is internally active, false otherwise\n */\n boolean isInternallyActiveWrtTo(Node node)\n {\n return isPertinentWrtTo(node) && !isExternallyActiveWrtTo(node);\n }\n\n /**\n * Check whether this node is inactive. A node is inactive it is neither pertinent nor\n * externally active\n *\n * @param node an ancestor of this node\n * @return true if this node is inactive, false otherwise\n */\n boolean isInactiveWrtTo(Node node)\n {\n return !isExternallyActiveWrtTo(node) && !isPertinentWrtTo(node);\n }\n\n /**\n * Check whether this node is active. A node is active it is either pertinent or externally\n * active\n *\n * @param node an ancestor of this node\n * @return true if this node is active, false otherwise\n */\n boolean isActiveWrtTo(Node node)\n {\n return !isInactiveWrtTo(node);\n }\n\n /**\n * Returns a circulator, that moves in the direction {@code direction}. The next node along\n * the traversal will be {@code this.outerFaceNeighbor[direction]}.\n *\n * @param direction the direction to move in\n * @return an iterator over the boundary nodes in the direction {@code direction}\n */\n OuterFaceCirculator iterator(int direction)\n {\n return new OuterFaceCirculator(outerFaceNeighbors[direction], this);\n }\n\n void removeShortCircuitEdges()\n {\n embedded.removeIf(e -> e.shortCircuit);\n }\n\n /**\n * Returns the parent of this node in the dfs tree. Tree parent of the dfs root node is\n * {@code null}\n *\n * @return the parent of this node in the dfs tree\n */\n Node getParent()\n {\n return parentEdge == null ? null : parentEdge.source;\n }\n\n /**\n * Checks whether this node has a neighbor {@code node} on the boundary of the biconnected\n * component\n *\n * @param node a possible neighbor of this node\n */\n void checkIsAdjacent(Node node)\n {\n assert node == outerFaceNeighbors[0] || node == outerFaceNeighbors[1];\n }\n\n /**\n * Swaps the outer face neighbors of this node\n */\n void swapNeighbors()\n {\n Node t = outerFaceNeighbors[0];\n outerFaceNeighbors[0] = outerFaceNeighbors[1];\n outerFaceNeighbors[1] = t;\n }\n\n /**\n * Substitutes the neighbor {@code node} with a {@code newNeighbor}\n *\n * @param node an old neighbor\n * @param newNeighbor a new neighbor\n */\n void substitute(Node node, Node newNeighbor)\n {\n checkIsAdjacent(node);\n if (outerFaceNeighbors[0] == node) {\n outerFaceNeighbors[0] = newNeighbor;\n } else {\n outerFaceNeighbors[1] = newNeighbor;\n }\n }\n\n /**\n * Substitutes a neighbor of this node, which is not equal to the {@code node}, with the\n * {@code newNeighbor}\n *\n * @param node the remaining neighbor\n * @param newNeighbor a new neighbor\n */\n void substituteAnother(Node node, Node newNeighbor)\n {\n checkIsAdjacent(node);\n if (outerFaceNeighbors[0] == node) {\n outerFaceNeighbors[1] = newNeighbor;\n } else {\n outerFaceNeighbors[0] = newNeighbor;\n }\n }\n\n /**\n * Checks whether this node has a neighbor, which is a root of a biconnected component\n *\n * @return true, if this node has a root node neighbor, false otherwise\n */\n boolean hasRootNeighbor()\n {\n return outerFaceNeighbors[0].isRootVertex() || outerFaceNeighbors[1].isRootVertex();\n }\n\n /**\n * Returns a neighbor of this node which is not equal to the {@code prev}\n *\n * @param prev a neighbor of this node\n * @return a neightbor, which is not equal to the {@code prev}\n */\n Node nextOnOuterFace(Node prev)\n {\n checkIsAdjacent(prev);\n if (outerFaceNeighbors[0] == prev) {\n return outerFaceNeighbors[1];\n } else {\n return outerFaceNeighbors[0];\n }\n }\n\n /**\n * Adds {@code edge} to the list of the embedded edges such that the {@code prev} node\n * becomes an inner node.\n *\n * @param edge an edge to embed\n * @param prev the node which should be on the new inner face\n */\n void embedBackEdge(Edge edge, Node prev)\n {\n assert !embedded.isEmpty();\n if (prev.isRootVertex()) {\n prev = prev.getParent();\n }\n Edge firstEdge = embedded.getFirst();\n if (firstEdge.getOpposite(this) == prev) {\n // edge on the new inner face is at the beginning of the list\n embedded.addFirst(edge);\n } else {\n embedded.addLast(edge);\n }\n }\n\n /**\n * Merges the embedded edges of the child component root into this node's embedded edges.\n * Note, that the edges in the {@code edges} list are always in the clockwise order. There\n * are 3 parameters which determine how the {@code edges} list is merged: the {@code vIn}\n * direction, the {@code vOut} direction and the orientation of the edges around this node\n * (clockwise or counterclockwise). The edges in the {@code edges} list should have the same\n * orientation. If this list is inverted, the sign of the {@code parentEdge} is set to $-1$.\n *\n * @param edges the edges from the child component root\n * @param vIn the direction used to enter the parent component\n * @param vOut the direction used to enter the child component\n * @param parentNext the next node along the traversal of the parent biconnected component\n * @param parentEdge the parent edge if the child component\n */\n void mergeChildEdges(\n DoublyLinkedList edges, int vIn, int vOut, Node parentNext, Edge parentEdge)\n {\n assert !embedded.isEmpty();\n Node firstOpposite = embedded.getFirst().getOpposite(this);\n boolean alongParentTraversal = firstOpposite != parentNext;\n boolean actionAppend = false, invert = false;\n if (vIn == 0) {\n if (vOut == 0) {\n if (!alongParentTraversal) {\n invert = actionAppend = true;\n }\n } else {\n if (alongParentTraversal) {\n invert = true;\n } else {\n actionAppend = true;\n }\n }\n } else {\n if (vOut == 0) {\n if (!alongParentTraversal) {\n invert = actionAppend = true;\n }\n } else {\n if (alongParentTraversal) {\n invert = true;\n } else {\n actionAppend = true;\n }\n }\n }\n if (invert) {\n parentEdge.sign = -1;\n edges.invert();\n }\n if (actionAppend) {\n embedded.append(edges);\n } else {\n embedded.prepend(edges);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n String neighbor1 =\n outerFaceNeighbors[0] == null ? \"null\" : outerFaceNeighbors[0].toString(false);\n String neighbor2 =\n outerFaceNeighbors[1] == null ? \"null\" : outerFaceNeighbors[1].toString(false);\n String childListString = \"null\";\n if (separatedDfsChildList != null) {\n StringBuilder builder = new StringBuilder(\"{\");\n separatedDfsChildList.forEach(n -> builder.append(n.toString(false)).append(\", \"));\n childListString = builder.append(\"}\").toString();\n }\n if (rootVertex) {\n return String\n .format(\n \"R {%s}: neighbors = [%s, %s], embedded = %s, visited = %d, back_edge_flag = %d, dfs_index = %d\",\n toString(false), neighbor1, neighbor2, embedded.toString(), visited,\n backEdgeFlag, dfsIndex);\n } else {\n return String\n .format(\n \"{%s}: neighbors = [%s, %s], embedded = %s, visited = %d, back_edge_flag = %d, dfs_index = %d, separated = %s, tree_edges = %s, down_edges = %s, back_edges = %s, parent = %s, lowpoint = %d, least_ancestor = %d\",\n toString(false), neighbor1, neighbor2, embedded.toString(), visited,\n backEdgeFlag, dfsIndex, childListString, treeEdges.toString(),\n downEdges.toString(), backEdges.toString(),\n parentEdge == null ? \"null\" : parentEdge.source.toString(false), lowpoint,\n leastAncestor);\n }\n }\n\n /**\n * Returns a full or a partial string representation of this node\n *\n * @param full whether to return full or partial string representation of this node\n * @return either full or partial string representation of this node\n */\n public String toString(boolean full)\n {\n if (!full) {\n if (rootVertex) {\n return String\n .format(\n \"%s^%s\", parentEdge.source.graphVertex.toString(),\n parentEdge.target.graphVertex.toString());\n } else {\n return graphVertex.toString();\n }\n } else {\n return toString();\n }\n }\n }\n}\n", "file_name": "BoyerMyrvoldPlanarityInspector.java", "human_label": "Find a circulator to the node that satisfies the Interface predicate.", "level": "class_runnable", "lineno": "668", "name": "selectOnOuterFace", "oracle_context": "{ \"apis\" : \"[iterator, next, test, OuterFaceCirculator, Node]\", \"classes\" : \"[OuterFaceCirculator, Node]\", \"vars\" : \"[]\" }", "package": "org.jgrapht.alg.planar", "project": "jgrapht-master" }, { "_id": "636767841a6d9265ec0183e8", "all_context": "{ \"class_level\" : \"import org.apache.log4j.spi.LoggingEvent;\\nLoggingEvent[] ea;\\nint first;\\nint last;\\nint numElems;\\nint maxSize;\\nCyclicBuffer(int maxSize);\\nget(int i);\\ngetMaxSize();\\nget();\\nlength();\\nresize(int newSize);\\n\", \"repo_level\" : \"public interface LoggingEvent {public LocationInfo getLocationInformation();\\npublic Level getLevel();\\npublic String getLoggerName();\\npublic Category getLogger();\\npublic Object getMessage();\\npublic String getNDC();\\npublic Object getMDC(String key);\\npublic void getMDCCopy();\\npublic String getRenderedMessage();\\nstatic long getStartTime();\\npublic String getThreadName();\\npublic ThrowableInformation getThrowableInformation();\\npublic String[] getThrowableStrRep();\\nfinal void setProperty(String propName,String propValue);\\nfinal String getProperty(String key);\\nfinal boolean locationInformationExists();\\nfinal long getTimeStamp();\\npublic Set getPropertyKeySet();\\npublic Map getProperties();\\npublic String getFQNOfLoggerClass();\\npublic Object removeProperty(String propName);\\n }\\n\" }", "class_name": "CyclicBuffer", "code": "public void add(LoggingEvent event){\n ea[last]=event;\n if (++last == maxSize) last=0;\n if (numElems < maxSize) numElems++;\n else if (++first == maxSize) first=0;\n}\n", "docstring": "/** \n * Add an event as the last event in the buffer.\n */\n", "end_lineno": "75", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n \npackage org.apache.log4j.helpers;\n\nimport org.apache.log4j.spi.LoggingEvent;\n\n/**\n\n CyclicBuffer is used by other appenders to hold {@link LoggingEvent\n LoggingEvents} for immediate or differed display.\n \n

This buffer gives read access to any element in the buffer not\n just the first or last element.\n\n @author Ceki Gülcü\n @since 0.9.0\n\n */\npublic class CyclicBuffer {\n \n LoggingEvent[] ea;\n int first; \n int last; \n int numElems;\n int maxSize;\n\n /**\n Instantiate a new CyclicBuffer of at most maxSize events.\n\n The maxSize argument must a positive integer.\n\n @param maxSize The maximum number of elements in the buffer.\n */\n public CyclicBuffer(int maxSize) throws IllegalArgumentException {\n if(maxSize < 1) {\n throw new IllegalArgumentException(\"The maxSize argument (\"+maxSize+\n\t\t\t \") is not a positive integer.\");\n }\n this.maxSize = maxSize;\n ea = new LoggingEvent[maxSize];\n first = 0;\n last = 0;\n numElems = 0;\n }\n \n /**\n Add an event as the last event in the buffer.\n\n */\n public\n void add(LoggingEvent event) { \n ea[last] = event; \n if(++last == maxSize)\n last = 0;\n\n if(numElems < maxSize)\n numElems++;\n else if(++first == maxSize)\n first = 0;\n }\n\n\n /**\n Get the ith oldest event currently in the buffer. If\n i is outside the range 0 to the number of elements\n currently in the buffer, then null is returned.\n\n\n */\n public\n LoggingEvent get(int i) {\n if(i < 0 || i >= numElems)\n return null;\n\n return ea[(first + i) % maxSize];\n }\n\n public \n int getMaxSize() {\n return maxSize;\n }\n\n /**\n Get the oldest (first) element in the buffer. The oldest element\n is removed from the buffer.\n */\n public\n LoggingEvent get() {\n LoggingEvent r = null;\n if(numElems > 0) {\n numElems--;\n r = ea[first];\n ea[first] = null;\n if(++first == maxSize)\n\tfirst = 0;\n } \n return r;\n }\n \n /**\n Get the number of elements in the buffer. This number is\n guaranteed to be in the range 0 to maxSize\n (inclusive).\n */\n public\n int length() {\n return numElems;\n } \n\n /**\n Resize the cyclic buffer to newSize.\n\n @throws IllegalArgumentException if newSize is negative.\n */\n public \n void resize(int newSize) {\n if(newSize < 0) {\n throw new IllegalArgumentException(\"Negative array size [\"+newSize+\n\t\t\t\t\t \"] not allowed.\");\n }\n if(newSize == numElems)\n return; // nothing to do\n \n LoggingEvent[] temp = new LoggingEvent[newSize];\n\n int loopLen = newSize < numElems ? newSize : numElems;\n \n for(int i = 0; i < loopLen; i++) {\n temp[i] = ea[first];\n ea[first] = null;\n if(++first == numElems) \n\tfirst = 0;\n }\n ea = temp;\n first = 0;\n numElems = loopLen;\n maxSize = newSize;\n if (loopLen == newSize) {\n last = 0;\n } else {\n last = loopLen;\n }\n }\n}\n", "file_name": "CyclicBuffer.java", "human_label": "Add an event as the last event in the buffer.", "level": "class_runnable", "lineno": "61", "name": "add", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[ea, last, maxSize, numElems, first]\" }", "package": "org.apache.log4j.helpers", "project": "logging-log4j1-main" }, { "_id": "636767a41a6d9265ec01857e", "all_context": "{ \"class_level\" : \"import java.math.BigInteger;\\nlong MAX_VALUE;\\nlong INT_MASK;\\nlong[] maxValueDivs;\\nint[] maxValueMods;\\nint[] maxSafeDigits;\\nUnsignedNumberUtil();\\nflip(int value);\\ntoLong(int value);\\nparseUnsignedInt(String s);\\nparseUnsignedInt(String string,int radix);\\nunsignedIntToString(int x);\\ncompareUnsigned(long a,long b);\\ncompareSigned(long a,long b);\\nunsignedIntToString(int x,int radix);\\ndivide(long dividend,long divisor);\\nremainder(long dividend,long divisor);\\nparseUnsignedLong(String s);\\nparseUnsignedLong(String s,int radix);\\noverflowInParse(long current,int digit,int radix);\\nunsignedLongToString(long x);\\nunsignedLongToString(long x,int radix);\\nflip(long a);\\n\", \"repo_level\" : \"\" }", "class_name": "UnsignedNumberUtil", "code": "private static int compareSigned(long a,long b){\n return (a < b) ? -1 : ((a > b) ? 1 : 0);\n}\n", "docstring": "/** \n * Compares the two specified {@code long} values. The sign of the value returned is the same as that of{@code ((Long) a).compareTo(b)}.

Note for Java 7 and later: this method should be treated as deprecated; use the equivalent {@link Long#compare} method instead.\n * @param a the first {@code long} to compare\n * @param b the second {@code long} to compare\n * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is greater than{@code b}; or zero if they are equal\n */\n", "end_lineno": "158", "file_content": "//========================================================================\n//Copyright 2016 The Protostuff Authors\n//------------------------------------------------------------------------\n//Licensed under the Apache License, Version 2.0 (the \"License\");\n//you may not use this file except in compliance with the License.\n//You may obtain a copy of the License at\n//http://www.apache.org/licenses/LICENSE-2.0\n//Unless required by applicable law or agreed to in writing, software\n//distributed under the License is distributed on an \"AS IS\" BASIS,\n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//See the License for the specific language governing permissions and\n//limitations under the License.\n//========================================================================\n\npackage io.protostuff;\n\n/*\n * Copyright (C) 2011 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the\n * License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport java.math.BigInteger;\n\npublic final class UnsignedNumberUtil\n{\n public static final long MAX_VALUE = -1L; // Equivalent to 2^64 - 1\n static final long INT_MASK = 0xffffffffL;\n // calculated as 0xffffffffffffffff / radix\n private static final long[] maxValueDivs = new long[Character.MAX_RADIX + 1];\n private static final int[] maxValueMods = new int[Character.MAX_RADIX + 1];\n private static final int[] maxSafeDigits = new int[Character.MAX_RADIX + 1];\n\n static\n {\n BigInteger overflow = new BigInteger(\"10000000000000000\", 16);\n for (int i = Character.MIN_RADIX; i <= Character.MAX_RADIX; i++)\n {\n maxValueDivs[i] = divide(MAX_VALUE, i);\n maxValueMods[i] = (int) remainder(MAX_VALUE, i);\n maxSafeDigits[i] = overflow.toString(i).length() - 1;\n }\n }\n\n private UnsignedNumberUtil()\n {\n }\n\n private static int flip(int value)\n {\n return value ^ Integer.MIN_VALUE;\n }\n\n /**\n * A (self-inverse) bijection which converts the ordering on unsigned longs to the ordering on longs, that is,\n * {@code a <= b} as unsigned longs if and only if {@code flip(a) <= flip(b)} as signed longs.\n */\n private static long flip(long a)\n {\n return a ^ Long.MIN_VALUE;\n }\n\n /**\n * Returns the value of the given {@code int} as a {@code long}, when treated as unsigned.\n */\n private static long toLong(int value)\n {\n return value & INT_MASK;\n }\n\n /**\n * Returns the unsigned {@code int} value represented by the given decimal string.\n *\n * @throws NumberFormatException\n * if the string does not contain a valid unsigned {@code int} value\n * @throws NullPointerException\n * if {@code s} is null (in contrast to {@link Integer#parseInt(String)})\n */\n public static int parseUnsignedInt(String s)\n {\n return parseUnsignedInt(s, 10);\n }\n\n /**\n * Returns the unsigned {@code int} value represented by a string with the given radix.\n *\n * @param string\n * the string containing the unsigned integer representation to be parsed.\n * @param radix\n * the radix to use while parsing {@code s}; must be between {@link Character#MIN_RADIX} and\n * {@link Character#MAX_RADIX}.\n * @throws NumberFormatException\n * if the string does not contain a valid unsigned {@code int}, or if supplied radix is invalid.\n * @throws NullPointerException\n * if {@code s} is null (in contrast to {@link Integer#parseInt(String)})\n */\n private static int parseUnsignedInt(String string, int radix)\n {\n long result = Long.parseLong(string, radix);\n if ((result & INT_MASK) != result)\n {\n throw new NumberFormatException(\"Input \" + string + \" in base \" + radix\n + \" is not in the range of an unsigned integer\");\n }\n return (int) result;\n }\n\n /**\n * Returns a string representation of x, where x is treated as unsigned.\n */\n public static String unsignedIntToString(int x)\n {\n return unsignedIntToString(x, 10);\n }\n\n /**\n * Compares the two specified {@code long} values, treating them as unsigned values between {@code 0} and\n * {@code 2^64 - 1} inclusive.\n *\n * @param a\n * the first unsigned {@code long} to compare\n * @param b\n * the second unsigned {@code long} to compare\n * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is greater than\n * {@code b}; or zero if they are equal\n */\n private static int compareUnsigned(long a, long b)\n {\n return compareSigned(flip(a), flip(b));\n }\n\n /**\n * Compares the two specified {@code long} values. The sign of the value returned is the same as that of\n * {@code ((Long) a).compareTo(b)}.\n *\n *

\n * Note for Java 7 and later: this method should be treated as deprecated; use the equivalent\n * {@link Long#compare} method instead.\n *\n * @param a\n * the first {@code long} to compare\n * @param b\n * the second {@code long} to compare\n * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is greater than\n * {@code b}; or zero if they are equal\n */\n private static int compareSigned(long a, long b)\n {\n return (a < b) ? -1 : ((a > b) ? 1 : 0);\n }\n\n /**\n * Returns a string representation of {@code x} for the given radix, where {@code x} is treated as unsigned.\n *\n * @param x\n * the value to convert to a string.\n * @param radix\n * the radix to use while working with {@code x}\n * @throws IllegalArgumentException\n * if {@code radix} is not between {@link Character#MIN_RADIX} and {@link Character#MAX_RADIX}.\n */\n private static String unsignedIntToString(int x, int radix)\n {\n long asLong = x & INT_MASK;\n return Long.toString(asLong, radix);\n }\n\n /**\n * Returns dividend / divisor, where the dividend and divisor are treated as unsigned 64-bit quantities.\n *\n * @param dividend\n * the dividend (numerator)\n * @param divisor\n * the divisor (denominator)\n * @throws ArithmeticException\n * if divisor is 0\n */\n private static long divide(long dividend, long divisor)\n {\n if (divisor < 0)\n { // i.e., divisor >= 2^63:\n if (compareUnsigned(dividend, divisor) < 0)\n {\n return 0; // dividend < divisor\n }\n else\n {\n return 1; // dividend >= divisor\n }\n }\n\n // Optimization - use signed division if dividend < 2^63\n if (dividend >= 0)\n {\n return dividend / divisor;\n }\n\n /*\n * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is guaranteed to be\n * either exact or one less than the correct value. This follows from fact that floor(floor(x)/i) == floor(x/i)\n * for any real x and integer i != 0. The proof is not quite trivial.\n */\n long quotient = ((dividend >>> 1) / divisor) << 1;\n long rem = dividend - quotient * divisor;\n return quotient + (compareUnsigned(rem, divisor) >= 0 ? 1 : 0);\n }\n\n /**\n * Returns dividend % divisor, where the dividend and divisor are treated as unsigned 64-bit quantities.\n *\n * @param dividend\n * the dividend (numerator)\n * @param divisor\n * the divisor (denominator)\n * @throws ArithmeticException\n * if divisor is 0\n * @since 11.0\n */\n private static long remainder(long dividend, long divisor)\n {\n if (divisor < 0)\n { // i.e., divisor >= 2^63:\n if (compareUnsigned(dividend, divisor) < 0)\n {\n return dividend; // dividend < divisor\n }\n else\n {\n return dividend - divisor; // dividend >= divisor\n }\n }\n\n // Optimization - use signed modulus if dividend < 2^63\n if (dividend >= 0)\n {\n return dividend % divisor;\n }\n\n /*\n * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is guaranteed to be\n * either exact or one less than the correct value. This follows from fact that floor(floor(x)/i) == floor(x/i)\n * for any real x and integer i != 0. The proof is not quite trivial.\n */\n long quotient = ((dividend >>> 1) / divisor) << 1;\n long rem = dividend - quotient * divisor;\n return rem - (compareUnsigned(rem, divisor) >= 0 ? divisor : 0);\n }\n\n\t/**\n\t * Returns the unsigned {@code long} value represented by the given decimal string.\n\t *\n\t * @throws NumberFormatException if the string does not contain a valid unsigned {@code long}\n\t * value\n\t * @throws NullPointerException if {@code s} is null\n\t * (in contrast to {@link Long#parseLong(String)})\n\t */\n\tpublic static long parseUnsignedLong(String s) {\n\t\treturn parseUnsignedLong(s, 10);\n\t}\n\n /**\n * Returns the unsigned {@code long} value represented by a string with the given radix.\n *\n * @param s\n * the string containing the unsigned {@code long} representation to be parsed.\n * @param radix\n * the radix to use while parsing {@code s}\n * @throws NumberFormatException\n * if the string does not contain a valid unsigned {@code long} with the given radix, or if\n * {@code radix} is not between {@link Character#MIN_RADIX} and {@link Character#MAX_RADIX}.\n * @throws NullPointerException\n * if {@code s} is null (in contrast to {@link Long#parseLong(String)})\n */\n private static long parseUnsignedLong(String s, int radix)\n {\n if (s.length() == 0)\n {\n throw new NumberFormatException(\"empty string\");\n }\n if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)\n {\n throw new NumberFormatException(\"illegal radix: \" + radix);\n }\n\n int max_safe_pos = maxSafeDigits[radix] - 1;\n long value = 0;\n for (int pos = 0; pos < s.length(); pos++)\n {\n int digit = Character.digit(s.charAt(pos), radix);\n if (digit == -1)\n {\n throw new NumberFormatException(s);\n }\n if (pos > max_safe_pos && overflowInParse(value, digit, radix))\n {\n throw new NumberFormatException(\"Too large for unsigned long: \" + s);\n }\n value = (value * radix) + digit;\n }\n\n return value;\n }\n\n /**\n * Returns true if (current * radix) + digit is a number too large to be represented by an unsigned long. This is\n * useful for detecting overflow while parsing a string representation of a number. Does not verify whether supplied\n * radix is valid, passing an invalid radix will give undefined results or an ArrayIndexOutOfBoundsException.\n */\n private static boolean overflowInParse(long current, int digit, int radix)\n {\n if (current >= 0)\n {\n if (current < maxValueDivs[radix])\n {\n return false;\n }\n if (current > maxValueDivs[radix])\n {\n return true;\n }\n // current == maxValueDivs[radix]\n return (digit > maxValueMods[radix]);\n }\n\n // current < 0: high bit is set\n return true;\n }\n\n /**\n * Returns a string representation of x, where x is treated as unsigned.\n */\n public static String unsignedLongToString(long x)\n {\n return unsignedLongToString(x, 10);\n }\n\n /**\n * Returns a string representation of {@code x} for the given radix, where {@code x} is treated as unsigned.\n *\n * @param x\n * the value to convert to a string.\n * @param radix\n * the radix to use while working with {@code x}\n * @throws IllegalArgumentException\n * if {@code radix} is not between {@link Character#MIN_RADIX} and {@link Character#MAX_RADIX}.\n */\n private static String unsignedLongToString(long x, int radix)\n {\n if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)\n {\n throw new IllegalArgumentException(\"Invalid radix: \" + radix);\n }\n if (x == 0)\n {\n // Simply return \"0\"\n return \"0\";\n }\n else\n {\n char[] buf = new char[64];\n int i = buf.length;\n if (x < 0)\n {\n // Separate off the last digit using unsigned division. That will leave\n // a number that is nonnegative as a signed integer.\n long quotient = divide(x, radix);\n long rem = x - quotient * radix;\n buf[--i] = Character.forDigit((int) rem, radix);\n x = quotient;\n }\n // Simple modulo/division approach\n while (x > 0)\n {\n buf[--i] = Character.forDigit((int) (x % radix), radix);\n x /= radix;\n }\n // Generate string\n return new String(buf, i, buf.length - i);\n }\n }\n}\n", "file_name": "UnsignedNumberUtil.java", "human_label": "Compare two numbers.", "level": "self_contained", "lineno": "140", "name": "compareSigned", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "io.protostuff", "project": "protostuff-master" }, { "_id": "636767691a6d9265ec0181ae", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static String[] toStringArray(Enumeration enumeration){\n if (enumeration == null) {\n return null;\n }\n List list=java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n}\n", "docstring": "/** \n * Copy the given Enumeration into a String array. The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-inEnumeration was null)\n */\n", "end_lineno": "824", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *

\n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
\n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Convert an enumeration to a string array.", "level": "slib_runnable", "lineno": "811", "name": "toStringArray", "oracle_context": "{ \"apis\" : \"[toArray, size]\", \"classes\" : \"[List, java.util, java]\", \"vars\" : \"[Collections, util]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636766a91a6d9265ec0175ae", "all_context": "{ \"class_level\" : \"byte[] data;\\nint length;\\nByteVector(int initialCapacity);\\nput11(int byteValue1,int byteValue2);\\nputShort(int shortValue);\\nput12(int byteValue,int shortValue);\\nputInt(int intValue);\\nput122(int byteValue,int shortValue1,int shortValue2);\\nputLong(long longValue);\\nputUTF8(String stringValue);\\nencodeUtf8(String stringValue,int offset,int maxByteLength);\\nputByteArray(byte[] byteArrayValue,int byteOffset,int byteLength);\\nenlarge(int size);\\nputByte(int byteValue);\\n\", \"repo_level\" : \"\" }", "class_name": "ByteVector", "code": "public ByteVector putByteArray(final byte[] byteArrayValue,final int byteOffset,final int byteLength){\n if (length + byteLength > data.length) {\n enlarge(byteLength);\n }\n if (byteArrayValue != null) {\n System.arraycopy(byteArrayValue,byteOffset,data,length,byteLength);\n }\n length+=byteLength;\n return this;\n}\n", "docstring": "/** \n * Puts an array of bytes into this byte vector. The byte vector is automatically enlarged if necessary.\n * @param byteArrayValue an array of bytes. May be {@literal null} to put {@code byteLength} nullbytes into this byte vector.\n * @param byteOffset index of the first byte of byteArrayValue that must be copied.\n * @param byteLength number of bytes of byteArrayValue that must be copied.\n * @return this byte vector.\n */\n", "end_lineno": "319", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage com.alibaba.fastjson2.internal.asm;\n\n/**\n * A dynamically extensible vector of bytes. This class is roughly equivalent to a DataOutputStream\n * on top of a ByteArrayOutputStream, but is more efficient.\n *\n * @author Eric Bruneton\n */\npublic class ByteVector {\n /**\n * The content of this vector. Only the first {@link #length} bytes contain real data.\n */\n byte[] data;\n\n /**\n * The actual number of bytes in this vector.\n */\n int length;\n//\n// /**\n// * Constructs a new {@link ByteVector} with a default initial capacity.\n// */\n// public ByteVector() {\n// data = new byte[64];\n// }\n\n /**\n * Constructs a new {@link ByteVector} with the given initial capacity.\n *\n * @param initialCapacity the initial capacity of the byte vector to be constructed.\n */\n public ByteVector(final int initialCapacity) {\n data = new byte[initialCapacity];\n }\n\n /**\n * Puts a byte into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param byteValue a byte.\n * @return this byte vector.\n */\n public ByteVector putByte(final int byteValue) {\n int currentLength = length;\n if (currentLength + 1 > data.length) {\n enlarge(1);\n }\n data[currentLength++] = (byte) byteValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts two bytes into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param byteValue1 a byte.\n * @param byteValue2 another byte.\n * @return this byte vector.\n */\n final ByteVector put11(final int byteValue1, final int byteValue2) {\n int currentLength = length;\n if (currentLength + 2 > data.length) {\n enlarge(2);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue1;\n currentData[currentLength++] = (byte) byteValue2;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a short into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param shortValue a short.\n * @return this byte vector.\n */\n public ByteVector putShort(final int shortValue) {\n int currentLength = length;\n if (currentLength + 2 > data.length) {\n enlarge(2);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a byte and a short into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteValue a byte.\n * @param shortValue a short.\n * @return this byte vector.\n */\n final ByteVector put12(final int byteValue, final int shortValue) {\n int currentLength = length;\n if (currentLength + 3 > data.length) {\n enlarge(3);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an int into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param intValue an int.\n * @return this byte vector.\n */\n public ByteVector putInt(final int intValue) {\n int currentLength = length;\n if (currentLength + 4 > data.length) {\n enlarge(4);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts one byte and two shorts into this byte vector. The byte vector is automatically enlarged\n * if necessary.\n *\n * @param byteValue a byte.\n * @param shortValue1 a short.\n * @param shortValue2 another short.\n * @return this byte vector.\n */\n final ByteVector put122(final int byteValue, final int shortValue1, final int shortValue2) {\n int currentLength = length;\n if (currentLength + 5 > data.length) {\n enlarge(5);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue;\n currentData[currentLength++] = (byte) (shortValue1 >>> 8);\n currentData[currentLength++] = (byte) shortValue1;\n currentData[currentLength++] = (byte) (shortValue2 >>> 8);\n currentData[currentLength++] = (byte) shortValue2;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a long into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param longValue a long.\n * @return this byte vector.\n */\n public ByteVector putLong(final long longValue) {\n int currentLength = length;\n if (currentLength + 8 > data.length) {\n enlarge(8);\n }\n byte[] currentData = data;\n int intValue = (int) (longValue >>> 32);\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n intValue = (int) longValue;\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param stringValue a String whose UTF8 encoded length must be less than 65536.\n * @return this byte vector.\n */\n // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility).\n public ByteVector putUTF8(final String stringValue) {\n int charLength = stringValue.length();\n if (charLength > 65535) {\n throw new IllegalArgumentException(\"UTF8 string too large\");\n }\n int currentLength = length;\n if (currentLength + 2 + charLength > data.length) {\n enlarge(2 + charLength);\n }\n byte[] currentData = data;\n // Optimistic algorithm: instead of computing the byte length and then serializing the string\n // (which requires two loops), we assume the byte length is equal to char length (which is the\n // most frequent case), and we start serializing the string right away. During the\n // serialization, if we find that this assumption is wrong, we continue with the general method.\n currentData[currentLength++] = (byte) (charLength >>> 8);\n currentData[currentLength++] = (byte) charLength;\n for (int i = 0; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= '\\u0001' && charValue <= '\\u007F') {\n currentData[currentLength++] = (byte) charValue;\n } else {\n length = currentLength;\n return encodeUtf8(stringValue, i, 65535);\n }\n }\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if\n * necessary. The string length is encoded in two bytes before the encoded characters, if there is\n * space for that (i.e. if this.length - offset - 2 >= 0).\n *\n * @param stringValue the String to encode.\n * @param offset the index of the first character to encode. The previous characters are supposed\n * to have already been encoded, using only one byte per character.\n * @param maxByteLength the maximum byte length of the encoded string, including the already\n * encoded characters.\n * @return this byte vector.\n */\n final ByteVector encodeUtf8(final String stringValue, final int offset, final int maxByteLength) {\n int charLength = stringValue.length();\n int byteLength = offset;\n for (int i = offset; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= 0x0001 && charValue <= 0x007F) {\n byteLength++;\n } else if (charValue <= 0x07FF) {\n byteLength += 2;\n } else {\n byteLength += 3;\n }\n }\n if (byteLength > maxByteLength) {\n throw new IllegalArgumentException(\"UTF8 string too large\");\n }\n // Compute where 'byteLength' must be stored in 'data', and store it at this location.\n int byteLengthOffset = length - offset - 2;\n if (byteLengthOffset >= 0) {\n data[byteLengthOffset] = (byte) (byteLength >>> 8);\n data[byteLengthOffset + 1] = (byte) byteLength;\n }\n if (length + byteLength - offset > data.length) {\n enlarge(byteLength - offset);\n }\n int currentLength = length;\n for (int i = offset; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= 0x0001 && charValue <= 0x007F) {\n data[currentLength++] = (byte) charValue;\n } else if (charValue <= 0x07FF) {\n data[currentLength++] = (byte) (0xC0 | charValue >> 6 & 0x1F);\n data[currentLength++] = (byte) (0x80 | charValue & 0x3F);\n } else {\n data[currentLength++] = (byte) (0xE0 | charValue >> 12 & 0xF);\n data[currentLength++] = (byte) (0x80 | charValue >> 6 & 0x3F);\n data[currentLength++] = (byte) (0x80 | charValue & 0x3F);\n }\n }\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an array of bytes into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteArrayValue an array of bytes. May be {@literal null} to put {@code byteLength} null\n * bytes into this byte vector.\n * @param byteOffset index of the first byte of byteArrayValue that must be copied.\n * @param byteLength number of bytes of byteArrayValue that must be copied.\n * @return this byte vector.\n */\n public ByteVector putByteArray(\n final byte[] byteArrayValue, final int byteOffset, final int byteLength) {\n if (length + byteLength > data.length) {\n enlarge(byteLength);\n }\n if (byteArrayValue != null) {\n System.arraycopy(byteArrayValue, byteOffset, data, length, byteLength);\n }\n length += byteLength;\n return this;\n }\n\n /**\n * Enlarges this byte vector so that it can receive 'size' more bytes.\n *\n * @param size number of additional bytes that this byte vector should be able to receive.\n */\n private void enlarge(final int size) {\n int doubleCapacity = 2 * data.length;\n int minimalCapacity = length + size;\n byte[] newData = new byte[doubleCapacity > minimalCapacity ? doubleCapacity : minimalCapacity];\n System.arraycopy(data, 0, newData, 0, length);\n data = newData;\n }\n}\n", "file_name": "ByteVector.java", "human_label": "Add a byte array into the byte vector.", "level": "class_runnable", "lineno": "299", "name": "putByteArray", "oracle_context": "{ \"apis\" : \"[enlarge, arraycopy, ByteVector]\", \"classes\" : \"[data]\", \"vars\" : \"[length, data]\" }", "package": "com.alibaba.fastjson2.internal.asm", "project": "fastjson2-main" }, { "_id": "636766f11a6d9265ec01764f", "all_context": "{ \"class_level\" : \"import net.hasor.utils.BeanUtils;\\nimport java.beans.BeanInfo;\\nimport java.beans.IntrospectionException;\\nimport java.beans.Introspector;\\nimport java.beans.PropertyDescriptor;\\nimport java.lang.reflect.Constructor;\\nimport java.lang.reflect.InvocationTargetException;\\nimport java.lang.reflect.Method;\\nimport java.util.*;\\nObject bean;\\nMap readMethods;\\nMap writeMethods;\\nMap> types;\\nObject[] NULL_ARGUMENTS;\\nMap,Transformer> typeTransformers;\\nBeanMap owner;\\ncreateTypeTransformers();\\nBeanMap();\\nBeanMap(Object bean);\\nclone();\\nputAllWriteable(BeanMap map);\\nclear();\\ncontainsKey(Object name);\\ncontainsValue(Object value);\\nget(Object name);\\nput(String name,Object value);\\nsize();\\nkeySet();\\nentrySet();\\niterator();\\nvalues();\\ngetType(String name);\\nkeyIterator();\\nvalueIterator();\\nhasNext();\\nnext();\\nremove();\\nentryIterator();\\ngetBean();\\nsetBean(Object newBean);\\ngetReadMethod(String name);\\ngetWriteMethod(String name);\\ngetReadMethod(Object name);\\ngetWriteMethod(Object name);\\nreinitialise();\\ninitialise();\\nfirePropertyChange(Object key,Object oldValue,Object newValue);\\nEntry(BeanMap owner,String key,Object value);\\nsetValue(Object value);\\ncreateWriteMethodArguments(Method method,Object value);\\nconvertType(Class newType,Object value);\\ngetTypeTransformer(Class aType);\\nlogInfo(Exception ex);\\nlogWarn(Exception ex);\\ntoString();\\n\", \"repo_level\" : \"public interface BeanUtils {static Object getDefaultValue(Class returnType);\\nstatic Object[] getDefaultValue(Class[] paramArray);\\nstatic Object invokeMethod(Object target,String methodName,Object objects);\\nstatic List findALLFields(Class target);\\nstatic List findALLMethods(Class target);\\nstatic List getFields(Class type);\\nstatic List getMethods(Class type);\\nstatic Field getField(String fieldName,Class type);\\nstatic Method getMethod(Class atClass,String name,Class[] paramType);\\nstatic List getPropertiesAndFields(Class target);\\nstatic List getProperties(Class target);\\nstatic PropertyDescriptor[] getPropertyDescriptors(Class defineType);\\nstatic Method getReadMethod(String property,Class target);\\nstatic Method getWriteMethod(String property,Class target);\\nstatic boolean hasProperty(String propertyName,Class target);\\nstatic boolean hasField(String propertyName,Class target);\\nstatic boolean hasPropertyOrField(String name,Class target);\\nstatic boolean canReadProperty(String propertyName,Class target);\\nstatic boolean canReadPropertyOrField(String propertyName,Class target);\\nstatic boolean canWriteProperty(String propertyName,Class target);\\nstatic boolean canWriteField(String propertyName,Class target);\\nstatic boolean canWritePropertyOrField(String propertyName,Class target);\\nstatic boolean writeProperty(Object object,String attName,Object value);\\nstatic boolean writeField(Object object,String fieldName,Object value);\\nstatic boolean writePropertyOrField(Object object,String attName,Object value);\\nstatic Object readProperty(Object object,String attName);\\nstatic Object readField(Object object,String fieldName);\\nstatic Object readPropertyOrField(Object object,String attName);\\nstatic Class getPropertyType(Class defineType,String attName);\\nstatic Class getFieldType(Class defineType,String attName);\\nstatic Class getPropertyOrFieldType(Class defineType,String attName);\\nstatic void copyProperties(Object dest,Object orig);\\nstatic void copyProperty(Object dest,Object orig,String propertyName);\\n }\\n\" }", "class_name": "BeanMap", "code": "public Collection values(){\n ArrayList answer=new ArrayList<>(readMethods.size());\n for (Iterator iter=valueIterator(); iter.hasNext(); ) {\n answer.add(iter.next());\n }\n return Collections.unmodifiableList(answer);\n}\n", "docstring": "/** \n * Returns the values for the BeanMap.\n * @return values for the BeanMap. The returned collection is not modifiable.\n */\n", "end_lineno": "316", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.ref;\nimport net.hasor.utils.BeanUtils;\n\nimport java.beans.BeanInfo;\nimport java.beans.IntrospectionException;\nimport java.beans.Introspector;\nimport java.beans.PropertyDescriptor;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.*;\n\n/**\n * An implementation of Map for JavaBeans which uses introspection to\n * get and put properties in the bean.\n *

\n * If an exception occurs during attempts to get or set a property then the\n * property is considered non existent in the Map\n *\n * @version $Revision: 812176 $ $Date: 2009-09-07 15:59:25 +0100 (Mon, 07 Sep 2009) $\n *\n * @author James Strachan\n * @author Stephen Colebourne\n */\npublic class BeanMap extends AbstractMap implements Cloneable {\n private transient Object bean;\n private transient Map readMethods = new LinkedHashMap<>();\n private transient Map writeMethods = new LinkedHashMap<>();\n private transient Map> types = new LinkedHashMap<>();\n /** An empty array. Used to invoke accessors via reflection. */\n public static final Object[] NULL_ARGUMENTS = {};\n /**\n * Maps primitive Class types to transformers. The transformer\n * transform strings into the appropriate primitive wrapper.\n * N.B. private & unmodifiable replacement for the (public & static) defaultTransformers instance.\n */\n private static final Map, Transformer> typeTransformers = Collections.unmodifiableMap(createTypeTransformers());\n\n private static Map, Transformer> createTypeTransformers() {\n Map, Transformer> defaultTransformers = new HashMap<>();\n defaultTransformers.put(Boolean.TYPE, input -> Boolean.valueOf(input.toString()));\n defaultTransformers.put(Character.TYPE, input -> input.toString().charAt(0));\n defaultTransformers.put(Byte.TYPE, input -> Byte.valueOf(input.toString()));\n defaultTransformers.put(Short.TYPE, input -> Short.valueOf(input.toString()));\n defaultTransformers.put(Integer.TYPE, input -> Integer.valueOf(input.toString()));\n defaultTransformers.put(Long.TYPE, input -> Long.valueOf(input.toString()));\n defaultTransformers.put(Float.TYPE, input -> Float.valueOf(input.toString()));\n defaultTransformers.put(Double.TYPE, input -> Double.valueOf(input.toString()));\n return defaultTransformers;\n }\n // Constructors\n //-------------------------------------------------------------------------\n\n /** Constructs a new empty BeanMap. */\n public BeanMap() {\n }\n\n /**\n * Constructs a new BeanMap that operates on the specified bean.\n * If the given bean is null, then this map will be empty.\n * @param bean the bean for this map to operate on\n */\n public BeanMap(Object bean) {\n this.bean = bean;\n initialise();\n }\n // Map interface\n //-------------------------------------------------------------------------\n\n /**\n * Renders a string representation of this object.\n * @return a String representation of this object\n */\n public String toString() {\n return \"BeanMap<\" + bean + \">\";\n }\n\n /**\n * Clone this bean map using the following process: \n *

    \n *
  • If there is no underlying bean, return a cloned BeanMap without a bean.\n *\n *
  • Since there is an underlying bean, try to instantiate a new bean of\n * the same type using Class.newInstance().\n *\n *
  • If the instantiation fails, throw a CloneNotSupportedException\n *\n *
  • Clone the bean map and set the newly instantiated bean as the\n * underlying bean for the bean map.\n *\n *
  • Copy each property that is both readable and writable from the\n * existing object to a cloned bean map. \n *\n *
  • If anything fails along the way, throw a CloneNotSupportedException.\n *
      \n *\n * @return a cloned instance of this bean map\n * @throws CloneNotSupportedException if the underlying bean cannot be cloned\n */\n public Object clone() throws CloneNotSupportedException {\n BeanMap newMap = (BeanMap) super.clone();\n if (bean == null) {\n // no bean, just an empty bean map at the moment. return a newly\n // cloned and empty bean map.\n return newMap;\n }\n Object newBean = null;\n Class beanClass = bean.getClass(); // Cannot throw Exception\n try {\n newBean = beanClass.newInstance();\n } catch (Exception e) {\n // unable to instantiate\n throw new CloneNotSupportedException(\"Unable to instantiate the underlying bean \\\"\" + beanClass.getName() + \"\\\": \" + e);\n }\n try {\n newMap.setBean(newBean);\n } catch (Exception exception) {\n throw new CloneNotSupportedException(\"Unable to set bean in the cloned bean map: \" + exception);\n }\n try {\n // copy only properties that are readable and writable. If its\n // not readable, we can't get the value from the old map. If\n // its not writable, we can't write a value into the new map.\n Iterator readableKeys = readMethods.keySet().iterator();\n while (readableKeys.hasNext()) {\n String key = readableKeys.next();\n if (getWriteMethod(key) != null) {\n newMap.put(key, get(key));\n }\n }\n } catch (Exception exception) {\n throw new CloneNotSupportedException(\"Unable to copy bean values to cloned bean map: \" + exception);\n }\n return newMap;\n }\n\n /**\n * Puts all of the writable properties from the given BeanMap into this\n * BeanMap. Read-only and Write-only properties will be ignored.\n * @param map the BeanMap whose properties to put\n */\n public void putAllWriteable(BeanMap map) {\n Iterator readableKeys = map.readMethods.keySet().iterator();\n while (readableKeys.hasNext()) {\n String key = readableKeys.next();\n if (getWriteMethod(key) != null) {\n this.put(key, map.get(key));\n }\n }\n }\n\n /**\n * This method reinitializes the bean map to have default values for the\n * bean's properties. This is accomplished by constructing a new instance\n * of the bean which the map uses as its underlying data source.\n * This behavior for clear() differs from the Map contract in that\n * the mappings are not actually removed from the map (the mappings for a BeanMap are fixed).\n */\n public void clear() {\n if (bean == null) {\n return;\n }\n Class beanClass = null;\n try {\n beanClass = bean.getClass();\n bean = beanClass.newInstance();\n } catch (Exception e) {\n throw new UnsupportedOperationException(\"Could not create new instance of class: \" + beanClass);\n }\n }\n\n /**\n * Returns true if the bean defines a property with the given name.

      \n * The given name must be a String; if not, this method\n * returns false. This method will also return false if the bean\n * does not define a property with that name.

      \n * Write-only properties will not be matched as the test operates against property read methods.\n *\n * @param name the name of the property to check\n * @return false if the given name is null or is not a String;\n * false if the bean does not define a property with that name; or\n * true if the bean does define a property with that name\n */\n public boolean containsKey(Object name) {\n Method method = getReadMethod(name);\n return method != null;\n }\n\n /**\n * Returns true if the bean defines a property whose current value is the given object.\n * @param value the value to check\n * @return false true if the bean has at least one property whose current value is that object, false otherwise\n */\n public boolean containsValue(Object value) {\n // use default implementation\n return super.containsValue(value);\n }\n\n /**\n * Returns the value of the bean's property with the given name.

      \n * The given name must be a {@link String} and must not be \n * null; otherwise, this method returns null.\n * If the bean defines a property with the given name, the value of\n * that property is returned. Otherwise, null is returned.

      \n * Write-only properties will not be matched as the test operates against property read methods.\n *\n * @param name the name of the property whose value to return\n * @return the value of the property with that name\n */\n public Object get(Object name) {\n if (bean != null) {\n Method method = getReadMethod(name);\n if (method != null) {\n try {\n return method.invoke(bean, NULL_ARGUMENTS);\n } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NullPointerException e) {\n logWarn(e);\n }\n }\n }\n return null;\n }\n\n /**\n * Sets the bean property with the given name to the given value.\n * @param name the name of the property to set\n * @param value the value to set that property to\n * @return the previous value of that property\n * @throws IllegalArgumentException if the given name is null; \n * if the given name is not a {@link String}; if the bean doesn't\n * define a property with that name; or if the bean property with that name is read-only\n * @throws ClassCastException if an error occurs creating the method args\n */\n public Object put(String name, Object value) throws IllegalArgumentException, ClassCastException {\n if (bean != null) {\n Object oldValue = get(name);\n Method method = getWriteMethod(name);\n if (method == null) {\n throw new IllegalArgumentException(\"The bean of type: \" + bean.getClass().getName() + \" has no property called: \" + name);\n }\n try {\n Object[] arguments = createWriteMethodArguments(method, value);\n method.invoke(bean, arguments);\n Object newValue = get(name);\n firePropertyChange(name, oldValue, newValue);\n } catch (InvocationTargetException | IllegalAccessException e) {\n logInfo(e);\n throw new IllegalArgumentException(e.getMessage());\n }\n return oldValue;\n }\n return null;\n }\n\n /**\n * Returns the number of properties defined by the bean.\n * @return the number of properties defined by the bean\n */\n public int size() {\n return readMethods.size();\n }\n\n /**\n * Get the keys for this BeanMap.

      \n * Write-only properties are not included in the returned set of\n * property names, although it is possible to set their value and to get their type.\n * @return BeanMap keys. The Set returned by this method is not modifiable.\n */\n public Set keySet() {\n return Collections.unmodifiableSet(readMethods.keySet());\n }\n\n /**\n * Gets a Set of MapEntry objects that are the mappings for this BeanMap.

      \n * Each MapEntry can be set but not removed.\n * @return the unmodifiable set of mappings\n */\n public Set> entrySet() {\n return Collections.unmodifiableSet(new AbstractSet>() {\n public Iterator> iterator() {\n return entryIterator();\n }\n\n public int size() {\n return BeanMap.this.readMethods.size();\n }\n });\n }\n\n /**\n * Returns the values for the BeanMap.\n * @return values for the BeanMap. The returned collection is not modifiable.\n */\n public Collection values() {\n ArrayList answer = new ArrayList<>(readMethods.size());\n for (Iterator iter = valueIterator(); iter.hasNext(); ) {\n answer.add(iter.next());\n }\n return Collections.unmodifiableList(answer);\n }\n // Helper methods\n //-------------------------------------------------------------------------\n\n /**\n * Returns the type of the property with the given name.\n * @param name the name of the property\n * @return the type of the property, or null if no such property exists\n */\n public Class getType(String name) {\n return types.get(name);\n }\n\n /**\n * Convenience method for getting an iterator over the keys.

      \n * Write-only properties will not be returned in the iterator.\n * @return an iterator over the keys\n */\n public Iterator keyIterator() {\n return readMethods.keySet().iterator();\n }\n\n /**\n * Convenience method for getting an iterator over the values.\n * @return an iterator over the values\n */\n public Iterator valueIterator() {\n final Iterator iter = keyIterator();\n return new Iterator() {\n public boolean hasNext() {\n return iter.hasNext();\n }\n\n public Object next() {\n Object key = iter.next();\n return get(key);\n }\n\n public void remove() {\n throw new UnsupportedOperationException(\"remove() not supported for BeanMap\");\n }\n };\n }\n\n /**\n * Convenience method for getting an iterator over the entries.\n * @return an iterator over the entries\n */\n public Iterator> entryIterator() {\n final Iterator iter = keyIterator();\n return new Iterator>() {\n public boolean hasNext() {\n return iter.hasNext();\n }\n\n public Map.Entry next() {\n String key = iter.next();\n Object value = get(key);\n return new Entry(BeanMap.this, key, value);\n }\n\n public void remove() {\n throw new UnsupportedOperationException(\"remove() not supported for BeanMap\");\n }\n };\n }\n // Properties\n //-------------------------------------------------------------------------\n\n /**\n * Returns the bean currently being operated on. The return value may be null if this map is empty.\n * @return the bean being operated on by this map\n */\n public Object getBean() {\n return bean;\n }\n\n /**\n * Sets the bean to be operated on by this map. The given value may be null, in which case this map will be empty.\n * @param newBean the new bean to operate on\n */\n public void setBean(Object newBean) {\n bean = newBean;\n reinitialise();\n }\n\n /**\n * Returns the accessor for the property with the given name.\n * @param name the name of the property \n * @return the accessor method for the property, or null\n */\n public Method getReadMethod(String name) {\n return readMethods.get(name);\n }\n\n /**\n * Returns the mutator for the property with the given name.\n * @param name the name of the property\n * @return the mutator method for the property, or null\n */\n public Method getWriteMethod(String name) {\n return writeMethods.get(name);\n }\n // Implementation methods\n //-------------------------------------------------------------------------\n\n /**\n * Returns the accessor for the property with the given name.\n * @param name the name of the property \n * @return null if the name is null; null if the name is not a {@link String};\n * null if no such property exists; or the accessor method for that property\n */\n protected Method getReadMethod(Object name) {\n return readMethods.get(name);\n }\n\n /**\n * Returns the mutator for the property with the given name.\n * @param name the name of the \n * @return null if the name is null; null if the name is not a {@link String};\n * null if no such property exists; null if the property is read-only; or the mutator method for that property\n */\n protected Method getWriteMethod(Object name) {\n return writeMethods.get(name);\n }\n\n /** Reinitializes this bean. Called during {@link #setBean(Object)}. Does introspection to find properties. */\n protected void reinitialise() {\n readMethods.clear();\n writeMethods.clear();\n types.clear();\n initialise();\n }\n\n private void initialise() {\n if (getBean() == null) {\n return;\n }\n Class beanClass = getBean().getClass();\n try {\n Map pd = new LinkedHashMap<>();\n // 为了有序\n BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);\n PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();\n BeanUtils.getProperties(beanClass).forEach(s -> pd.put(s, null));\n if (propertyDescriptors != null) {\n for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {\n pd.put(propertyDescriptor.getName(), propertyDescriptor);\n }\n }\n // 为了有序\n pd.forEach((name, propertyDescriptor) -> {\n if (propertyDescriptor == null) {\n return;\n }\n Method readMethod = propertyDescriptor.getReadMethod();\n Method writeMethod = propertyDescriptor.getWriteMethod();\n Class aType = propertyDescriptor.getPropertyType();\n if (readMethod != null) {\n readMethods.put(name, readMethod);\n }\n if (writeMethod != null) {\n writeMethods.put(name, writeMethod);\n }\n types.put(name, aType);\n });\n } catch (IntrospectionException e) {\n logWarn(e);\n }\n }\n\n /**\n * Called during a successful {@link #put(String, Object)} operation.\n * Default implementation does nothing. Override to be notified of\n * property changes in the bean caused by this map.\n *\n * @param key the name of the property that changed\n * @param oldValue the old value for that property\n * @param newValue the new value for that property\n */\n protected void firePropertyChange(Object key, Object oldValue, Object newValue) {\n }\n // Implementation classes\n //-------------------------------------------------------------------------\n\n /** Map entry used by {@link BeanMap}. */\n protected static class Entry extends AbstractMapEntry {\n private BeanMap owner;\n\n /**\n * Constructs a new Entry.\n * @param owner the BeanMap this entry belongs to\n * @param key the key for this entry\n * @param value the value for this entry\n */\n protected Entry(BeanMap owner, String key, Object value) {\n super(key, value);\n this.owner = owner;\n }\n\n /**\n * Sets the value.\n * @param value the new value for the entry\n * @return the old value for the entry\n */\n public Object setValue(Object value) {\n String key = getKey();\n Object oldValue = owner.get(key);\n owner.put(key, value);\n super.value = owner.get(key);\n return oldValue;\n }\n }\n\n /**\n * Creates an array of parameters to pass to the given mutator method.\n * If the given object is not the right type to pass to the method \n * directly, it will be converted using {@link #convertType(Class, Object)}.\n *\n * @param method the mutator method\n * @param value the value to pass to the mutator method\n * @return an array containing one object that is either the given value or a transformed value\n * @throws IllegalAccessException if {@link #convertType(Class, Object)} raises it\n * @throws IllegalArgumentException if any other exception is raised by {@link #convertType(Class, Object)}\n * @throws ClassCastException if an error occurs creating the method args\n */\n protected Object[] createWriteMethodArguments(Method method, Object value) throws IllegalAccessException, ClassCastException {\n try {\n if (value != null) {\n Class[] types = method.getParameterTypes();\n if (types != null && types.length > 0) {\n Class paramType = types[0];\n if (!paramType.isAssignableFrom(value.getClass())) {\n value = convertType(paramType, value);\n }\n }\n }\n Object[] answer = { value };\n return answer;\n } catch (InvocationTargetException | InstantiationException e) {\n logInfo(e);\n throw new IllegalArgumentException(e.getMessage());\n }\n }\n\n /**\n * Converts the given value to the given type. First, reflection is\n * is used to find a public constructor declared by the given class \n * that takes one argument, which must be the precise type of the \n * given value. If such a constructor is found, a new object is\n * created by passing the given value to that constructor, and the\n * newly constructed object is returned.

      \n *\n * If no such constructor exists, and the given type is a primitive\n * type, then the given value is converted to a string using its \n * {@link Object#toString() toString()} method, and that string is\n * parsed into the correct primitive type using, for instance, \n * {@link Integer#valueOf(String)} to convert the string into an\n * int.

      \n *\n * If no special constructor exists and the given type is not a \n * primitive type, this method returns the original value.\n *\n * @param newType the type to convert the value to\n * @param value the value to convert\n * @return the converted value\n * @throws NumberFormatException if newType is a primitive type, and \n * the string representation of the given value cannot be converted to that type\n * @throws InstantiationException if the constructor found with \n * reflection raises it\n * @throws InvocationTargetException if the constructor found with\n * reflection raises it\n * @throws IllegalAccessException never\n * @throws IllegalArgumentException never\n */\n protected Object convertType(Class newType, Object value) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {\n // try call constructor\n Class[] types = { value.getClass() };\n try {\n Constructor constructor = newType.getConstructor(types);\n Object[] arguments = { value };\n return constructor.newInstance(arguments);\n } catch (NoSuchMethodException e) {\n // try using the transformers\n Transformer transformer = getTypeTransformer(newType);\n if (transformer != null) {\n return transformer.transform(value);\n }\n return value;\n }\n }\n\n /**\n * Returns a transformer for the given primitive type.\n *\n * @param aType the primitive type whose transformer to return\n * @return a transformer that will convert strings into that type,\n * or null if the given type is not a primitive type\n */\n protected Transformer getTypeTransformer(Class aType) {\n return typeTransformers.get(aType);\n }\n\n /**\n * Logs the given exception to System.out. Used to display\n * warnings while accessing/mutating the bean.\n *\n * @param ex the exception to log\n */\n protected void logInfo(Exception ex) {\n // Deliberately do not use LOG4J or Commons Logging to avoid dependencies\n System.out.println(\"INFO: Exception: \" + ex);\n }\n\n /**\n * Logs the given exception to System.err. Used to display\n * errors while accessing/mutating the bean.\n *\n * @param ex the exception to log\n */\n protected void logWarn(Exception ex) {\n // Deliberately do not use LOG4J or Commons Logging to avoid dependencies\n System.out.println(\"WARN: Exception: \" + ex);\n ex.printStackTrace();\n }\n}\n", "file_name": "BeanMap.java", "human_label": "Return an unmodifiable list that contains all methods in the BeanMap.", "level": "class_runnable", "lineno": "306", "name": "values", "oracle_context": "{ \"apis\" : \"[size, valueIterator, hasNext, add, next, unmodifiableList]\", \"classes\" : \"[ArrayList]\", \"vars\" : \"[readMethods]\" }", "package": "net.hasor.utils.ref", "project": "hasor-master" }, { "_id": "636766f81a6d9265ec017758", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Constructor;\\nimport java.lang.reflect.Method;\\nint VOID;\\nint BOOLEAN;\\nint CHAR;\\nint BYTE;\\nint SHORT;\\nint INT;\\nint FLOAT;\\nint LONG;\\nint DOUBLE;\\nint ARRAY;\\nint OBJECT;\\nint METHOD;\\nint INTERNAL;\\nString PRIMITIVE_DESCRIPTORS;\\nType VOID_TYPE;\\nType BOOLEAN_TYPE;\\nType CHAR_TYPE;\\nType BYTE_TYPE;\\nType SHORT_TYPE;\\nType INT_TYPE;\\nType FLOAT_TYPE;\\nType LONG_TYPE;\\nType DOUBLE_TYPE;\\nint sort;\\nString valueBuffer;\\nint valueBegin;\\nint valueEnd;\\nType(int sort,String valueBuffer,int valueBegin,int valueEnd);\\ngetType(String typeDescriptor);\\ngetType(Class clazz);\\ngetType(Constructor constructor);\\ngetType(Method method);\\ngetElementType();\\ngetObjectType(String internalName);\\ngetMethodType(String methodDescriptor);\\ngetMethodType(Type returnType,Type argumentTypes);\\ngetArgumentTypes();\\ngetArgumentTypes(String methodDescriptor);\\ngetArgumentTypes(Method method);\\ngetReturnType();\\ngetReturnType(String methodDescriptor);\\ngetReturnType(Method method);\\ngetReturnTypeOffset(String methodDescriptor);\\ngetTypeInternal(String descriptorBuffer,int descriptorBegin,int descriptorEnd);\\ngetClassName();\\ngetInternalName();\\ngetInternalName(Class clazz);\\ngetDescriptor();\\ngetDescriptor(Class clazz);\\ngetConstructorDescriptor(Constructor constructor);\\ngetMethodDescriptor(Type returnType,Type argumentTypes);\\ngetMethodDescriptor(Method method);\\nappendDescriptor(Class clazz,StringBuilder stringBuilder);\\ngetSort();\\ngetDimensions();\\ngetSize();\\ngetArgumentsAndReturnSizes();\\ngetArgumentsAndReturnSizes(String methodDescriptor);\\ngetOpcode(int opcode);\\nequals(Object object);\\nhashCode();\\ntoString();\\nappendDescriptor(StringBuilder stringBuilder);\\n\", \"repo_level\" : \"\" }", "class_name": "Type", "code": "@Override public int hashCode(){\n int hashCode=13 * (sort == INTERNAL ? OBJECT : sort);\n if (sort >= ARRAY) {\n for (int i=valueBegin, end=valueEnd; i < end; i++) {\n hashCode=17 * (hashCode + valueBuffer.charAt(i));\n }\n }\n return hashCode;\n}\n", "docstring": "/** \n * Returns a hash code value for this type.\n * @return a hash code value for this type.\n */\n", "end_lineno": "844", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage net.hasor.utils.asm;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Method;\n\n/**\n * A Java field or method type. This class can be used to make it easier to manipulate type and\n * method descriptors.\n *\n * @author Eric Bruneton\n * @author Chris Nokleberg\n */\npublic final class Type {\n /** The sort of the {@code void} type. See {@link #getSort}. */\n public static final int VOID = 0;\n /** The sort of the {@code boolean} type. See {@link #getSort}. */\n public static final int BOOLEAN = 1;\n /** The sort of the {@code char} type. See {@link #getSort}. */\n public static final int CHAR = 2;\n /** The sort of the {@code byte} type. See {@link #getSort}. */\n public static final int BYTE = 3;\n /** The sort of the {@code short} type. See {@link #getSort}. */\n public static final int SHORT = 4;\n /** The sort of the {@code int} type. See {@link #getSort}. */\n public static final int INT = 5;\n /** The sort of the {@code float} type. See {@link #getSort}. */\n public static final int FLOAT = 6;\n /** The sort of the {@code long} type. See {@link #getSort}. */\n public static final int LONG = 7;\n /** The sort of the {@code double} type. See {@link #getSort}. */\n public static final int DOUBLE = 8;\n /** The sort of array reference types. See {@link #getSort}. */\n public static final int ARRAY = 9;\n /** The sort of object reference types. See {@link #getSort}. */\n public static final int OBJECT = 10;\n /** The sort of method types. See {@link #getSort}. */\n public static final int METHOD = 11;\n /** The (private) sort of object reference types represented with an internal name. */\n private static final int INTERNAL = 12;\n /** The descriptors of the primitive types. */\n private static final String PRIMITIVE_DESCRIPTORS = \"VZCBSIFJD\";\n /** The {@code void} type. */\n public static final Type VOID_TYPE = new Type(VOID, PRIMITIVE_DESCRIPTORS, VOID, VOID + 1);\n /** The {@code boolean} type. */\n public static final Type BOOLEAN_TYPE = new Type(BOOLEAN, PRIMITIVE_DESCRIPTORS, BOOLEAN, BOOLEAN + 1);\n /** The {@code char} type. */\n public static final Type CHAR_TYPE = new Type(CHAR, PRIMITIVE_DESCRIPTORS, CHAR, CHAR + 1);\n /** The {@code byte} type. */\n public static final Type BYTE_TYPE = new Type(BYTE, PRIMITIVE_DESCRIPTORS, BYTE, BYTE + 1);\n /** The {@code short} type. */\n public static final Type SHORT_TYPE = new Type(SHORT, PRIMITIVE_DESCRIPTORS, SHORT, SHORT + 1);\n /** The {@code int} type. */\n public static final Type INT_TYPE = new Type(INT, PRIMITIVE_DESCRIPTORS, INT, INT + 1);\n /** The {@code float} type. */\n public static final Type FLOAT_TYPE = new Type(FLOAT, PRIMITIVE_DESCRIPTORS, FLOAT, FLOAT + 1);\n /** The {@code long} type. */\n public static final Type LONG_TYPE = new Type(LONG, PRIMITIVE_DESCRIPTORS, LONG, LONG + 1);\n /** The {@code double} type. */\n public static final Type DOUBLE_TYPE = new Type(DOUBLE, PRIMITIVE_DESCRIPTORS, DOUBLE, DOUBLE + 1);\n // -----------------------------------------------------------------------------------------------\n // Fields\n // -----------------------------------------------------------------------------------------------\n /**\n * The sort of this type. Either {@link #VOID}, {@link #BOOLEAN}, {@link #CHAR}, {@link #BYTE},\n * {@link #SHORT}, {@link #INT}, {@link #FLOAT}, {@link #LONG}, {@link #DOUBLE}, {@link #ARRAY},\n * {@link #OBJECT}, {@link #METHOD} or {@link #INTERNAL}.\n */\n private final int sort;\n /**\n * A buffer containing the value of this field or method type. This value is an internal name for\n * {@link #OBJECT} and {@link #INTERNAL} types, and a field or method descriptor in the other\n * cases.\n *\n *

      For {@link #OBJECT} types, this field also contains the descriptor: the characters in\n * [{@link #valueBegin},{@link #valueEnd}) contain the internal name, and those in [{@link\n * #valueBegin} - 1, {@link #valueEnd} + 1) contain the descriptor.\n */\n private final String valueBuffer;\n /**\n * The beginning index, inclusive, of the value of this Java field or method type in {@link\n * #valueBuffer}. This value is an internal name for {@link #OBJECT} and {@link #INTERNAL} types,\n * and a field or method descriptor in the other cases.\n */\n private final int valueBegin;\n /**\n * The end index, exclusive, of the value of this Java field or method type in {@link\n * #valueBuffer}. This value is an internal name for {@link #OBJECT} and {@link #INTERNAL} types,\n * and a field or method descriptor in the other cases.\n */\n private final int valueEnd;\n\n /**\n * Constructs a reference type.\n *\n * @param sort the sort of this type, see {@link #sort}.\n * @param valueBuffer a buffer containing the value of this field or method type.\n * @param valueBegin the beginning index, inclusive, of the value of this field or method type in\n * valueBuffer.\n * @param valueEnd the end index, exclusive, of the value of this field or method type in\n * valueBuffer.\n */\n private Type(final int sort, final String valueBuffer, final int valueBegin, final int valueEnd) {\n this.sort = sort;\n this.valueBuffer = valueBuffer;\n this.valueBegin = valueBegin;\n this.valueEnd = valueEnd;\n }\n // -----------------------------------------------------------------------------------------------\n // Methods to get Type(s) from a descriptor, a reflected Method or Constructor, other types, etc.\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the {@link Type} corresponding to the given type descriptor.\n *\n * @param typeDescriptor a field or method type descriptor.\n * @return the {@link Type} corresponding to the given type descriptor.\n */\n public static Type getType(final String typeDescriptor) {\n return getTypeInternal(typeDescriptor, 0, typeDescriptor.length());\n }\n\n /**\n * Returns the {@link Type} corresponding to the given class.\n *\n * @param clazz a class.\n * @return the {@link Type} corresponding to the given class.\n */\n public static Type getType(final Class clazz) {\n if (clazz.isPrimitive()) {\n if (clazz == Integer.TYPE) {\n return INT_TYPE;\n } else if (clazz == Void.TYPE) {\n return VOID_TYPE;\n } else if (clazz == Boolean.TYPE) {\n return BOOLEAN_TYPE;\n } else if (clazz == Byte.TYPE) {\n return BYTE_TYPE;\n } else if (clazz == Character.TYPE) {\n return CHAR_TYPE;\n } else if (clazz == Short.TYPE) {\n return SHORT_TYPE;\n } else if (clazz == Double.TYPE) {\n return DOUBLE_TYPE;\n } else if (clazz == Float.TYPE) {\n return FLOAT_TYPE;\n } else if (clazz == Long.TYPE) {\n return LONG_TYPE;\n } else {\n throw new AssertionError();\n }\n } else {\n return getType(getDescriptor(clazz));\n }\n }\n\n /**\n * Returns the method {@link Type} corresponding to the given constructor.\n *\n * @param constructor a {@link Constructor} object.\n * @return the method {@link Type} corresponding to the given constructor.\n */\n public static Type getType(final Constructor constructor) {\n return getType(getConstructorDescriptor(constructor));\n }\n\n /**\n * Returns the method {@link Type} corresponding to the given method.\n *\n * @param method a {@link Method} object.\n * @return the method {@link Type} corresponding to the given method.\n */\n public static Type getType(final Method method) {\n return getType(getMethodDescriptor(method));\n }\n\n /**\n * Returns the type of the elements of this array type. This method should only be used for an\n * array type.\n *\n * @return Returns the type of the elements of this array type.\n */\n public Type getElementType() {\n final int numDimensions = getDimensions();\n return getTypeInternal(valueBuffer, valueBegin + numDimensions, valueEnd);\n }\n\n /**\n * Returns the {@link Type} corresponding to the given internal name.\n *\n * @param internalName an internal name.\n * @return the {@link Type} corresponding to the given internal name.\n */\n public static Type getObjectType(final String internalName) {\n return new Type(internalName.charAt(0) == '[' ? ARRAY : INTERNAL, internalName, 0, internalName.length());\n }\n\n /**\n * Returns the {@link Type} corresponding to the given method descriptor. Equivalent to \n * Type.getType(methodDescriptor).\n *\n * @param methodDescriptor a method descriptor.\n * @return the {@link Type} corresponding to the given method descriptor.\n */\n public static Type getMethodType(final String methodDescriptor) {\n return new Type(METHOD, methodDescriptor, 0, methodDescriptor.length());\n }\n\n /**\n * Returns the method {@link Type} corresponding to the given argument and return types.\n *\n * @param returnType the return type of the method.\n * @param argumentTypes the argument types of the method.\n * @return the method {@link Type} corresponding to the given argument and return types.\n */\n public static Type getMethodType(final Type returnType, final Type... argumentTypes) {\n return getType(getMethodDescriptor(returnType, argumentTypes));\n }\n\n /**\n * Returns the argument types of methods of this type. This method should only be used for method\n * types.\n *\n * @return the argument types of methods of this type.\n */\n public Type[] getArgumentTypes() {\n return getArgumentTypes(getDescriptor());\n }\n\n /**\n * Returns the {@link Type} values corresponding to the argument types of the given method\n * descriptor.\n *\n * @param methodDescriptor a method descriptor.\n * @return the {@link Type} values corresponding to the argument types of the given method\n * descriptor.\n */\n public static Type[] getArgumentTypes(final String methodDescriptor) {\n // First step: compute the number of argument types in methodDescriptor.\n int numArgumentTypes = 0;\n // Skip the first character, which is always a '('.\n int currentOffset = 1;\n // Parse the argument types, one at a each loop iteration.\n while (methodDescriptor.charAt(currentOffset) != ')') {\n while (methodDescriptor.charAt(currentOffset) == '[') {\n currentOffset++;\n }\n if (methodDescriptor.charAt(currentOffset++) == 'L') {\n // Skip the argument descriptor content.\n int semiColumnOffset = methodDescriptor.indexOf(';', currentOffset);\n currentOffset = Math.max(currentOffset, semiColumnOffset + 1);\n }\n ++numArgumentTypes;\n }\n // Second step: create a Type instance for each argument type.\n Type[] argumentTypes = new Type[numArgumentTypes];\n // Skip the first character, which is always a '('.\n currentOffset = 1;\n // Parse and create the argument types, one at each loop iteration.\n int currentArgumentTypeIndex = 0;\n while (methodDescriptor.charAt(currentOffset) != ')') {\n final int currentArgumentTypeOffset = currentOffset;\n while (methodDescriptor.charAt(currentOffset) == '[') {\n currentOffset++;\n }\n if (methodDescriptor.charAt(currentOffset++) == 'L') {\n // Skip the argument descriptor content.\n int semiColumnOffset = methodDescriptor.indexOf(';', currentOffset);\n currentOffset = Math.max(currentOffset, semiColumnOffset + 1);\n }\n argumentTypes[currentArgumentTypeIndex++] = getTypeInternal(methodDescriptor, currentArgumentTypeOffset, currentOffset);\n }\n return argumentTypes;\n }\n\n /**\n * Returns the {@link Type} values corresponding to the argument types of the given method.\n *\n * @param method a method.\n * @return the {@link Type} values corresponding to the argument types of the given method.\n */\n public static Type[] getArgumentTypes(final Method method) {\n Class[] classes = method.getParameterTypes();\n Type[] types = new Type[classes.length];\n for (int i = classes.length - 1; i >= 0; --i) {\n types[i] = getType(classes[i]);\n }\n return types;\n }\n\n /**\n * Returns the return type of methods of this type. This method should only be used for method\n * types.\n *\n * @return the return type of methods of this type.\n */\n public Type getReturnType() {\n return getReturnType(getDescriptor());\n }\n\n /**\n * Returns the {@link Type} corresponding to the return type of the given method descriptor.\n *\n * @param methodDescriptor a method descriptor.\n * @return the {@link Type} corresponding to the return type of the given method descriptor.\n */\n public static Type getReturnType(final String methodDescriptor) {\n return getTypeInternal(methodDescriptor, getReturnTypeOffset(methodDescriptor), methodDescriptor.length());\n }\n\n /**\n * Returns the {@link Type} corresponding to the return type of the given method.\n *\n * @param method a method.\n * @return the {@link Type} corresponding to the return type of the given method.\n */\n public static Type getReturnType(final Method method) {\n return getType(method.getReturnType());\n }\n\n /**\n * Returns the start index of the return type of the given method descriptor.\n *\n * @param methodDescriptor a method descriptor.\n * @return the start index of the return type of the given method descriptor.\n */\n static int getReturnTypeOffset(final String methodDescriptor) {\n // Skip the first character, which is always a '('.\n int currentOffset = 1;\n // Skip the argument types, one at a each loop iteration.\n while (methodDescriptor.charAt(currentOffset) != ')') {\n while (methodDescriptor.charAt(currentOffset) == '[') {\n currentOffset++;\n }\n if (methodDescriptor.charAt(currentOffset++) == 'L') {\n // Skip the argument descriptor content.\n int semiColumnOffset = methodDescriptor.indexOf(';', currentOffset);\n currentOffset = Math.max(currentOffset, semiColumnOffset + 1);\n }\n }\n return currentOffset + 1;\n }\n\n /**\n * Returns the {@link Type} corresponding to the given field or method descriptor.\n *\n * @param descriptorBuffer a buffer containing the field or method descriptor.\n * @param descriptorBegin the beginning index, inclusive, of the field or method descriptor in\n * descriptorBuffer.\n * @param descriptorEnd the end index, exclusive, of the field or method descriptor in\n * descriptorBuffer.\n * @return the {@link Type} corresponding to the given type descriptor.\n */\n private static Type getTypeInternal(final String descriptorBuffer, final int descriptorBegin, final int descriptorEnd) {\n switch (descriptorBuffer.charAt(descriptorBegin)) {\n case 'V':\n return VOID_TYPE;\n case 'Z':\n return BOOLEAN_TYPE;\n case 'C':\n return CHAR_TYPE;\n case 'B':\n return BYTE_TYPE;\n case 'S':\n return SHORT_TYPE;\n case 'I':\n return INT_TYPE;\n case 'F':\n return FLOAT_TYPE;\n case 'J':\n return LONG_TYPE;\n case 'D':\n return DOUBLE_TYPE;\n case '[':\n return new Type(ARRAY, descriptorBuffer, descriptorBegin, descriptorEnd);\n case 'L':\n return new Type(OBJECT, descriptorBuffer, descriptorBegin + 1, descriptorEnd - 1);\n case '(':\n return new Type(METHOD, descriptorBuffer, descriptorBegin, descriptorEnd);\n default:\n throw new IllegalArgumentException();\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Methods to get class names, internal names or descriptors.\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the binary name of the class corresponding to this type. This method must not be used\n * on method types.\n *\n * @return the binary name of the class corresponding to this type.\n */\n public String getClassName() {\n switch (sort) {\n case VOID:\n return \"void\";\n case BOOLEAN:\n return \"boolean\";\n case CHAR:\n return \"char\";\n case BYTE:\n return \"byte\";\n case SHORT:\n return \"short\";\n case INT:\n return \"int\";\n case FLOAT:\n return \"float\";\n case LONG:\n return \"long\";\n case DOUBLE:\n return \"double\";\n case ARRAY:\n StringBuilder stringBuilder = new StringBuilder(getElementType().getClassName());\n for (int i = getDimensions(); i > 0; --i) {\n stringBuilder.append(\"[]\");\n }\n return stringBuilder.toString();\n case OBJECT:\n case INTERNAL:\n return valueBuffer.substring(valueBegin, valueEnd).replace('/', '.');\n default:\n throw new AssertionError();\n }\n }\n\n /**\n * Returns the internal name of the class corresponding to this object or array type. The internal\n * name of a class is its fully qualified name (as returned by Class.getName(), where '.' are\n * replaced by '/'). This method should only be used for an object or array type.\n *\n * @return the internal name of the class corresponding to this object type.\n */\n public String getInternalName() {\n return valueBuffer.substring(valueBegin, valueEnd);\n }\n\n /**\n * Returns the internal name of the given class. The internal name of a class is its fully\n * qualified name, as returned by Class.getName(), where '.' are replaced by '/'.\n *\n * @param clazz an object or array class.\n * @return the internal name of the given class.\n */\n public static String getInternalName(final Class clazz) {\n return clazz.getName().replace('.', '/');\n }\n\n /**\n * Returns the descriptor corresponding to this type.\n *\n * @return the descriptor corresponding to this type.\n */\n public String getDescriptor() {\n if (sort == OBJECT) {\n return valueBuffer.substring(valueBegin - 1, valueEnd + 1);\n } else if (sort == INTERNAL) {\n return 'L' + valueBuffer.substring(valueBegin, valueEnd) + ';';\n } else {\n return valueBuffer.substring(valueBegin, valueEnd);\n }\n }\n\n /**\n * Returns the descriptor corresponding to the given class.\n *\n * @param clazz an object class, a primitive class or an array class.\n * @return the descriptor corresponding to the given class.\n */\n public static String getDescriptor(final Class clazz) {\n StringBuilder stringBuilder = new StringBuilder();\n appendDescriptor(clazz, stringBuilder);\n return stringBuilder.toString();\n }\n\n /**\n * Returns the descriptor corresponding to the given constructor.\n *\n * @param constructor a {@link Constructor} object.\n * @return the descriptor of the given constructor.\n */\n public static String getConstructorDescriptor(final Constructor constructor) {\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append('(');\n Class[] parameters = constructor.getParameterTypes();\n for (Class parameter : parameters) {\n appendDescriptor(parameter, stringBuilder);\n }\n return stringBuilder.append(\")V\").toString();\n }\n\n /**\n * Returns the descriptor corresponding to the given argument and return types.\n *\n * @param returnType the return type of the method.\n * @param argumentTypes the argument types of the method.\n * @return the descriptor corresponding to the given argument and return types.\n */\n public static String getMethodDescriptor(final Type returnType, final Type... argumentTypes) {\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append('(');\n for (Type argumentType : argumentTypes) {\n argumentType.appendDescriptor(stringBuilder);\n }\n stringBuilder.append(')');\n returnType.appendDescriptor(stringBuilder);\n return stringBuilder.toString();\n }\n\n /**\n * Returns the descriptor corresponding to the given method.\n *\n * @param method a {@link Method} object.\n * @return the descriptor of the given method.\n */\n public static String getMethodDescriptor(final Method method) {\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append('(');\n Class[] parameters = method.getParameterTypes();\n for (Class parameter : parameters) {\n appendDescriptor(parameter, stringBuilder);\n }\n stringBuilder.append(')');\n appendDescriptor(method.getReturnType(), stringBuilder);\n return stringBuilder.toString();\n }\n\n /**\n * Appends the descriptor corresponding to this type to the given string buffer.\n *\n * @param stringBuilder the string builder to which the descriptor must be appended.\n */\n private void appendDescriptor(final StringBuilder stringBuilder) {\n if (sort == OBJECT) {\n stringBuilder.append(valueBuffer, valueBegin - 1, valueEnd + 1);\n } else if (sort == INTERNAL) {\n stringBuilder.append('L').append(valueBuffer, valueBegin, valueEnd).append(';');\n } else {\n stringBuilder.append(valueBuffer, valueBegin, valueEnd);\n }\n }\n\n /**\n * Appends the descriptor of the given class to the given string builder.\n *\n * @param clazz the class whose descriptor must be computed.\n * @param stringBuilder the string builder to which the descriptor must be appended.\n */\n private static void appendDescriptor(final Class clazz, final StringBuilder stringBuilder) {\n Class currentClass = clazz;\n while (currentClass.isArray()) {\n stringBuilder.append('[');\n currentClass = currentClass.getComponentType();\n }\n if (currentClass.isPrimitive()) {\n char descriptor;\n if (currentClass == Integer.TYPE) {\n descriptor = 'I';\n } else if (currentClass == Void.TYPE) {\n descriptor = 'V';\n } else if (currentClass == Boolean.TYPE) {\n descriptor = 'Z';\n } else if (currentClass == Byte.TYPE) {\n descriptor = 'B';\n } else if (currentClass == Character.TYPE) {\n descriptor = 'C';\n } else if (currentClass == Short.TYPE) {\n descriptor = 'S';\n } else if (currentClass == Double.TYPE) {\n descriptor = 'D';\n } else if (currentClass == Float.TYPE) {\n descriptor = 'F';\n } else if (currentClass == Long.TYPE) {\n descriptor = 'J';\n } else {\n throw new AssertionError();\n }\n stringBuilder.append(descriptor);\n } else {\n stringBuilder.append('L').append(getInternalName(currentClass)).append(';');\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Methods to get the sort, dimension, size, and opcodes corresponding to a Type or descriptor.\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the sort of this type.\n *\n * @return {@link #VOID}, {@link #BOOLEAN}, {@link #CHAR}, {@link #BYTE}, {@link #SHORT}, {@link\n * #INT}, {@link #FLOAT}, {@link #LONG}, {@link #DOUBLE}, {@link #ARRAY}, {@link #OBJECT} or\n * {@link #METHOD}.\n */\n public int getSort() {\n return sort == INTERNAL ? OBJECT : sort;\n }\n\n /**\n * Returns the number of dimensions of this array type. This method should only be used for an\n * array type.\n *\n * @return the number of dimensions of this array type.\n */\n public int getDimensions() {\n int numDimensions = 1;\n while (valueBuffer.charAt(valueBegin + numDimensions) == '[') {\n numDimensions++;\n }\n return numDimensions;\n }\n\n /**\n * Returns the size of values of this type. This method must not be used for method types.\n *\n * @return the size of values of this type, i.e., 2 for {@code long} and {@code double}, 0 for\n * {@code void} and 1 otherwise.\n */\n public int getSize() {\n switch (sort) {\n case VOID:\n return 0;\n case BOOLEAN:\n case CHAR:\n case BYTE:\n case SHORT:\n case INT:\n case FLOAT:\n case ARRAY:\n case OBJECT:\n case INTERNAL:\n return 1;\n case LONG:\n case DOUBLE:\n return 2;\n default:\n throw new AssertionError();\n }\n }\n\n /**\n * Returns the size of the arguments and of the return value of methods of this type. This method\n * should only be used for method types.\n *\n * @return the size of the arguments of the method (plus one for the implicit this argument),\n * argumentsSize, and the size of its return value, returnSize, packed into a single int i =\n * {@code (argumentsSize << 2) | returnSize} (argumentsSize is therefore equal to {@code\n * i >> 2}, and returnSize to {@code i & 0x03}).\n */\n public int getArgumentsAndReturnSizes() {\n return getArgumentsAndReturnSizes(getDescriptor());\n }\n\n /**\n * Computes the size of the arguments and of the return value of a method.\n *\n * @param methodDescriptor a method descriptor.\n * @return the size of the arguments of the method (plus one for the implicit this argument),\n * argumentsSize, and the size of its return value, returnSize, packed into a single int i =\n * {@code (argumentsSize << 2) | returnSize} (argumentsSize is therefore equal to {@code\n * i >> 2}, and returnSize to {@code i & 0x03}).\n */\n public static int getArgumentsAndReturnSizes(final String methodDescriptor) {\n int argumentsSize = 1;\n // Skip the first character, which is always a '('.\n int currentOffset = 1;\n int currentChar = methodDescriptor.charAt(currentOffset);\n // Parse the argument types and compute their size, one at a each loop iteration.\n while (currentChar != ')') {\n if (currentChar == 'J' || currentChar == 'D') {\n currentOffset++;\n argumentsSize += 2;\n } else {\n while (methodDescriptor.charAt(currentOffset) == '[') {\n currentOffset++;\n }\n if (methodDescriptor.charAt(currentOffset++) == 'L') {\n // Skip the argument descriptor content.\n int semiColumnOffset = methodDescriptor.indexOf(';', currentOffset);\n currentOffset = Math.max(currentOffset, semiColumnOffset + 1);\n }\n argumentsSize += 1;\n }\n currentChar = methodDescriptor.charAt(currentOffset);\n }\n currentChar = methodDescriptor.charAt(currentOffset + 1);\n if (currentChar == 'V') {\n return argumentsSize << 2;\n } else {\n int returnSize = (currentChar == 'J' || currentChar == 'D') ? 2 : 1;\n return argumentsSize << 2 | returnSize;\n }\n }\n\n /**\n * Returns a JVM instruction opcode adapted to this {@link Type}. This method must not be used for\n * method types.\n *\n * @param opcode a JVM instruction opcode. This opcode must be one of ILOAD, ISTORE, IALOAD,\n * IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, ISHL, ISHR, IUSHR, IAND, IOR, IXOR and\n * IRETURN.\n * @return an opcode that is similar to the given opcode, but adapted to this {@link Type}. For\n * example, if this type is {@code float} and {@code opcode} is IRETURN, this method returns\n * FRETURN.\n */\n public int getOpcode(final int opcode) {\n if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) {\n switch (sort) {\n case BOOLEAN:\n case BYTE:\n return opcode + (Opcodes.BALOAD - Opcodes.IALOAD);\n case CHAR:\n return opcode + (Opcodes.CALOAD - Opcodes.IALOAD);\n case SHORT:\n return opcode + (Opcodes.SALOAD - Opcodes.IALOAD);\n case INT:\n return opcode;\n case FLOAT:\n return opcode + (Opcodes.FALOAD - Opcodes.IALOAD);\n case LONG:\n return opcode + (Opcodes.LALOAD - Opcodes.IALOAD);\n case DOUBLE:\n return opcode + (Opcodes.DALOAD - Opcodes.IALOAD);\n case ARRAY:\n case OBJECT:\n case INTERNAL:\n return opcode + (Opcodes.AALOAD - Opcodes.IALOAD);\n case METHOD:\n case VOID:\n throw new UnsupportedOperationException();\n default:\n throw new AssertionError();\n }\n } else {\n switch (sort) {\n case VOID:\n if (opcode != Opcodes.IRETURN) {\n throw new UnsupportedOperationException();\n }\n return Opcodes.RETURN;\n case BOOLEAN:\n case BYTE:\n case CHAR:\n case SHORT:\n case INT:\n return opcode;\n case FLOAT:\n return opcode + (Opcodes.FRETURN - Opcodes.IRETURN);\n case LONG:\n return opcode + (Opcodes.LRETURN - Opcodes.IRETURN);\n case DOUBLE:\n return opcode + (Opcodes.DRETURN - Opcodes.IRETURN);\n case ARRAY:\n case OBJECT:\n case INTERNAL:\n if (opcode != Opcodes.ILOAD && opcode != Opcodes.ISTORE && opcode != Opcodes.IRETURN) {\n throw new UnsupportedOperationException();\n }\n return opcode + (Opcodes.ARETURN - Opcodes.IRETURN);\n case METHOD:\n throw new UnsupportedOperationException();\n default:\n throw new AssertionError();\n }\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Equals, hashCode and toString.\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Tests if the given object is equal to this type.\n *\n * @param object the object to be compared to this type.\n * @return {@literal true} if the given object is equal to this type.\n */\n @Override\n public boolean equals(final Object object) {\n if (this == object) {\n return true;\n }\n if (!(object instanceof Type)) {\n return false;\n }\n Type other = (Type) object;\n if ((sort == INTERNAL ? OBJECT : sort) != (other.sort == INTERNAL ? OBJECT : other.sort)) {\n return false;\n }\n int begin = valueBegin;\n int end = valueEnd;\n int otherBegin = other.valueBegin;\n int otherEnd = other.valueEnd;\n // Compare the values.\n if (end - begin != otherEnd - otherBegin) {\n return false;\n }\n for (int i = begin, j = otherBegin; i < end; i++, j++) {\n if (valueBuffer.charAt(i) != other.valueBuffer.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns a hash code value for this type.\n *\n * @return a hash code value for this type.\n */\n @Override\n public int hashCode() {\n int hashCode = 13 * (sort == INTERNAL ? OBJECT : sort);\n if (sort >= ARRAY) {\n for (int i = valueBegin, end = valueEnd; i < end; i++) {\n hashCode = 17 * (hashCode + valueBuffer.charAt(i));\n }\n }\n return hashCode;\n }\n\n /**\n * Returns a string representation of this type.\n *\n * @return the descriptor of this type.\n */\n @Override\n public String toString() {\n return getDescriptor();\n }\n}\n", "file_name": "Type.java", "human_label": "Compute a hash code according to the type.", "level": "class_runnable", "lineno": "830", "name": "hashCode", "oracle_context": "{ \"apis\" : \"[charAt]\", \"classes\" : \"[]\", \"vars\" : \"[sort, INTERNAL, OBJECT, ARRAY, valueBegin, valueEnd, valueBuffer]\" }", "package": "net.hasor.utils.asm", "project": "hasor-master" }, { "_id": "6367676c1a6d9265ec01820b", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static String deleteAny(String inString,String charsToDelete){\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb=new StringBuilder();\n for (int i=0; i < inString.length(); i++) {\n char c=inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n}\n", "docstring": "/** \n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n", "end_lineno": "429", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *

      \n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
      \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
      \n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
      \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

      The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

      This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

      The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

      The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

      Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

      Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

      The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

      The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

      A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

      A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Delete characters that exists in the intersection between two character strings of the first character string and return the first character string that is modified.", "level": "class_runnable", "lineno": "410", "name": "deleteAny", "oracle_context": "{ \"apis\" : \"[hasLength, length, charAt, indexOf, append, toString]\", \"classes\" : \"[StringBuilder]\", \"vars\" : \"[]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636766861a6d9265ec01755a", "all_context": "{ \"class_level\" : \"import java.util.List;\\nimport java.util.Map;\\nimport java.util.Objects;\\nimport java.util.regex.MatchResult;\\nimport java.util.regex.Matcher;\\nimport java.util.regex.Pattern;\\nUriPattern EMPTY;\\nString regex;\\nPattern regexPattern;\\nint[] groupIndexes;\\nEmptyStringMatchResult EMPTY_STRING_MATCH_RESULT;\\nMatchResult r;\\nUriPattern();\\nUriPattern(String regex);\\nUriPattern(String regex,int[] groupIndexes);\\ncompile(String regex);\\nUriPattern(Pattern regexPattern);\\nUriPattern(Pattern regexPattern,int[] groupIndexes);\\ngetRegex();\\ngetGroupIndexes();\\nstart();\\nstart(int group);\\nend();\\nend(int group);\\ngroup();\\ngroup(int group);\\ngroupCount();\\nGroupIndexMatchResult(MatchResult r);\\nmatch(CharSequence uri,List groupValues);\\nmatch(CharSequence uri,List groupNames,Map groupValues);\\nhashCode();\\nequals(Object obj);\\ntoString();\\n\", \"repo_level\" : \"\" }", "class_name": "UriPattern", "code": "public final MatchResult match(CharSequence uri){\n if (uri == null || uri.length() == 0) return (regexPattern == null) ? EMPTY_STRING_MATCH_RESULT : null;\n else if (regexPattern == null) return null;\n Matcher m=regexPattern.matcher(uri);\n if (!m.matches()) return null;\n return (groupIndexes.length > 0) ? new GroupIndexMatchResult(m) : m;\n}\n", "docstring": "/** \n * Match a URI against the pattern.\n * @param uri the uri to match against the template.\n * @return the match result, otherwise null if no match occurs.\n */\n", "end_lineno": "277", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * Copyright (c) 2010-2018 Oracle and/or its affiliates. All rights reserved.\n *\n * The contents of this file are subject to the terms of either the GNU\n * General Public License Version 2 only (\"GPL\") or the Common Development\n * and Distribution License(\"CDDL\") (collectively, the \"License\"). You\n * may not use this file except in compliance with the License. You can\n * obtain a copy of the License at\n * http://glassfish.java.net/public/CDDL+GPL_1_1.html\n * or packager/legal/LICENSE.txt. See the License for the specific\n * language governing permissions and limitations under the License.\n *\n * When distributing the software, include this License Header Notice in each\n * file and include the License file at packager/legal/LICENSE.txt.\n *\n * GPL Classpath Exception:\n * Oracle designates this particular file as subject to the \"Classpath\"\n * exception as provided by Oracle in the GPL Version 2 section of the License\n * file that accompanied this code.\n *\n * Modifications:\n * If applicable, add the following below the License Header, with the fields\n * enclosed by brackets [] replaced by your own identifying information:\n * \"Portions Copyright [year] [name of copyright owner]\"\n *\n * Contributor(s):\n * If you wish your version of this file to be governed by only the CDDL or\n * only the GPL Version 2, indicate your decision by adding \"[Contributor]\n * elects to include this software in this distribution under the [CDDL or GPL\n * Version 2] license.\" If you don't indicate a single choice of license, a\n * recipient has the option to distribute your version of this file under\n * either the CDDL, the GPL Version 2 or to extend the choice of license to\n * its licensees as provided above. However, if you add GPL Version 2 code\n * and therefore, elected the GPL Version 2 license, then the option applies\n * only if the new code is made subject to such option by the copyright\n * holder.\n */\n\npackage org.atmosphere.util.uri;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.regex.MatchResult;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * A URI pattern for matching a URI against a regular expression\n * and returning capturing group values for any capturing groups present in\n * the expression.\n *\n * @author Paul.Sandoz@Sun.Com\n */\npublic class UriPattern {\n /**\n * The empty URI pattern that matches the null or empty URI path\n */\n public static final UriPattern EMPTY = new UriPattern();\n\n /**\n * The regular expression for matching URIs\n * and obtaining capturing group values.\n */\n private final String regex;\n\n /**\n * The compiled regular expression of {@link #regex}\n */\n private final Pattern regexPattern;\n\n private final int[] groupIndexes;\n\n /**\n * Construct an empty pattern.\n */\n protected UriPattern() {\n this.regex = \"\";\n this.regexPattern = null;\n this.groupIndexes = null;\n }\n\n /**\n * Construct a new URI pattern.\n *\n * @param regex the regular expression. If the expression is null or an\n * empty string then the pattern will only match a null or empty\n * URI path.\n * @throws java.util.regex.PatternSyntaxException if the\n * regular expression could not be compiled\n */\n public UriPattern(String regex) {\n this(regex, UriTemplateParser.EMPTY_INT_ARRAY);\n }\n\n /**\n * Construct a new URI pattern.\n *\n * @param regex the regular expression. If the expression is null or an\n * empty string then the pattern will only match a null or empty\n * URI path.\n * @param groupIndexes the array of group indexes to capturing groups.\n * @throws java.util.regex.PatternSyntaxException if the\n * regular expression could not be compiled\n */\n public UriPattern(String regex, int[] groupIndexes) {\n this(compile(regex), groupIndexes);\n }\n\n private static Pattern compile(String regex) {\n return (regex == null || regex.length() == 0) ? null : Pattern.compile(regex);\n }\n\n /**\n * Construct a new URI pattern.\n *\n * @param regexPattern the regular expression pattern\n * @throws IllegalArgumentException if the regexPattern is null.\n */\n public UriPattern(Pattern regexPattern) {\n this(regexPattern, UriTemplateParser.EMPTY_INT_ARRAY);\n }\n\n /**\n * Construct a new URI pattern.\n *\n * @param regexPattern the regular expression pattern\n * @param groupIndexes the array of group indexes to capturing groups.\n * @throws IllegalArgumentException if the regexPattern is null.\n */\n public UriPattern(Pattern regexPattern, int[] groupIndexes) {\n if (regexPattern == null)\n throw new IllegalArgumentException();\n\n this.regex = regexPattern.toString();\n this.regexPattern = regexPattern;\n this.groupIndexes = groupIndexes;\n }\n\n /**\n * Get the regular expression.\n *\n * @return the regular expression.\n */\n public final String getRegex() {\n return regex;\n }\n\n /**\n * Get the group indexes.\n *\n * @return the group indexes.\n */\n public final int[] getGroupIndexes() {\n return groupIndexes;\n }\n\n private static final class EmptyStringMatchResult implements MatchResult {\n public int start() {\n return 0;\n }\n\n public int start(int group) {\n if (group != 0)\n throw new IndexOutOfBoundsException();\n return start();\n }\n\n public int end() {\n return 0;\n }\n\n public int end(int group) {\n if (group != 0)\n throw new IndexOutOfBoundsException();\n return end();\n }\n\n public String group() {\n return \"\";\n }\n\n public String group(int group) {\n if (group != 0)\n throw new IndexOutOfBoundsException();\n return group();\n }\n\n public int groupCount() {\n return 0;\n }\n }\n\n private static final EmptyStringMatchResult EMPTY_STRING_MATCH_RESULT = new EmptyStringMatchResult();\n\n private final class GroupIndexMatchResult implements MatchResult {\n private final MatchResult r;\n\n GroupIndexMatchResult(MatchResult r) {\n this.r = r;\n }\n\n public int start() {\n return r.start();\n }\n\n public int start(int group) {\n if (group > groupCount())\n throw new IndexOutOfBoundsException();\n\n return (group > 0) ? r.start(groupIndexes[group - 1]) : r.start();\n }\n\n public int end() {\n return r.end();\n }\n\n public int end(int group) {\n if (group > groupCount())\n throw new IndexOutOfBoundsException();\n\n return (group > 0) ? r.end(groupIndexes[group - 1]) : r.end();\n }\n\n public String group() {\n return r.group();\n }\n\n public String group(int group) {\n if (group > groupCount())\n throw new IndexOutOfBoundsException();\n\n return (group > 0) ? r.group(groupIndexes[group - 1]) : r.group();\n }\n\n public int groupCount() {\n return (groupIndexes != null ? groupIndexes.length : 0) - 1;\n }\n }\n\n /**\n * Match a URI against the pattern.\n *\n * @param uri the uri to match against the template.\n * @return the match result, otherwise null if no match occurs.\n */\n public final MatchResult match(CharSequence uri) {\n // Check for match against the empty pattern\n if (uri == null || uri.length() == 0)\n return (regexPattern == null) ? EMPTY_STRING_MATCH_RESULT : null;\n else if (regexPattern == null)\n return null;\n\n // Match the URI to the URI template regular expression\n Matcher m = regexPattern.matcher(uri);\n if (!m.matches())\n return null;\n\n return (groupIndexes.length > 0) ? new GroupIndexMatchResult(m) : m;\n }\n\n /**\n * Match a URI against the pattern.\n *

      \n * If the URI matches against the pattern then the capturing group values\n * (if any) will be added to a list passed in as parameter.\n *\n * @param uri the uri to match against the template.\n * @param groupValues the list to add the values of a pattern's\n * capturing groups if matching is successful. The values are added\n * in the same order as the pattern's capturing groups. The list\n * is cleared before values are added.\n * @return true if the URI matches the pattern, otherwise false.\n * @throws IllegalArgumentException if the uri or\n * capturingGroupValues is null.\n */\n public final boolean match(CharSequence uri, List groupValues) {\n if (groupValues == null)\n throw new IllegalArgumentException();\n\n // Check for match against the empty pattern\n if (uri == null || uri.length() == 0)\n return regexPattern == null;\n else if (regexPattern == null)\n return false;\n\n // Match the URI to the URI template regular expression\n Matcher m = regexPattern.matcher(uri);\n if (!m.matches())\n return false;\n\n groupValues.clear();\n if (groupIndexes.length > 0) {\n for (int i = 0; i < groupIndexes.length - 1; i++) {\n groupValues.add(m.group(groupIndexes[i]));\n }\n } else {\n for (int i = 1; i <= m.groupCount(); i++) {\n groupValues.add(m.group(i));\n }\n }\n\n // TODO check for consistency of different capturing groups\n // that must have the same value\n\n return true;\n }\n\n /**\n * Match a URI against the pattern.\n *

      \n * If the URI matches against the pattern then the capturing group values\n * (if any) will be added to a map passed in as parameter.\n *\n * @param uri the uri to match against the template.\n * @param groupNames the list names associated with a pattern's\n * capturing groups. The names MUST be in the same order as the\n * pattern's capturing groups and the size MUST be equal to or\n * less than the number of capturing groups.\n * @param groupValues the map to add the values of a pattern's\n * capturing groups if matching is successful. A values is put\n * into the map using the group name associated with the\n * capturing group. The map is cleared before values are added.\n * @return true if the URI matches the pattern, otherwise false.\n * @throws IllegalArgumentException if the uri or\n * capturingGroupValues is null.\n */\n public final boolean match(CharSequence uri,\n List groupNames, Map groupValues) {\n if (groupValues == null)\n throw new IllegalArgumentException();\n\n // Check for match against the empty pattern\n if (uri == null || uri.length() == 0)\n return regexPattern == null;\n else if (regexPattern == null)\n return false;\n\n // Match the URI to the URI template regular expression\n Matcher m = regexPattern.matcher(uri);\n if (!m.matches())\n return false;\n\n // Assign the matched group values to group names\n groupValues.clear();\n for (int i = 0; i < groupNames.size(); i++) {\n String name = groupNames.get(i);\n String currentValue = m.group((groupIndexes.length > 0) ? groupIndexes[i] : i + 1);\n\n // Group names can have the same name occuring more than once, \n // check that groups values are same.\n String previousValue = groupValues.get(name);\n if (previousValue != null && !previousValue.equals(currentValue))\n return false;\n\n groupValues.put(name, currentValue);\n }\n\n return true;\n }\n\n @Override\n public final int hashCode() {\n return regex.hashCode();\n }\n\n @Override\n public final boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final UriPattern that = (UriPattern) obj;\n if (!Objects.equals(this.regex, that.regex)) {\n return false;\n }\n return true;\n }\n\n @Override\n public final String toString() {\n return regex;\n }\n}\n", "file_name": "UriPattern.java", "human_label": "If the match between the url and the pattern occurs, return the match result. Otherwise, return null.", "level": "project_runnable", "lineno": "258", "name": "match", "oracle_context": "{ \"apis\" : \"[length, matcher, matches, GroupIndexMatchResult]\", \"classes\" : \"[Matcher, groupIndexes]\", \"vars\" : \"[length, regexPattern, EMPTY_STRING_MATCH_RESULT, groupIndexes]\" }", "package": "org.atmosphere.util.uri", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636766f91a6d9265ec01777d", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.io.InputStream;\\nimport java.lang.reflect.Constructor;\\nimport java.lang.reflect.InvocationTargetException;\\nimport java.lang.reflect.Method;\\nimport java.lang.reflect.Modifier;\\nimport java.net.URL;\\nimport java.util.Arrays;\\nimport java.util.Collections;\\nimport java.util.HashMap;\\nimport java.util.List;\\nimport java.util.logging.Logger;\\nLogger logger;\\nint CR;\\nint LF;\\nHashMap> name2Class;\\nHashMap,String> class2Name;\\nHashMap,Method> class2Value;\\nfromName(String name);\\ntoName(Class type);\\nvalueOf(Class type,String value);\\nvalueOf(String type,String value);\\nparseInt(String s,int offset,int length,int base);\\nparseInt(byte[] b,int offset,int length,int base);\\nparseBytes(String s,int base);\\ntoString(byte[] bytes,int base);\\nconvertHexDigit(byte b);\\ntoHex(byte b,Appendable buf);\\ntoHexString(byte b);\\ntoHexString(byte[] b);\\ntoHexString(byte[] b,int offset,int length);\\nfromHexString(String s);\\ndump(Class c);\\ndump(ClassLoader cl);\\nreadLine(InputStream in);\\njarFor(String className);\\ncall(Class oClass,String method,Object obj,Object[] arg);\\nasList(T[] a);\\n\", \"repo_level\" : \"\" }", "class_name": "TypeUtil", "code": "public static byte convertHexDigit(byte b){\n if ((b >= '0') && (b <= '9')) return (byte)(b - '0');\n if ((b >= 'a') && (b <= 'f')) return (byte)(b - 'a' + 10);\n if ((b >= 'A') && (b <= 'F')) return (byte)(b - 'A' + 10);\n throw new IllegalArgumentException(\"!hex:\" + Integer.toHexString(0xff & b));\n}\n", "docstring": "/** \n * @param b An ASCII encoded character 0-9 a-f A-F\n * @return The byte value of the character 0-16.\n */\n", "end_lineno": "300", "file_content": "// ========================================================================\n// Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd.\n// ------------------------------------------------------------------------\n// All rights reserved. This program and the accompanying materials\n// are made available under the terms of the Eclipse Public License v1.0\n// and Apache License v2.0 which accompanies this distribution.\n// The Eclipse Public License is available at\n// http://www.eclipse.org/legal/epl-v10.html\n// The Apache License v2.0 is available at\n// http://www.opensource.org/licenses/apache2.0.php\n// You may elect to redistribute this code under either of these licenses.\n// ========================================================================\npackage net.hasor.utils.json;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.net.URL;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.logging.Logger;\n/* ------------------------------------------------------------ */\n\n/**\n * TYPE Utilities.\n * Provides various static utiltiy methods for manipulating types and their\n * string representations.\n *\n * @since Jetty 4.1\n */\nclass TypeUtil {\n protected final static Logger logger = Logger.getLogger(TypeUtil.class.getName());\n public static int CR = '\\015';\n public static int LF = '\\012';\n /* ------------------------------------------------------------ */\n private static final HashMap> name2Class = new HashMap>();\n\n static {\n name2Class.put(\"boolean\", Boolean.TYPE);\n name2Class.put(\"byte\", Byte.TYPE);\n name2Class.put(\"char\", Character.TYPE);\n name2Class.put(\"double\", Double.TYPE);\n name2Class.put(\"float\", Float.TYPE);\n name2Class.put(\"int\", Integer.TYPE);\n name2Class.put(\"long\", Long.TYPE);\n name2Class.put(\"short\", Short.TYPE);\n name2Class.put(\"void\", Void.TYPE);\n name2Class.put(\"java.lang.Boolean.TYPE\", Boolean.TYPE);\n name2Class.put(\"java.lang.Byte.TYPE\", Byte.TYPE);\n name2Class.put(\"java.lang.Character.TYPE\", Character.TYPE);\n name2Class.put(\"java.lang.Double.TYPE\", Double.TYPE);\n name2Class.put(\"java.lang.Float.TYPE\", Float.TYPE);\n name2Class.put(\"java.lang.Integer.TYPE\", Integer.TYPE);\n name2Class.put(\"java.lang.Long.TYPE\", Long.TYPE);\n name2Class.put(\"java.lang.Short.TYPE\", Short.TYPE);\n name2Class.put(\"java.lang.Void.TYPE\", Void.TYPE);\n name2Class.put(\"java.lang.Boolean\", Boolean.class);\n name2Class.put(\"java.lang.Byte\", Byte.class);\n name2Class.put(\"java.lang.Character\", Character.class);\n name2Class.put(\"java.lang.Double\", Double.class);\n name2Class.put(\"java.lang.Float\", Float.class);\n name2Class.put(\"java.lang.Integer\", Integer.class);\n name2Class.put(\"java.lang.Long\", Long.class);\n name2Class.put(\"java.lang.Short\", Short.class);\n name2Class.put(\"Boolean\", Boolean.class);\n name2Class.put(\"Byte\", Byte.class);\n name2Class.put(\"Character\", Character.class);\n name2Class.put(\"Double\", Double.class);\n name2Class.put(\"Float\", Float.class);\n name2Class.put(\"Integer\", Integer.class);\n name2Class.put(\"Long\", Long.class);\n name2Class.put(\"Short\", Short.class);\n name2Class.put(null, Void.TYPE);\n name2Class.put(\"string\", String.class);\n name2Class.put(\"String\", String.class);\n name2Class.put(\"java.lang.String\", String.class);\n }\n\n /* ------------------------------------------------------------ */\n private static final HashMap, String> class2Name = new HashMap, String>();\n\n static {\n class2Name.put(Boolean.TYPE, \"boolean\");\n class2Name.put(Byte.TYPE, \"byte\");\n class2Name.put(Character.TYPE, \"char\");\n class2Name.put(Double.TYPE, \"double\");\n class2Name.put(Float.TYPE, \"float\");\n class2Name.put(Integer.TYPE, \"int\");\n class2Name.put(Long.TYPE, \"long\");\n class2Name.put(Short.TYPE, \"short\");\n class2Name.put(Void.TYPE, \"void\");\n class2Name.put(Boolean.class, \"java.lang.Boolean\");\n class2Name.put(Byte.class, \"java.lang.Byte\");\n class2Name.put(Character.class, \"java.lang.Character\");\n class2Name.put(Double.class, \"java.lang.Double\");\n class2Name.put(Float.class, \"java.lang.Float\");\n class2Name.put(Integer.class, \"java.lang.Integer\");\n class2Name.put(Long.class, \"java.lang.Long\");\n class2Name.put(Short.class, \"java.lang.Short\");\n class2Name.put(null, \"void\");\n class2Name.put(String.class, \"java.lang.String\");\n }\n\n /* ------------------------------------------------------------ */\n private static final HashMap, Method> class2Value = new HashMap, Method>();\n\n static {\n try {\n Class[] s = { String.class };\n class2Value.put(Boolean.TYPE, Boolean.class.getMethod(\"valueOf\", s));\n class2Value.put(Byte.TYPE, Byte.class.getMethod(\"valueOf\", s));\n class2Value.put(Double.TYPE, Double.class.getMethod(\"valueOf\", s));\n class2Value.put(Float.TYPE, Float.class.getMethod(\"valueOf\", s));\n class2Value.put(Integer.TYPE, Integer.class.getMethod(\"valueOf\", s));\n class2Value.put(Long.TYPE, Long.class.getMethod(\"valueOf\", s));\n class2Value.put(Short.TYPE, Short.class.getMethod(\"valueOf\", s));\n class2Value.put(Boolean.class, Boolean.class.getMethod(\"valueOf\", s));\n class2Value.put(Byte.class, Byte.class.getMethod(\"valueOf\", s));\n class2Value.put(Double.class, Double.class.getMethod(\"valueOf\", s));\n class2Value.put(Float.class, Float.class.getMethod(\"valueOf\", s));\n class2Value.put(Integer.class, Integer.class.getMethod(\"valueOf\", s));\n class2Value.put(Long.class, Long.class.getMethod(\"valueOf\", s));\n class2Value.put(Short.class, Short.class.getMethod(\"valueOf\", s));\n } catch (Exception e) {\n throw new Error(e);\n }\n }\n /* ------------------------------------------------------------ */\n\n /** Array to List.\n *

      \n * Works like {@link Arrays#asList(Object...)}, but handles null arrays.\n * @return a list backed by the array.\n */\n public static List asList(T[] a) {\n if (a == null)\n return Collections.emptyList();\n return Arrays.asList(a);\n }\n /* ------------------------------------------------------------ */\n\n /** Class from a canonical name for a type.\n * @param name A class or type name.\n * @return A class , which may be a primitive TYPE field..\n */\n public static Class fromName(String name) {\n return name2Class.get(name);\n }\n /* ------------------------------------------------------------ */\n\n /** Canonical name for a type.\n * @param type A class , which may be a primitive TYPE field.\n * @return Canonical name.\n */\n public static String toName(Class type) {\n return class2Name.get(type);\n }\n /* ------------------------------------------------------------ */\n\n /** Convert String value to instance.\n * @param type The class of the instance, which may be a primitive TYPE field.\n * @param value The value as a string.\n * @return The value as an Object.\n */\n public static Object valueOf(Class type, String value) {\n try {\n if (type.equals(String.class))\n return value;\n Method m = class2Value.get(type);\n if (m != null)\n return m.invoke(null, value);\n if (type.equals(Character.TYPE) || type.equals(Character.class))\n return new Character(value.charAt(0));\n Constructor c = type.getConstructor(String.class);\n return c.newInstance(value);\n } catch (NoSuchMethodException e) {\n // LogSupport.ignore(log,e);\n } catch (IllegalAccessException e) {\n // LogSupport.ignore(log,e);\n } catch (InstantiationException e) {\n // LogSupport.ignore(log,e);\n } catch (InvocationTargetException e) {\n if (e.getTargetException() instanceof Error)\n throw (Error) (e.getTargetException());\n // LogSupport.ignore(log,e);\n }\n return null;\n }\n /* ------------------------------------------------------------ */\n\n /** Convert String value to instance.\n * @param type classname or type (eg int)\n * @param value The value as a string.\n * @return The value as an Object.\n */\n public static Object valueOf(String type, String value) {\n return valueOf(fromName(type), value);\n }\n /* ------------------------------------------------------------ */\n\n /** Parse an int from a substring.\n * Negative numbers are not handled.\n * @param s String\n * @param offset Offset within string\n * @param length Length of integer or -1 for remainder of string\n * @param base base of the integer\n * @return the parsed integer\n * @throws NumberFormatException if the string cannot be parsed\n */\n public static int parseInt(String s, int offset, int length, int base) throws NumberFormatException {\n int value = 0;\n if (length < 0)\n length = s.length() - offset;\n for (int i = 0; i < length; i++) {\n char c = s.charAt(offset + i);\n int digit = c - '0';\n if (digit < 0 || digit >= base || digit >= 10) {\n digit = 10 + c - 'A';\n if (digit < 10 || digit >= base)\n digit = 10 + c - 'a';\n }\n if (digit < 0 || digit >= base)\n throw new NumberFormatException(s.substring(offset, offset + length));\n value = value * base + digit;\n }\n return value;\n }\n /* ------------------------------------------------------------ */\n\n /** Parse an int from a byte array of ascii characters.\n * Negative numbers are not handled.\n * @param b byte array\n * @param offset Offset within string\n * @param length Length of integer or -1 for remainder of string\n * @param base base of the integer\n * @return the parsed integer\n * @throws NumberFormatException if the array cannot be parsed into an integer\n */\n public static int parseInt(byte[] b, int offset, int length, int base) throws NumberFormatException {\n int value = 0;\n if (length < 0)\n length = b.length - offset;\n for (int i = 0; i < length; i++) {\n char c = (char) (0xff & b[offset + i]);\n int digit = c - '0';\n if (digit < 0 || digit >= base || digit >= 10) {\n digit = 10 + c - 'A';\n if (digit < 10 || digit >= base)\n digit = 10 + c - 'a';\n }\n if (digit < 0 || digit >= base)\n throw new NumberFormatException(new String(b, offset, length));\n value = value * base + digit;\n }\n return value;\n }\n\n /* ------------------------------------------------------------ */\n public static byte[] parseBytes(String s, int base) {\n byte[] bytes = new byte[s.length() / 2];\n for (int i = 0; i < s.length(); i += 2)\n bytes[i / 2] = (byte) TypeUtil.parseInt(s, i, 2, base);\n return bytes;\n }\n\n /* ------------------------------------------------------------ */\n public static String toString(byte[] bytes, int base) {\n StringBuilder buf = new StringBuilder();\n for (byte b : bytes) {\n int bi = 0xff & b;\n int c = '0' + (bi / base) % base;\n if (c > '9')\n c = 'a' + (c - '0' - 10);\n buf.append((char) c);\n c = '0' + bi % base;\n if (c > '9')\n c = 'a' + (c - '0' - 10);\n buf.append((char) c);\n }\n return buf.toString();\n }\n /* ------------------------------------------------------------ */\n\n /**\n * @param b An ASCII encoded character 0-9 a-f A-F\n * @return The byte value of the character 0-16.\n */\n public static byte convertHexDigit(byte b) {\n if ((b >= '0') && (b <= '9'))\n return (byte) (b - '0');\n if ((b >= 'a') && (b <= 'f'))\n return (byte) (b - 'a' + 10);\n if ((b >= 'A') && (b <= 'F'))\n return (byte) (b - 'A' + 10);\n throw new IllegalArgumentException(\"!hex:\" + Integer.toHexString(0xff & b));\n }\n\n /* ------------------------------------------------------------ */\n public static void toHex(byte b, Appendable buf) {\n try {\n int bi = 0xff & b;\n int c = '0' + (bi / 16) % 16;\n if (c > '9')\n c = 'A' + (c - '0' - 10);\n buf.append((char) c);\n c = '0' + bi % 16;\n if (c > '9')\n c = 'A' + (c - '0' - 10);\n buf.append((char) c);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /* ------------------------------------------------------------ */\n public static String toHexString(byte b) {\n return toHexString(new byte[] { b }, 0, 1);\n }\n\n /* ------------------------------------------------------------ */\n public static String toHexString(byte[] b) {\n return toHexString(b, 0, b.length);\n }\n\n /* ------------------------------------------------------------ */\n public static String toHexString(byte[] b, int offset, int length) {\n StringBuilder buf = new StringBuilder();\n for (int i = offset; i < offset + length; i++) {\n int bi = 0xff & b[i];\n int c = '0' + (bi / 16) % 16;\n if (c > '9')\n c = 'A' + (c - '0' - 10);\n buf.append((char) c);\n c = '0' + bi % 16;\n if (c > '9')\n c = 'a' + (c - '0' - 10);\n buf.append((char) c);\n }\n return buf.toString();\n }\n\n /* ------------------------------------------------------------ */\n public static byte[] fromHexString(String s) {\n if (s.length() % 2 != 0)\n throw new IllegalArgumentException(s);\n byte[] array = new byte[s.length() / 2];\n for (int i = 0; i < array.length; i++) {\n int b = Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16);\n array[i] = (byte) (0xff & b);\n }\n return array;\n }\n\n public static void dump(Class c) {\n System.err.println(\"Dump: \" + c);\n dump(c.getClassLoader());\n }\n\n public static void dump(ClassLoader cl) {\n System.err.println(\"Dump Loaders:\");\n while (cl != null) {\n System.err.println(\" loader \" + cl);\n cl = cl.getParent();\n }\n }\n\n /* ------------------------------------------------------------ */\n public static byte[] readLine(InputStream in) throws IOException {\n byte[] buf = new byte[256];\n int i = 0;\n int loops = 0;\n int ch = 0;\n while (true) {\n ch = in.read();\n if (ch < 0)\n break;\n loops++;\n // skip a leading LF's\n if (loops == 1 && ch == LF)\n continue;\n if (ch == CR || ch == LF)\n break;\n if (i >= buf.length) {\n byte[] old_buf = buf;\n buf = new byte[old_buf.length + 256];\n System.arraycopy(old_buf, 0, buf, 0, old_buf.length);\n }\n buf[i++] = (byte) ch;\n }\n if (ch == -1 && i == 0)\n return null;\n // skip a trailing LF if it exists\n if (ch == CR && in.available() >= 1 && in.markSupported()) {\n in.mark(1);\n ch = in.read();\n if (ch != LF)\n in.reset();\n }\n byte[] old_buf = buf;\n buf = new byte[i];\n System.arraycopy(old_buf, 0, buf, 0, i);\n return buf;\n }\n\n public static URL jarFor(String className) {\n try {\n className = className.replace('.', '/') + \".class\";\n // hack to discover jstl libraries\n URL url = Loader.getResource(null, className, false);\n String s = url.toString();\n if (s.startsWith(\"jar:file:\"))\n return new URL(s.substring(4, s.indexOf(\"!/\")));\n } catch (Exception e) {\n logger.fine(e.getMessage());\n }\n return null;\n }\n\n public static Object call(Class oClass, String method, Object obj, Object[] arg) throws InvocationTargetException, NoSuchMethodException {\n // Lets just try all methods for now\n Method[] methods = oClass.getMethods();\n for (int c = 0; methods != null && c < methods.length; c++) {\n if (!methods[c].getName().equals(method))\n continue;\n if (methods[c].getParameterTypes().length != arg.length)\n continue;\n if (Modifier.isStatic(methods[c].getModifiers()) != (obj == null))\n continue;\n if ((obj == null) && methods[c].getDeclaringClass() != oClass)\n continue;\n try {\n return methods[c].invoke(obj, arg);\n } catch (IllegalAccessException e) {\n logger.fine(e.getMessage());\n } catch (IllegalArgumentException e) {\n logger.fine(e.getMessage());\n }\n }\n throw new NoSuchMethodException(method);\n }\n}\n", "file_name": "TypeUtil.java", "human_label": "Convert an ASCII encoded character to hex.", "level": "slib_runnable", "lineno": "288", "name": "convertHexDigit", "oracle_context": "{ \"apis\" : \"[toHexString]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils.json", "project": "hasor-master" }, { "_id": "636766801a6d9265ec017477", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.io.InputStream;\\nimport java.util.Deque;\\nimport java.util.LinkedList;\\nDeque stack;\\nint rootCount;\\nInputStream current;\\nInputStreamIterator(InputStream filesOrDirectories);\\naddReverse(InputStream[] files);\\nnext();\\n\", \"repo_level\" : \"\" }", "class_name": "InputStreamIterator", "code": "private void addReverse(final InputStream[] files){\n for (int i=files.length - 1; i >= 0; --i) {\n stack.add(files[i]);\n }\n}\n", "docstring": "/** \n * Add the specified files in reverse order.\n */\n", "end_lineno": "83", "file_content": "package org.atmosphere.util.annotation;/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Deque;\nimport java.util.LinkedList;\n\n/**\n * {@code FileIterator} enables iteration over all files in a directory and all\n * its sub directories.\n *
      \n * Usage:\n *

      \n * FileIterator iter = new FileIterator(new File(\"./src\"));\n * File f;\n * while ((f = iter.next()) != null) {\n *     // do something with f\n *     assert f == iter.getCurrent();\n * }\n * 
      \n *\n * @author Ronald K. Muller\n * @since annotation-detector 3.0.0\n */\npublic final class InputStreamIterator {\n\n private final Deque stack;\n private final int rootCount;\n private InputStream current;\n\n /**\n * Create a new {@code FileIterator} using the specified 'filesOrDirectories' as root.\n *
      \n * If 'filesOrDirectories' contains a file, the iterator just returns that single file.\n * If 'filesOrDirectories' contains a directory, all files in that directory\n * and its sub directories are returned (depth first).\n *\n * @param filesOrDirectories Zero or more {@link java.io.File} objects, which are iterated\n * in the specified order (depth first)\n */\n public InputStreamIterator(final InputStream... filesOrDirectories) {\n addReverse(filesOrDirectories);\n stack = new LinkedList<>();\n rootCount = 0;\n }\n\n /**\n * Return the next {@link java.io.File} object or {@code null} if no more files are\n * available.\n *\n */\n public InputStream next() throws IOException {\n if (stack.isEmpty()) {\n current = null;\n return null;\n } else {\n current = stack.removeLast();\n return current;\n }\n }\n\n /**\n * Add the specified files in reverse order.\n */\n private void addReverse(final InputStream[] files) {\n for (int i = files.length - 1; i >=0; --i) {\n stack.add(files[i]);\n }\n }\n\n}\n\n", "file_name": "InputStreamIterator.java", "human_label": "Add files in the stack in reverse order.", "level": "class_runnable", "lineno": "76", "name": "addReverse", "oracle_context": "{ \"apis\" : \"[add]\", \"classes\" : \"[]\", \"vars\" : \"[length, stack]\" }", "package": "org.atmosphere.util.annotation", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767de1a6d9265ec01871e", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Field;\\nimport java.util.ArrayList;\\nimport java.util.Collections;\\nimport java.util.HashMap;\\nimport java.util.List;\\nimport java.util.Map;\\nimport java.util.Objects;\\nimport java.util.Optional;\\nimport lombok.extern.slf4j.Slf4j;\\nimport org.apache.skywalking.oap.server.core.source.DefaultScopeDefine;\\nimport org.apache.skywalking.oap.server.core.storage.StorageException;\\nimport org.apache.skywalking.oap.server.core.storage.annotation.BanyanDB;\\nimport org.apache.skywalking.oap.server.core.storage.annotation.Column;\\nimport org.apache.skywalking.oap.server.core.storage.annotation.ElasticSearch;\\nimport org.apache.skywalking.oap.server.core.storage.annotation.SQLDatabase;\\nimport org.apache.skywalking.oap.server.core.storage.annotation.Storage;\\nimport org.apache.skywalking.oap.server.core.storage.annotation.SuperDataset;\\nimport org.apache.skywalking.oap.server.core.storage.annotation.ValueColumnMetadata;\\nimport org.apache.skywalking.oap.server.library.util.StringUtil;\\nList models;\\nHashMap columnNameOverrideRule;\\nList listeners;\\nArrayList keys;\\nStorageModels();\\nadd(Class aClass,int scopeId,Storage storage,boolean record);\\nisSuperDatasetModel(Class aClass);\\nretrieval(Class clazz,String modelName,List modelColumns,int scopeId,ShardingKeyChecker checker,SQLDatabaseModelExtension sqlDBModelExtension,boolean record);\\noverrideColumnName(String columnName,String newName);\\nfollowColumnNameRules(Model model);\\naddExtraColumn4AdditionalEntity(SQLDatabaseModelExtension sqlDBModelExtension,List modelColumns,String extraColumn,List additionalTables);\\nallModels();\\naccept(String modelName,ModelColumn modelColumn);\\ncheck(String modelName);\\naddModelListener(CreatingListener listener);\\n\", \"repo_level\" : \"public interface DefaultScopeDefine {static void activeExtraModelColumns();\\npublic Class annotation();\\npublic void notify(Class originalClass);\\nstatic String nameOf(int id);\\nstatic int valueOf(String name);\\nstatic void reset();\\nstatic boolean inServiceCatalog(int scopeId);\\nstatic boolean inServiceInstanceCatalog(int scopeId);\\nstatic boolean inEndpointCatalog(int scopeId);\\nstatic boolean inServiceRelationCatalog(int scopeId);\\nstatic boolean inServiceInstanceRelationCatalog(int scopeId);\\nstatic boolean inEndpointRelationCatalog(int scopeId);\\nstatic boolean inProcessCatalog(int scopeId);\\nstatic boolean inProcessRelationCatalog(int scopeId);\\nstatic String catalogOf(int scope);\\nstatic List getDefaultColumns(String scopeName);\\n }\\npublic interface StorageException { }\\npublic interface Storage { }\\npublic interface StringUtil {static boolean isEmpty(String str);\\nstatic boolean isNotEmpty(String str);\\nstatic boolean isBlank(String str);\\nstatic boolean isNotBlank(String str);\\nstatic void setIfPresent(String value,Consumer setter);\\nstatic String join(char delimiter,String strings);\\nstatic boolean substringMatch(CharSequence str,int index,CharSequence substring);\\nstatic String cut(String str,int threshold);\\nstatic String trim(String str,char ch);\\n }\\n\" }", "class_name": "StorageModels$ShardingKeyChecker", "code": "private void check(String modelName) throws IllegalStateException {\n for (int i=0; i < keys.size(); i++) {\n final ModelColumn modelColumn=keys.get(i);\n if (modelColumn == null) {\n throw new IllegalStateException(\"Sharding key index=\" + i + \" is missing in \"+ modelName);\n }\n }\n}\n", "docstring": "/** \n * @param modelName model name of the entity\n * @throws IllegalStateException if sharding key indices are not continuous\n */\n", "end_lineno": "342", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.skywalking.oap.server.core.storage.model;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.skywalking.oap.server.core.source.DefaultScopeDefine;\nimport org.apache.skywalking.oap.server.core.storage.StorageException;\nimport org.apache.skywalking.oap.server.core.storage.annotation.BanyanDB;\nimport org.apache.skywalking.oap.server.core.storage.annotation.Column;\nimport org.apache.skywalking.oap.server.core.storage.annotation.ElasticSearch;\nimport org.apache.skywalking.oap.server.core.storage.annotation.SQLDatabase;\nimport org.apache.skywalking.oap.server.core.storage.annotation.Storage;\nimport org.apache.skywalking.oap.server.core.storage.annotation.SuperDataset;\nimport org.apache.skywalking.oap.server.core.storage.annotation.ValueColumnMetadata;\nimport org.apache.skywalking.oap.server.library.util.StringUtil;\n\n/**\n * StorageModels manages all models detected by the core.\n */\n@Slf4j\npublic class StorageModels implements IModelManager, ModelCreator, ModelManipulator {\n private final List models;\n private final HashMap columnNameOverrideRule;\n private final List listeners;\n\n public StorageModels() {\n this.models = new ArrayList<>();\n this.columnNameOverrideRule = new HashMap<>();\n this.listeners = new ArrayList<>();\n }\n\n @Override\n public Model add(Class aClass, int scopeId, Storage storage, boolean record) throws StorageException {\n // Check this scope id is valid.\n DefaultScopeDefine.nameOf(scopeId);\n\n List modelColumns = new ArrayList<>();\n ShardingKeyChecker checker = new ShardingKeyChecker();\n SQLDatabaseModelExtension sqlDBModelExtension = new SQLDatabaseModelExtension();\n retrieval(aClass, storage.getModelName(), modelColumns, scopeId, checker, sqlDBModelExtension, record);\n // Add extra column for additional entities\n if (aClass.isAnnotationPresent(SQLDatabase.ExtraColumn4AdditionalEntity.class)\n || aClass.isAnnotationPresent(SQLDatabase.MultipleExtraColumn4AdditionalEntity.class)) {\n Map/*tables*/> extraColumns = new HashMap<>();\n if (aClass.isAnnotationPresent(SQLDatabase.MultipleExtraColumn4AdditionalEntity.class)) {\n for (SQLDatabase.ExtraColumn4AdditionalEntity extraColumn : aClass.getAnnotation(\n SQLDatabase.MultipleExtraColumn4AdditionalEntity.class).value()) {\n List tables = extraColumns.computeIfAbsent(\n extraColumn.parentColumn(), v -> new ArrayList<>());\n tables.add(extraColumn.additionalTable());\n }\n } else {\n SQLDatabase.ExtraColumn4AdditionalEntity extraColumn = aClass.getAnnotation(\n SQLDatabase.ExtraColumn4AdditionalEntity.class);\n List tables = extraColumns.computeIfAbsent(extraColumn.parentColumn(), v -> new ArrayList<>());\n tables.add(extraColumn.additionalTable());\n }\n\n extraColumns.forEach((extraColumn, tables) -> {\n if (!addExtraColumn4AdditionalEntity(sqlDBModelExtension, modelColumns, extraColumn, tables)) {\n throw new IllegalStateException(\n \"Model [\" + storage.getModelName() + \"] defined an extra column [\" + extraColumn + \"] by @SQLDatabase.ExtraColumn4AdditionalEntity, \" +\n \"but couldn't be found from the parent.\");\n }\n });\n }\n checker.check(storage.getModelName());\n\n Model model = new Model(\n storage.getModelName(),\n modelColumns,\n scopeId,\n storage.getDownsampling(),\n record,\n isSuperDatasetModel(aClass),\n aClass,\n storage.isTimeRelativeID(),\n sqlDBModelExtension\n );\n\n this.followColumnNameRules(model);\n models.add(model);\n\n for (final CreatingListener listener : listeners) {\n listener.whenCreating(model);\n }\n return model;\n }\n\n private boolean isSuperDatasetModel(Class aClass) {\n return aClass.isAnnotationPresent(SuperDataset.class);\n }\n\n /**\n * CreatingListener listener could react when {@link #add(Class, int, Storage, boolean)} model happens. Also, the\n * added models are being notified in this add operation.\n */\n @Override\n public void addModelListener(final CreatingListener listener) throws StorageException {\n listeners.add(listener);\n for (Model model : models) {\n listener.whenCreating(model);\n }\n }\n\n /**\n * Read model column metadata based on the class level definition.\n */\n private void retrieval(final Class clazz,\n final String modelName,\n final List modelColumns,\n final int scopeId,\n ShardingKeyChecker checker,\n final SQLDatabaseModelExtension sqlDBModelExtension,\n boolean record) {\n if (log.isDebugEnabled()) {\n log.debug(\"Analysis {} to generate Model.\", clazz.getName());\n }\n\n Field[] fields = clazz.getDeclaredFields();\n\n for (Field field : fields) {\n if (field.isAnnotationPresent(Column.class)) {\n if (field.isAnnotationPresent(SQLDatabase.AdditionalEntity.class)) {\n if (!record) {\n throw new IllegalStateException(\"Model [\" + modelName + \"] is not a Record, @SQLDatabase.AdditionalEntity only supports Record.\");\n }\n }\n\n Column column = field.getAnnotation(Column.class);\n // Use the column#length as the default column length, as read the system env as the override mechanism.\n // Log the error but don't block the startup sequence.\n int columnLength = column.length();\n final String lengthEnvVariable = column.lengthEnvVariable();\n if (StringUtil.isNotEmpty(lengthEnvVariable)) {\n final String envValue = System.getenv(lengthEnvVariable);\n if (StringUtil.isNotEmpty(envValue)) {\n try {\n columnLength = Integer.parseInt(envValue);\n } catch (NumberFormatException e) {\n log.error(\"Model [{}] Column [{}], illegal value {} of column length from system env [{}]\",\n modelName, column.columnName(), envValue, lengthEnvVariable\n );\n }\n }\n }\n\n // SQL Database extension\n SQLDatabaseExtension sqlDatabaseExtension = new SQLDatabaseExtension();\n List indexDefinitions = new ArrayList<>();\n if (field.isAnnotationPresent(SQLDatabase.QueryUnifiedIndex.class)) {\n indexDefinitions.add(field.getAnnotation(SQLDatabase.QueryUnifiedIndex.class));\n }\n\n if (field.isAnnotationPresent(SQLDatabase.MultipleQueryUnifiedIndex.class)) {\n Collections.addAll(\n indexDefinitions, field.getAnnotation(SQLDatabase.MultipleQueryUnifiedIndex.class).value());\n }\n\n indexDefinitions.forEach(indexDefinition -> {\n sqlDatabaseExtension.appendIndex(new SQLDatabaseExtension.MultiColumnsIndex(\n column.columnName(),\n indexDefinition.withColumns()\n ));\n });\n\n // ElasticSearch extension\n final ElasticSearch.MatchQuery elasticSearchAnalyzer = field.getAnnotation(\n ElasticSearch.MatchQuery.class);\n final ElasticSearch.Column elasticSearchColumn = field.getAnnotation(ElasticSearch.Column.class);\n ElasticSearchExtension elasticSearchExtension = new ElasticSearchExtension(\n elasticSearchAnalyzer == null ? null : elasticSearchAnalyzer.analyzer(),\n elasticSearchColumn == null ? null : elasticSearchColumn.columnAlias()\n );\n\n // BanyanDB extension\n final BanyanDB.ShardingKey banyanDBShardingKey = field.getAnnotation(\n BanyanDB.ShardingKey.class);\n final BanyanDB.GlobalIndex banyanDBGlobalIndex = field.getAnnotation(\n BanyanDB.GlobalIndex.class);\n final BanyanDB.NoIndexing banyanDBNoIndex = field.getAnnotation(\n BanyanDB.NoIndexing.class);\n final BanyanDB.IndexRule banyanDBIndexRule = field.getAnnotation(\n BanyanDB.IndexRule.class);\n BanyanDBExtension banyanDBExtension = new BanyanDBExtension(\n banyanDBShardingKey == null ? -1 : banyanDBShardingKey.index(),\n banyanDBGlobalIndex != null,\n banyanDBNoIndex == null && column.storageOnly(),\n banyanDBIndexRule == null ? BanyanDB.IndexRule.IndexType.INVERTED : banyanDBIndexRule.indexType()\n );\n\n final ModelColumn modelColumn = new ModelColumn(\n new ColumnName(\n modelName,\n column.columnName()\n ),\n field.getType(),\n field.getGenericType(),\n column.storageOnly(),\n column.indexOnly(),\n column.dataType().isValue(),\n columnLength,\n sqlDatabaseExtension,\n elasticSearchExtension,\n banyanDBExtension\n );\n if (banyanDBExtension.isShardingKey()) {\n checker.accept(modelName, modelColumn);\n }\n\n if (field.isAnnotationPresent(SQLDatabase.AdditionalEntity.class)) {\n String[] tableNames = field.getAnnotation(SQLDatabase.AdditionalEntity.class).additionalTables();\n for (final String tableName : tableNames) {\n sqlDBModelExtension.appendAdditionalTable(tableName, modelColumn);\n }\n if (!field.getAnnotation(SQLDatabase.AdditionalEntity.class).reserveOriginalColumns()) {\n sqlDBModelExtension.appendExcludeColumns(modelColumn);\n }\n }\n\n modelColumns.add(modelColumn);\n if (log.isDebugEnabled()) {\n log.debug(\"The field named [{}] with the [{}] type\", column.columnName(), field.getType());\n }\n if (column.dataType().isValue()) {\n ValueColumnMetadata.INSTANCE.putIfAbsent(\n modelName, column.columnName(), column.dataType(), column.function(),\n column.defaultValue(), scopeId\n );\n }\n }\n }\n\n // For the annotation need to be declared on the superclass, the other annotation should be declared on the subclass.\n if (!sqlDBModelExtension.getSharding().isPresent() && clazz.isAnnotationPresent(SQLDatabase.Sharding.class)) {\n SQLDatabase.Sharding sharding = clazz.getAnnotation(SQLDatabase.Sharding.class);\n sqlDBModelExtension.setSharding(\n Optional.of(new SQLDatabaseModelExtension.Sharding(sharding.shardingAlgorithm(),\n sharding.dataSourceShardingColumn(),\n sharding.tableShardingColumn()\n )));\n }\n\n if (Objects.nonNull(clazz.getSuperclass())) {\n retrieval(clazz.getSuperclass(), modelName, modelColumns, scopeId, checker, sqlDBModelExtension, record);\n }\n }\n\n @Override\n public void overrideColumnName(String columnName, String newName) {\n columnNameOverrideRule.put(columnName, newName);\n models.forEach(this::followColumnNameRules);\n ValueColumnMetadata.INSTANCE.overrideColumnName(columnName, newName);\n }\n\n private void followColumnNameRules(Model model) {\n columnNameOverrideRule.forEach((oldName, newName) -> {\n model.getColumns().forEach(column -> {\n column.getColumnName().overrideName(oldName, newName);\n column.getSqlDatabaseExtension()\n .getIndices()\n .forEach(extraQueryIndex -> extraQueryIndex.overrideName(oldName, newName));\n });\n });\n }\n\n private boolean addExtraColumn4AdditionalEntity(SQLDatabaseModelExtension sqlDBModelExtension,\n List modelColumns,\n String extraColumn, List additionalTables) {\n for (ModelColumn modelColumn : modelColumns) {\n if (modelColumn.getColumnName().getName().equals(extraColumn)) {\n additionalTables.forEach(tableName -> {\n sqlDBModelExtension.appendAdditionalTable(tableName, modelColumn);\n });\n return true;\n }\n }\n return false;\n }\n\n @Override\n public List allModels() {\n return models;\n }\n\n private class ShardingKeyChecker {\n private ArrayList keys = new ArrayList<>();\n\n /**\n * @throws IllegalStateException if sharding key indices are conflicting.\n */\n private void accept(String modelName, ModelColumn modelColumn) throws IllegalStateException {\n final int idx = modelColumn.getBanyanDBExtension().getShardingKeyIdx();\n while (idx + 1 > keys.size()) {\n keys.add(null);\n }\n ModelColumn exist = keys.get(idx);\n if (exist != null) {\n throw new IllegalStateException(\n modelName + \"'s \"\n + \"Column [\" + exist.getColumnName() + \"] and column [\" + modelColumn.getColumnName()\n + \" are conflicting with sharding key index=\" + modelColumn.getBanyanDBExtension()\n .getShardingKeyIdx());\n }\n keys.set(idx, modelColumn);\n }\n\n /**\n * @param modelName model name of the entity\n * @throws IllegalStateException if sharding key indices are not continuous\n */\n private void check(String modelName) throws IllegalStateException {\n for (int i = 0; i < keys.size(); i++) {\n final ModelColumn modelColumn = keys.get(i);\n if (modelColumn == null) {\n throw new IllegalStateException(\"Sharding key index=\" + i + \" is missing in \" + modelName);\n }\n }\n }\n }\n}\n", "file_name": "StorageModels.java", "human_label": "Check whether the key contains null.", "level": "self_contained", "lineno": "331", "name": "check", "oracle_context": "{ \"apis\" : \"[size, get]\", \"classes\" : \"[ModelColumn]\", \"vars\" : \"[keys]\" }", "package": "org.apache.skywalking.oap.server.core.storage.model", "project": "skywalking-master" }, { "_id": "636766f81a6d9265ec01774b", "all_context": "{ \"class_level\" : \"import net.hasor.web.upload.util.Streams;\\nimport java.io.*;\\nimport static java.lang.String.format;\\nimport static net.hasor.web.upload.FileUploadException.UploadErrorCodes.*;\\nbyte CR;\\nbyte LF;\\nbyte DASH;\\nint HEADER_PART_SIZE_MAX;\\nint DEFAULT_BUFSIZE;\\nbyte[] HEADER_SEPARATOR;\\nbyte[] FIELD_SEPARATOR;\\nbyte[] STREAM_TERMINATOR;\\nbyte[] BOUNDARY_PREFIX;\\nInputStream input;\\nint boundaryLength;\\nint keepRegion;\\nbyte[] boundary;\\nint bufSize;\\nbyte[] buffer;\\nint head;\\nint tail;\\nString headerEncoding;\\nlong total;\\nint pad;\\nint pos;\\nboolean closed;\\nint BYTE_POSITIVE_OFFSET;\\nMultipartStream(InputStream input,byte[] boundary,int bufSize);\\nMultipartStream(InputStream input,byte[] boundary);\\ngetHeaderEncoding();\\nsetHeaderEncoding(String encoding);\\nreadBoundary();\\nsetBoundary(byte[] boundary);\\nreadHeaders();\\nreadBodyData(OutputStream output);\\nnewInputStream();\\ndiscardBodyData();\\nskipPreamble();\\narrayequals(byte[] a,byte[] b,int count);\\nfindByte(byte value,int pos);\\nfindSeparator();\\nItemInputStream();\\ngetBytesRead();\\navailable();\\nread();\\nread(byte[] b,int off,int len);\\nclose();\\nclose(boolean pCloseUnderlying);\\nskip(long bytes);\\nmakeAvailable();\\nisClosed();\\n\", \"repo_level\" : \"public interface Streams {static long copy(InputStream inputStream,OutputStream outputStream,boolean closeOutputStream);\\nstatic long copy(InputStream inputStream,OutputStream outputStream,boolean closeOutputStream,byte[] buffer);\\nstatic String asString(InputStream inputStream);\\nstatic String asString(InputStream inputStream,String encoding);\\nstatic String checkFileName(String fileName);\\n }\\n\" }", "class_name": "MultipartStream", "code": "public byte readByte() throws IOException {\n if (head == tail) {\n head=0;\n tail=input.read(buffer,head,bufSize);\n if (tail == -1) {\n throw new IOException(\"No more data is available\");\n }\n }\n return buffer[head++];\n}\n", "docstring": "/** \n * Reads a byte from the buffer, and refills it as necessary.\n * @return The next byte from the input stream.\n * @throws IOException if there is no more data available.\n */\n", "end_lineno": "203", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.web.upload;\nimport net.hasor.web.upload.util.Streams;\n\nimport java.io.*;\n\nimport static java.lang.String.format;\nimport static net.hasor.web.upload.FileUploadException.UploadErrorCodes.*;\n\n/**\n *

      Low level API for processing file uploads.\n *\n *

      This class can be used to process data streams conforming to MIME\n * 'multipart' format as defined in\n * RFC 1867. Arbitrarily\n * large amounts of data in the stream can be processed under constant\n * memory usage.\n *\n *

      The format of the stream is defined in the following way:
      \n *\n * \n * multipart-body := preamble 1*encapsulation close-delimiter epilogue
      \n * encapsulation := delimiter body CRLF
      \n * delimiter := \"--\" boundary CRLF
      \n * close-delimiter := \"--\" boundary \"--\"
      \n * preamble := <ignore>
      \n * epilogue := <ignore>
      \n * body := header-part CRLF body-part
      \n * header-part := 1*header CRLF
      \n * header := header-name \":\" header-value
      \n * header-name := <printable ascii characters except \":\">
      \n * header-value := <any ascii characters except CR & LF>
      \n * body-data := <arbitrary data>
      \n *
      \n *\n *

      Note that body-data can contain another mulipart entity. There\n * is limited support for single pass processing of such nested\n * streams. The nested stream is required to have a\n * boundary token of the same length as the parent stream (see {@link\n * #setBoundary(byte[])}).\n *\n *

      Here is an example of usage of this class.
      \n *\n *

      \n *   try {\n *     MultipartStream multipartStream = new MultipartStream(input, boundary);\n *     boolean nextPart = multipartStream.skipPreamble();\n *     OutputStream output;\n *     while(nextPart) {\n *       String header = multipartStream.readHeaders();\n *       // process headers\n *       // create some output stream\n *       multipartStream.readBodyData(output);\n *       nextPart = multipartStream.readBoundary();\n *     }\n *   } catch(MultipartStream.MalformedStreamException e) {\n *     // the stream failed to follow required syntax\n *   } catch(IOException e) {\n *     // a read or write error occurred\n *   }\n * 
      \n *\n * @version $Id: MultipartStream.java 1745065 2016-05-22 14:56:37Z britter $\n */\nclass MultipartStream {\n // ----------------------------------------------------- Manifest constants\n /** The Carriage Return ASCII character value. */\n public static final byte CR = 0x0D;\n /** The Line Feed ASCII character value. */\n public static final byte LF = 0x0A;\n /** The dash (-) ASCII character value. */\n public static final byte DASH = 0x2D;\n /** The maximum length of header-part that will be processed (10 kilobytes = 10240 bytes.). */\n public static final int HEADER_PART_SIZE_MAX = 10240;\n /** The default length of the buffer used for processing a request. */\n protected static final int DEFAULT_BUFSIZE = 4096;\n /** A byte sequence that marks the end of header-part (CRLFCRLF). */\n protected static final byte[] HEADER_SEPARATOR = { CR, LF, CR, LF };\n /** A byte sequence that that follows a delimiter that will be followed by an encapsulation (CRLF). */\n protected static final byte[] FIELD_SEPARATOR = { CR, LF };\n /** A byte sequence that that follows a delimiter of the last encapsulation in the stream (--). */\n protected static final byte[] STREAM_TERMINATOR = { DASH, DASH };\n /** A byte sequence that precedes a boundary (CRLF--). */\n protected static final byte[] BOUNDARY_PREFIX = { CR, LF, DASH, DASH };\n // ----------------------------------------------------------- Data members\n /** The input stream from which data is read. */\n private final InputStream input;\n /** The length of the boundary token plus the leading CRLF--. */\n private int boundaryLength;\n /** The amount of data, in bytes, that must be kept in the buffer in order to detect delimiters reliably. */\n private int keepRegion;\n /** The byte sequence that partitions the stream. */\n private byte[] boundary;\n /** The length of the buffer used for processing the request. */\n private final int bufSize;\n /** The buffer used for processing the request. */\n private final byte[] buffer;\n /** The index of first valid character in the buffer.
      0 <= head < bufSize */\n private int head;\n /** The index of last valid character in the buffer + 1.
      0 <= tail <= bufSize */\n private int tail;\n /** The content encoding to use when reading headers. */\n private String headerEncoding;\n // ----------------------------------------------------------- Constructors\n\n /**\n *

      Constructs a MultipartStream with a custom size buffer.\n *\n *

      Note that the buffer must be at least big enough to contain the\n * boundary string, plus 4 characters for CR/LF and double dash, plus at\n * least one byte of data. Too small a buffer size setting will degrade\n * performance.\n *\n * @param input The InputStream to serve as a data source.\n * @param boundary The token used for dividing the stream into\n * encapsulations.\n * @param bufSize The size of the buffer to be used, in bytes.\n * @throws IllegalArgumentException If the buffer size is too small\n * @since 1.3.1\n */\n public MultipartStream(InputStream input, byte[] boundary, int bufSize) {\n if (boundary == null) {\n throw new IllegalArgumentException(\"boundary may not be null\");\n }\n // We prepend CR/LF to the boundary to chop trailing CR/LF from body-data tokens.\n this.boundaryLength = boundary.length + BOUNDARY_PREFIX.length;\n if (bufSize < this.boundaryLength + 1) {\n throw new IllegalArgumentException(\"The buffer size specified for the MultipartStream is too small\");\n }\n this.input = input;\n this.bufSize = Math.max(bufSize, boundaryLength * 2);\n this.buffer = new byte[this.bufSize];\n this.boundary = new byte[this.boundaryLength];\n this.keepRegion = this.boundary.length;\n System.arraycopy(BOUNDARY_PREFIX, 0, this.boundary, 0, BOUNDARY_PREFIX.length);\n System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length);\n head = 0;\n tail = 0;\n }\n\n /**\n *

      Constructs a MultipartStream with a default size buffer.\n * @param input The InputStream to serve as a data source.\n * @param boundary The token used for dividing the stream into encapsulations.\n * @see #MultipartStream(InputStream, byte[], int)\n */\n MultipartStream(InputStream input, byte[] boundary) {\n this(input, boundary, DEFAULT_BUFSIZE);\n }\n // --------------------------------------------------------- Public methods\n\n /**\n * Retrieves the character encoding used when reading the headers of an\n * individual part. When not specified, or null, the platform default encoding is used.\n * @return The encoding used to read part headers.\n */\n public String getHeaderEncoding() {\n return headerEncoding;\n }\n\n /**\n * Specifies the character encoding to be used when reading the headers of\n * individual parts. When not specified, or null, the platform\n * default encoding is used.\n * @param encoding The encoding used to read part headers.\n */\n public void setHeaderEncoding(String encoding) {\n headerEncoding = encoding;\n }\n\n /**\n * Reads a byte from the buffer, and refills it as necessary.\n * @return The next byte from the input stream.\n * @throws IOException if there is no more data available.\n */\n public byte readByte() throws IOException {\n // Buffer depleted ?\n if (head == tail) {\n head = 0;\n // Refill.\n tail = input.read(buffer, head, bufSize);\n if (tail == -1) {\n // No more data available.\n throw new IOException(\"No more data is available\");\n }\n }\n return buffer[head++];\n }\n\n /**\n * Skips a boundary token, and checks whether more\n * encapsulations are contained in the stream.\n * @return true if there are more encapsulations in this stream; false otherwise.\n * @throws FileUploadException if the stream ends unexpectedly or fails to follow required syntax.\n */\n public boolean readBoundary() throws IOException {\n byte[] marker = new byte[2];\n boolean nextChunk = false;\n head += boundaryLength;\n marker[0] = readByte();\n if (marker[0] == LF) {\n // Work around IE5 Mac bug with input type=image.\n // Because the boundary delimiter, not including the trailing CRLF, \n // must not appear within any file (RFC 2046, section 5.1.1),\n // we know the missing CR is due to a buggy browser rather than a file \n // containing something similar to a boundary.\n return true;\n }\n marker[1] = readByte();\n if (arrayequals(marker, STREAM_TERMINATOR, 2)) {\n nextChunk = false;\n } else if (arrayequals(marker, FIELD_SEPARATOR, 2)) {\n nextChunk = true;\n } else {\n throw new FileUploadException(MalformedStreamException, \"Unexpected characters follow a boundary\");\n }\n return nextChunk;\n }\n\n /**\n *

      Changes the boundary token used for partitioning the stream.\n *

      This method allows single pass processing of nested multipart streams.\n *

      The boundary token of the nested stream is required to be of the same length as the boundary token in parent stream.\n *

      Restoring the parent stream boundary token after processing of a nested stream is left to the application.\n * @param boundary The boundary to be used for parsing of the nested stream.\n * @throws FileUploadException if the boundary has a different length than the one being currently parsed.\n */\n public void setBoundary(byte[] boundary) throws FileUploadException {\n if (boundary.length != boundaryLength - BOUNDARY_PREFIX.length) {\n throw new FileUploadException(IllegalBoundaryException, \"The length of a boundary token can not be changed\");\n }\n System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length);\n }\n\n /**\n *

      Reads the header-part of the current\n * encapsulation.\n *

      Headers are returned verbatim to the input stream, including the\n * trailing CRLF marker. Parsing is left to the application.\n *

      TODO allow limiting maximum header size to protect against abuse.\n *\n * @return The header-part of the current encapsulation.\n * @throws FileUploadException if the stream ends unexpectedly.\n */\n public String readHeaders() throws IOException {\n int i = 0;\n byte b;\n // to support multi-byte characters\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n int size = 0;\n while (i < HEADER_SEPARATOR.length) {\n try {\n b = readByte();\n } catch (IOException e) {\n throw e;\n }\n if (++size > HEADER_PART_SIZE_MAX) {\n String logMEssage = format(\"Header section has more than %s bytes (maybe it is not properly terminated)\", Integer.valueOf(HEADER_PART_SIZE_MAX));\n throw new FileUploadException(MalformedStreamException, logMEssage);\n }\n if (b == HEADER_SEPARATOR[i]) {\n i++;\n } else {\n i = 0;\n }\n baos.write(b);\n }\n String headers = null;\n if (headerEncoding != null) {\n try {\n headers = baos.toString(headerEncoding);\n } catch (UnsupportedEncodingException e) {\n // Fall back to platform default if specified encoding is not supported.\n headers = baos.toString();\n }\n } else {\n headers = baos.toString();\n }\n return headers;\n }\n\n /**\n *

      Reads body-data from the current encapsulation and writes its contents into the output Stream.\n *

      Arbitrary large amounts of data can be processed by this method using a constant size buffer. \n * @param output The Stream to write data into. May be null, in which case this method is equivalent to {@link #discardBodyData()}.\n * @return the amount of data written.\n * @throws FileUploadException if the stream ends unexpectedly.\n * @throws IOException if an i/o error occurs.\n */\n public int readBodyData(OutputStream output) throws IOException {\n final InputStream istream = newInputStream();\n return (int) Streams.copy(istream, output, false);\n }\n\n /**\n * Creates a new {@link ItemInputStream}.\n * @return A new instance of {@link ItemInputStream}.\n */\n ItemInputStream newInputStream() {\n return new ItemInputStream();\n }\n\n /**\n *

      Reads body-data from the current\n * encapsulation and discards it.\n *\n *

      Use this method to skip encapsulations you don't need or don't understand.\n *\n * @return The amount of data discarded.\n * @throws FileUploadException if the stream ends unexpectedly.\n * @throws IOException if an i/o error occurs.\n */\n public int discardBodyData() throws IOException {\n return readBodyData(null);\n }\n\n /**\n * Finds the beginning of the first encapsulation.\n * @return true if an encapsulation was found in the stream.\n *\n * @throws IOException if an i/o error occurs.\n */\n public boolean skipPreamble() throws IOException {\n // First delimiter may be not preceeded with a CRLF.\n System.arraycopy(boundary, 2, boundary, 0, boundary.length - 2);\n boundaryLength = boundary.length - 2;\n try {\n // Discard all data up to the delimiter.\n discardBodyData();\n // Read boundary - if succeeded, the stream contains an encapsulation.\n return readBoundary();\n } catch (FileUploadException e) {\n if (e.getErrorCode() == MalformedStreamException) {\n return false;\n }\n throw e;\n } finally {\n // Restore delimiter.\n System.arraycopy(boundary, 0, boundary, 2, boundary.length - 2);\n boundaryLength = boundary.length;\n boundary[0] = CR;\n boundary[1] = LF;\n }\n }\n\n /**\n * Compares count first bytes in the arrays a and b.\n * @param a The first array to compare.\n * @param b The second array to compare.\n * @param count How many bytes should be compared.\n *\n * @return true if count first bytes in arrays\n * a and b are equal.\n */\n public static boolean arrayequals(byte[] a, byte[] b, int count) {\n for (int i = 0; i < count; i++) {\n if (a[i] != b[i]) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Searches for a byte of specified value in the buffer,\n * starting at the specified position.\n *\n * @param value The value to find.\n * @param pos The starting position for searching.\n *\n * @return The position of byte found, counting from beginning of the\n * buffer, or -1 if not found.\n */\n protected int findByte(byte value, int pos) {\n for (int i = pos; i < tail; i++) {\n if (buffer[i] == value) {\n return i;\n }\n }\n return -1;\n }\n\n /**\n * Searches for the boundary in the buffer\n * region delimited by head and tail.\n *\n * @return The position of the boundary found, counting from the\n * beginning of the buffer, or -1 if not found.\n */\n protected int findSeparator() {\n int first;\n int match = 0;\n int maxpos = tail - boundaryLength;\n for (first = head; first <= maxpos && match != boundaryLength; first++) {\n first = findByte(boundary[0], first);\n if (first == -1 || first > maxpos) {\n return -1;\n }\n for (match = 1; match < boundaryLength; match++) {\n if (buffer[first + match] != boundary[match]) {\n break;\n }\n }\n }\n if (match == boundaryLength) {\n return first - 1;\n }\n return -1;\n }\n\n /** An {@link InputStream} for reading an items contents. */\n public class ItemInputStream extends InputStream implements net.hasor.web.upload.util.Closeable {\n /** The number of bytes, which have been read so far. */\n private long total;\n /** The number of bytes, which must be hold, because they might be a part of the boundary. */\n private int pad;\n /** The current offset in the buffer. */\n private int pos;\n /** Whether the stream is already closed. */\n private boolean closed;\n\n /** Creates a new instance. */\n ItemInputStream() {\n findSeparator();\n }\n\n /** Called for finding the separator. */\n private void findSeparator() {\n pos = MultipartStream.this.findSeparator();\n if (pos == -1) {\n if (tail - head > keepRegion) {\n pad = keepRegion;\n } else {\n pad = tail - head;\n }\n }\n }\n\n /** Returns the number of bytes, which have been read by the stream.\n * @return Number of bytes, which have been read so far.\n */\n public long getBytesRead() {\n return total;\n }\n\n /**\n * Returns the number of bytes, which are currently available, without blocking.\n * @return Number of bytes in the buffer.\n */\n @Override\n public int available() {\n if (pos == -1) {\n return tail - head - pad;\n }\n return pos - head;\n }\n\n /** Offset when converting negative bytes to integers. */\n private static final int BYTE_POSITIVE_OFFSET = 256;\n\n /**\n * Returns the next byte in the stream.\n * @return The next byte in the stream, as a non-negative integer, or -1 for EOF.\n * @throws IOException An I/O error occurred.\n */\n @Override\n public int read() throws IOException {\n if (closed) {\n throw new FileUploadException(ItemSkippedException);\n }\n if (available() == 0 && makeAvailable() == 0) {\n return -1;\n }\n ++total;\n int b = buffer[head++];\n if (b >= 0) {\n return b;\n }\n return b + BYTE_POSITIVE_OFFSET;\n }\n\n /**\n * Reads bytes into the given buffer.\n * @param b The destination buffer, where to write to.\n * @param off Offset of the first byte in the buffer.\n * @param len Maximum number of bytes to read.\n * @return Number of bytes, which have been actually read, or -1 for EOF.\n * @throws IOException An I/O error occurred.\n */\n @Override\n public int read(byte[] b, int off, int len) throws IOException {\n if (closed) {\n throw new FileUploadException(ItemSkippedException);\n }\n if (len == 0) {\n return 0;\n }\n int res = available();\n if (res == 0) {\n res = makeAvailable();\n if (res == 0) {\n return -1;\n }\n }\n res = Math.min(res, len);\n System.arraycopy(buffer, head, b, off, res);\n head += res;\n total += res;\n return res;\n }\n\n /**\n * Closes the input stream.\n * @throws IOException An I/O error occurred.\n */\n @Override\n public void close() throws IOException {\n close(false);\n }\n\n /**\n * Closes the input stream.\n * @param pCloseUnderlying Whether to close the underlying stream (hard close)\n * @throws IOException An I/O error occurred.\n */\n public void close(boolean pCloseUnderlying) throws IOException {\n if (closed) {\n return;\n }\n if (pCloseUnderlying) {\n closed = true;\n input.close();\n } else {\n for (; ; ) {\n int av = available();\n if (av == 0) {\n av = makeAvailable();\n if (av == 0) {\n break;\n }\n }\n skip(av);\n }\n }\n closed = true;\n }\n\n /**\n * Skips the given number of bytes.\n * @param bytes Number of bytes to skip.\n * @return The number of bytes, which have actually been skipped.\n * @throws IOException An I/O error occurred.\n */\n @Override\n public long skip(long bytes) throws IOException {\n if (closed) {\n throw new FileUploadException(ItemSkippedException);\n }\n int av = available();\n if (av == 0) {\n av = makeAvailable();\n if (av == 0) {\n return 0;\n }\n }\n long res = Math.min(av, bytes);\n head += res;\n return res;\n }\n\n /**\n * Attempts to read more data.\n * @return Number of available bytes\n * @throws IOException An I/O error occurred.\n */\n private int makeAvailable() throws IOException {\n if (pos != -1) {\n return 0;\n }\n // Move the data to the beginning of the buffer.\n total += tail - head - pad;\n System.arraycopy(buffer, tail - pad, buffer, 0, pad);\n // Refill buffer with new data.\n head = 0;\n tail = pad;\n for (; ; ) {\n int bytesRead = input.read(buffer, tail, bufSize - tail);\n if (bytesRead == -1) {\n // The last pad amount is left in the buffer. Boundary can't be in there so signal an error condition.\n final String msg = \"Stream ended unexpectedly\";\n throw new FileUploadException(MalformedStreamException, msg);\n }\n tail += bytesRead;\n findSeparator();\n int av = available();\n if (av > 0 || pos != -1) {\n return av;\n }\n }\n }\n\n /**\n * Returns, whether the stream is closed.\n * @return True, if the stream is closed, otherwise false.\n */\n public boolean isClosed() {\n return closed;\n }\n }\n}", "file_name": "MultipartStream.java", "human_label": "Read the next buffer in the buffer.", "level": "class_runnable", "lineno": "186", "name": "readByte", "oracle_context": "{ \"apis\" : \"[read]\", \"classes\" : \"[]\", \"vars\" : \"[head, tail, input, buffer, bufSize]\" }", "package": "net.hasor.web.upload", "project": "hasor-master" }, { "_id": "636766851a6d9265ec017515", "all_context": "{ \"class_level\" : \"import org.atmosphere.cpr.Action;\\nimport org.atmosphere.cpr.AtmosphereConfig;\\nimport org.atmosphere.cpr.AtmosphereInterceptor;\\nimport org.atmosphere.cpr.AtmosphereResource;\\nimport org.atmosphere.cpr.AtmosphereResourceEvent;\\nimport org.atmosphere.cpr.AtmosphereResourceImpl;\\nimport org.atmosphere.util.Utils;\\nimport org.slf4j.Logger;\\nimport org.slf4j.LoggerFactory;\\nimport java.io.IOException;\\nimport java.util.concurrent.TimeUnit;\\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERERESOURCE_INTERCEPTOR_METHOD;\\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERERESOURCE_INTERCEPTOR_TIMEOUT;\\nimport static org.atmosphere.cpr.AtmosphereResource.TRANSPORT.UNDEFINED;\\nimport static org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter.OnBroadcast;\\nString method;\\nInteger timeoutInSeconds;\\nLogger logger;\\nboolean force;\\nlong timeoutInMilli;\\nAtmosphereResourceLifecycleInterceptor();\\nAtmosphereResourceLifecycleInterceptor(boolean force);\\nconfigure(AtmosphereConfig config);\\nmethod();\\ntimeoutInSeconds();\\nmethod(String method);\\ntimeoutInSeconds(int timeoutInSeconds);\\npostInspect(AtmosphereResource r);\\nonBroadcast(AtmosphereResourceEvent event);\\ndestroy();\\ntoString();\\n\", \"repo_level\" : \"public interface Action {public Action.TYPE type();\\npublic Action type(TYPE type);\\npublic long timeout();\\npublic Action timeout(long timeout);\\npublic boolean equals(Object o);\\npublic int hashCode();\\npublic String toString();\\n }\\npublic interface AtmosphereConfig {public List getAtmosphereHandlerConfig();\\npublic AtmosphereFramework framework();\\npublic ServletConfig getServletConfig();\\npublic ServletContext getServletContext();\\npublic String getWebServerName();\\npublic Map handlers();\\npublic String getInitParameter(String name);\\npublic Enumeration getInitParameterNames();\\npublic boolean isSupportSession();\\npublic void setSupportSession(boolean supportSession);\\npublic boolean isSessionTimeoutRemovalAllowed();\\npublic void setSessionTimeoutRemovalAllowed(boolean sessionTimeoutRemovalAllowed);\\npublic boolean isThrowExceptionOnCloned();\\npublic void setThrowExceptionOnCloned(boolean throwExceptionOnCloned);\\npublic BroadcasterFactory getBroadcasterFactory();\\npublic Map properties();\\nprotected void destroy();\\nprotected void initComplete();\\npublic AtmosphereConfig shutdownHook(ShutdownHook s);\\npublic AtmosphereConfig startupHook(StartupHook s);\\npublic String getInitParameter(String key,String defaultValue);\\npublic boolean getInitParameter(String key,boolean defaultValue);\\npublic int getInitParameter(String key,int defaultValue);\\npublic AtmosphereResourceFactory resourcesFactory();\\npublic MetaBroadcaster metaBroadcaster();\\npublic AtmosphereResourceSessionFactory sessionFactory();\\npublic UUIDProvider uuidProvider();\\npublic WebSocketFactory websocketFactory();\\n void shutdown();\\n void started(AtmosphereFramework framework);\\npublic AtmosphereConfig populate(AtmosphereConfig config);\\n }\\npublic interface AtmosphereInterceptor { Action inspect(AtmosphereResource r);\\n void postInspect(AtmosphereResource r);\\n void destroy();\\n }\\npublic interface AtmosphereResource { TRANSPORT transport();\\n AtmosphereResource resumeOnBroadcast(boolean resumeOnBroadcast);\\n boolean isSuspended();\\n boolean resumeOnBroadcast();\\n boolean isResumed();\\n boolean isCancelled();\\n AtmosphereResource resume();\\n AtmosphereResource suspend();\\n AtmosphereResource suspend(long timeout);\\n AtmosphereResource suspend(long timeout,TimeUnit timeunit);\\n AtmosphereRequest getRequest();\\n AtmosphereResponse getResponse();\\n AtmosphereConfig getAtmosphereConfig();\\n Broadcaster getBroadcaster();\\n List broadcasters();\\n AtmosphereResource removeFromAllBroadcasters();\\n AtmosphereResource setBroadcaster(Broadcaster broadcaster);\\n AtmosphereResource addBroadcaster(Broadcaster broadcaster);\\n AtmosphereResource removeBroadcaster(Broadcaster broadcaster);\\n AtmosphereResource setSerializer(Serializer s);\\n AtmosphereResource write(String s);\\n AtmosphereResource write(byte[] s);\\n Serializer getSerializer();\\n AtmosphereResourceEvent getAtmosphereResourceEvent();\\n AtmosphereHandler getAtmosphereHandler();\\n AtmosphereResource writeOnTimeout(Object o);\\n Object writeOnTimeout();\\n String uuid();\\n AtmosphereResource addEventListener(AtmosphereResourceEventListener e);\\n AtmosphereResource removeEventListener(AtmosphereResourceEventListener e);\\n AtmosphereResource removeEventListeners();\\n AtmosphereResource notifyListeners(AtmosphereResourceEvent e);\\n AtmosphereResource notifyListeners();\\n HttpSession session();\\n HttpSession session(boolean create);\\n void close();\\n AtmosphereResource forceBinaryWrite(boolean force);\\n boolean forceBinaryWrite();\\npublic AtmosphereResource initialize(AtmosphereConfig config,Broadcaster broadcaster,AtmosphereRequest req,AtmosphereResponse response,AsyncSupport asyncSupport,AtmosphereHandler atmosphereHandler);\\n }\\npublic interface AtmosphereResourceEvent { Object getMessage();\\n AtmosphereResourceEvent setMessage(Object o);\\n boolean isResumedOnTimeout();\\n boolean isCancelled();\\n boolean isSuspended();\\n boolean isResuming();\\n AtmosphereResource getResource();\\n boolean isClosedByClient();\\n boolean isClosedByApplication();\\n Throwable throwable();\\n Broadcaster broadcaster();\\n }\\npublic interface AtmosphereResourceImpl {public AtmosphereResource initialize(AtmosphereConfig config,Broadcaster broadcaster,AtmosphereRequest req,AtmosphereResponse response,AsyncSupport asyncSupport,AtmosphereHandler atmosphereHandler);\\nprotected void setUUID(String uuid);\\nprotected void register();\\npublic AtmosphereResourceEventImpl getAtmosphereResourceEvent();\\npublic AtmosphereHandler getAtmosphereHandler();\\npublic AtmosphereResource writeOnTimeout(Object o);\\npublic Object writeOnTimeout();\\npublic String uuid();\\npublic TRANSPORT transport();\\npublic AtmosphereResourceImpl transport(TRANSPORT transport);\\npublic AtmosphereResource resumeOnBroadcast(boolean resumeOnBroadcast);\\npublic boolean isSuspended();\\npublic boolean resumeOnBroadcast();\\npublic AtmosphereResource resume();\\npublic AtmosphereResource suspend();\\npublic AtmosphereResource suspend(long timeout,TimeUnit timeunit);\\npublic AtmosphereResource suspend(long timeout);\\npublic AtmosphereRequest getRequest(boolean enforceScope);\\npublic AtmosphereResponse getResponse(boolean enforceScope);\\npublic AtmosphereRequest getRequest();\\npublic AtmosphereResponse getResponse();\\npublic Broadcaster getBroadcaster();\\npublic List broadcasters();\\nprotected Broadcaster getBroadcaster(boolean autoCreate);\\npublic AtmosphereResource setBroadcaster(Broadcaster broadcaster);\\npublic AtmosphereResource addBroadcaster(Broadcaster broadcaster);\\npublic AtmosphereResource removeBroadcaster(Broadcaster broadcaster);\\nprotected AtmosphereResource uniqueBroadcaster(Broadcaster newB);\\npublic AtmosphereConfig getAtmosphereConfig();\\npublic Action action();\\npublic void reset();\\npublic void setIsInScope(boolean isInScope);\\npublic boolean isInScope();\\npublic AtmosphereResource setSerializer(Serializer s);\\npublic boolean isResumed();\\npublic boolean isCancelled();\\npublic AtmosphereResource write(String s);\\npublic AtmosphereResource write(byte[] o);\\npublic Serializer getSerializer();\\npublic AtmosphereResource addEventListener(AtmosphereResourceEventListener e);\\npublic AtmosphereResource removeEventListener(AtmosphereResourceEventListener e);\\npublic AtmosphereResource removeEventListeners();\\npublic AtmosphereResource notifyListeners();\\npublic AtmosphereResource notifyListeners(AtmosphereResourceEvent event);\\npublic AtmosphereResource removeFromAllBroadcasters();\\npublic void onThrowable(Throwable t);\\n void onThrowable(AtmosphereResourceEvent e);\\n void onHeartbeat(AtmosphereResourceEvent e);\\n void onSuspend(AtmosphereResourceEvent e);\\n void onPreSuspend(AtmosphereResourceEvent e);\\n void onResume(AtmosphereResourceEvent e);\\n void onDisconnect(AtmosphereResourceEvent e);\\n void onBroadcast(AtmosphereResourceEvent e);\\n void onClose(AtmosphereResourceEvent e);\\npublic ConcurrentLinkedQueue atmosphereResourceEventListener();\\npublic AtmosphereResourceImpl atmosphereHandler(AtmosphereHandler atmosphereHandler);\\npublic void cancel();\\npublic void _destroy();\\npublic String toString();\\npublic AtmosphereResourceImpl disableSuspend(boolean disableSuspend);\\npublic HttpSession session(boolean create);\\npublic void close();\\npublic void dirtyClose();\\npublic AtmosphereResource forceBinaryWrite(boolean forceBinaryWrite);\\npublic boolean forceBinaryWrite();\\npublic HttpSession session();\\npublic AtmosphereResourceImpl session(HttpSession session);\\npublic AtmosphereResourceImpl cloneState(AtmosphereResource r);\\npublic ConcurrentLinkedQueue listeners();\\npublic AtmosphereResourceImpl disableSuspendEvent(boolean disableSuspendEvent);\\npublic boolean disableSuspendEvent();\\npublic WebSocket webSocket();\\npublic AtmosphereResourceImpl webSocket(WebSocket webSocket);\\npublic boolean equals(Object o);\\npublic int hashCode();\\npublic boolean getAndSetInClosingPhase();\\npublic boolean isPendingClose();\\npublic boolean getAndSetPendingClose();\\n }\\npublic interface Utils {static boolean webSocketEnabled(HttpServletRequest request);\\nstatic boolean rawWebSocket(HttpServletRequest request);\\nstatic boolean firefoxWebSocketEnabled(HttpServletRequest request);\\nstatic boolean twoConnectionsTransport(TRANSPORT t);\\nstatic boolean webSocketQueryStringPresentOrNull(HttpServletRequest request);\\nstatic boolean resumableTransport(TRANSPORT t);\\nstatic boolean pollableTransport(TRANSPORT t);\\nstatic boolean pushMessage(TRANSPORT t);\\nstatic boolean atmosphereProtocol(AtmosphereRequest r);\\nstatic boolean webSocketMessage(AtmosphereResource r);\\nstatic boolean properProtocol(HttpServletRequest request);\\nstatic AtmosphereResource websocketResource(AtmosphereResource r);\\nstatic boolean closeMessage(HttpServletRequest request);\\nstatic Object invoke(Object proxiedInstance,Method m,Object o);\\nstatic void inject(AtmosphereResource r);\\nstatic void inject(Object object,Class clazz,AtmosphereResource r);\\nstatic void inject(Object object,Class clazz,AtmosphereConfig config);\\nstatic Set getInheritedPrivateFields(Class type);\\nstatic Set getInheritedPrivateMethod(Class type);\\nstatic boolean requestScopedInjection(AtmosphereConfig config,AtmosphereHandler h);\\nstatic boolean requestScopedInjection(AtmosphereConfig config,Object o);\\nstatic void destroyMeteor(AtmosphereRequest req);\\nstatic String pathInfo(AtmosphereRequest request);\\nstatic boolean isRunningTest();\\nstatic boolean isUnderJDK11AndUp();\\n }\\n\" }", "class_name": "AtmosphereResourceLifecycleInterceptor", "code": "@Override public Action inspect(AtmosphereResource r){\nswitch (r.transport()) {\ncase JSONP:\ncase AJAX:\ncase LONG_POLLING:\n r.resumeOnBroadcast(true);\n break;\ndefault :\nbreak;\n}\nreturn Action.CONTINUE;\n}\n", "docstring": "/** \n * Automatically suspend the {@link AtmosphereResource} based on {@link AtmosphereResource.TRANSPORT} value.\n * @param r a {@link AtmosphereResource}\n * @return {@link Action#CONTINUE}\n */\n", "end_lineno": "131", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\npackage org.atmosphere.interceptor;\n\nimport org.atmosphere.cpr.Action;\nimport org.atmosphere.cpr.AtmosphereConfig;\nimport org.atmosphere.cpr.AtmosphereInterceptor;\nimport org.atmosphere.cpr.AtmosphereResource;\nimport org.atmosphere.cpr.AtmosphereResourceEvent;\nimport org.atmosphere.cpr.AtmosphereResourceImpl;\nimport org.atmosphere.util.Utils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.io.IOException;\nimport java.util.concurrent.TimeUnit;\n\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERERESOURCE_INTERCEPTOR_METHOD;\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERERESOURCE_INTERCEPTOR_TIMEOUT;\nimport static org.atmosphere.cpr.AtmosphereResource.TRANSPORT.UNDEFINED;\nimport static org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter.OnBroadcast;\n\n/**\n *

      This {@link AtmosphereInterceptor} implementation automatically suspends the intercepted\n * {@link AtmosphereResource} and takes care of managing the response's state (flushing, resuming,\n * etc.) when a {@link org.atmosphere.cpr.Broadcaster#broadcast} is invoked. When used, {@link org.atmosphere.cpr.AtmosphereHandler} implementations no longer need to make calls to\n * {@link AtmosphereResource#suspend}.\n *

      \n * If your application doesn't use {@link org.atmosphere.cpr.Broadcaster}, this interceptor will not work and you need to programmatically\n * resume, flush, etc.\n *

      \n *

      By default, intercepted {@link AtmosphereResource} instances are suspended when a GET\n * request is received. You can change the triggering http method by configuring\n * {@link org.atmosphere.cpr.ApplicationConfig#ATMOSPHERERESOURCE_INTERCEPTOR_METHOD}\n *

      \n *

      \n *

      Use this class when you don't want to manage the suspend/resume operation from your\n * particular Atmosphere framework implementation classes ({@link org.atmosphere.cpr.AtmosphereHandler},\n * {@link org.atmosphere.websocket.WebSocketHandler}, or\n * {@link org.atmosphere.cpr.Meteor} instances) or extensions (GWT, Jersey, Wicket, etc...)\n *

      \n * For this mechanism to work properly, each client must set the\n * {@link org.atmosphere.cpr.HeaderConfig#X_ATMOSPHERE_TRANSPORT} header. Your AtmosphereHandler must also extends the\n * {@link org.atmosphere.handler.AbstractReflectorAtmosphereHandler} or implements the logic defined inside\n * {@link org.atmosphere.handler.AbstractReflectorAtmosphereHandler#postStateChange(org.atmosphere.cpr.AtmosphereResourceEvent)} \n *\n * @author Jeanfrancois Arcand\n */\npublic class AtmosphereResourceLifecycleInterceptor implements AtmosphereInterceptor {\n\n private String method = \"GET\";\n // For backward compat.\n private Integer timeoutInSeconds = -1;\n private static final Logger logger = LoggerFactory.getLogger(AtmosphereResourceLifecycleInterceptor.class);\n private final boolean force;\n private long timeoutInMilli = -1;\n\n public AtmosphereResourceLifecycleInterceptor(){\n this(false);\n }\n\n public AtmosphereResourceLifecycleInterceptor(boolean force){\n this.force = force;\n }\n\n @Override\n public void configure(AtmosphereConfig config) {\n String s = config.getInitParameter(ATMOSPHERERESOURCE_INTERCEPTOR_METHOD);\n if (s != null) {\n method = s;\n }\n\n s = config.getInitParameter(ATMOSPHERERESOURCE_INTERCEPTOR_TIMEOUT);\n if (s != null) {\n timeoutInSeconds = Integer.valueOf(s);\n timeoutInMilli = TimeUnit.MILLISECONDS.convert(timeoutInSeconds, TimeUnit.SECONDS);\n }\n }\n\n public String method() {\n return method;\n }\n\n public int timeoutInSeconds(){\n return timeoutInSeconds;\n }\n\n public AtmosphereResourceLifecycleInterceptor method(String method){\n this.method = method;\n return this;\n }\n\n public AtmosphereResourceLifecycleInterceptor timeoutInSeconds(int timeoutInSeconds) {\n this.timeoutInSeconds = timeoutInSeconds;\n timeoutInMilli = TimeUnit.MILLISECONDS.convert(timeoutInSeconds, TimeUnit.SECONDS);\n return this;\n }\n\n /**\n * Automatically suspend the {@link AtmosphereResource} based on {@link AtmosphereResource.TRANSPORT} value.\n *\n * @param r a {@link AtmosphereResource}\n * @return {@link Action#CONTINUE}\n */\n @Override\n public Action inspect(AtmosphereResource r) {\n\n switch (r.transport()) {\n case JSONP:\n case AJAX:\n case LONG_POLLING:\n r.resumeOnBroadcast(true);\n break;\n default:\n break;\n }\n return Action.CONTINUE;\n }\n\n @Override\n public void postInspect(final AtmosphereResource r) {\n\n if (Utils.pollableTransport(r.transport()) || r.transport().equals(UNDEFINED) || Utils.webSocketMessage(r)) return;\n\n AtmosphereResourceImpl impl = (AtmosphereResourceImpl) r;\n if ( (force || impl.getRequest(false).getMethod().equalsIgnoreCase(method))\n && !impl.action().equals(Action.CANCELLED)\n && impl.isInScope()) {\n\n logger.trace(\"Marking AtmosphereResource {} for suspend operation\", r.uuid());\n\n switch (r.transport()) {\n case JSONP:\n case AJAX:\n case LONG_POLLING:\n break;\n default:\n r.addEventListener(new OnBroadcast() {\n @Override\n public void onBroadcast(AtmosphereResourceEvent event) {\n try {\n r.getResponse().flushBuffer();\n } catch (IOException e) {\n logger.trace(\"\", e);\n }\n }\n });\n }\n\n r.suspend(timeoutInMilli);\n }\n }\n\n @Override\n public void destroy() {\n }\n\n public String toString() {\n return \"Atmosphere LifeCycle\";\n }\n}\n", "file_name": "AtmosphereResourceLifecycleInterceptor.java", "human_label": "Suspend the AtmosphereResource based on its transport value.", "level": "project_runnable", "lineno": "112", "name": "inspect", "oracle_context": "{ \"apis\" : \"[transport, resumeOnBroadcast]\", \"classes\" : \"[Action]\", \"vars\" : \"[CONTINUE]\" }", "package": "org.atmosphere.interceptor", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767611a6d9265ec018106", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.graph.*;\\nimport java.util.*;\\nGraph,DefaultWeightedEdge> workingGraph;\\ndouble bestCutWeight;\\nSet bestCut;\\nSet vertex;\\nDouble weight;\\nboolean active;\\nStoerWagnerMinimumCut(Graph graph);\\nminCutWeight();\\nminCut();\\nmergeVertices(Set s,Set t);\\nvertexWeight(Set v);\\nVertexAndWeight(Set v,double w,boolean active);\\ncompareTo(VertexAndWeight that);\\ntoString();\\nminimumCutPhase(Set a);\\n\", \"repo_level\" : \"\" }", "class_name": "StoerWagnerMinimumCut", "code": "public double vertexWeight(Set v){\n double wsum=0.0;\n for ( DefaultWeightedEdge e : workingGraph.edgesOf(v)) {\n wsum+=workingGraph.getEdgeWeight(e);\n }\n return wsum;\n}\n", "docstring": "/** \n * Compute the sum of the weights entering a vertex\n * @param v the vertex\n * @return the sum of the weights entering a vertex\n */\n", "end_lineno": "237", "file_content": "/*\n * (C) Copyright 2011-2021, by Robby McKilliam, Ernst de Ridder and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg;\n\nimport org.jgrapht.*;\nimport org.jgrapht.graph.*;\n\nimport java.util.*;\n\n/**\n * Implements the Stoer and Wagner minimum cut\n * algorithm. Deterministically computes the minimum cut in $O(|V||E| + |V| \\log |V|)$ time.\n * This implementation uses Java's PriorityQueue and requires $O(|V||E| \\log |E|)$ time. M. Stoer\n * and F. Wagner, \"A Simple Min-Cut Algorithm\", Journal of the ACM, volume 44, number 4. pp 585-591,\n * 1997.\n *\n * @param the graph vertex type\n * @param the graph edge type\n *\n * @author Robby McKilliam\n * @author Ernst de Ridder\n */\npublic class StoerWagnerMinimumCut\n{\n final Graph, DefaultWeightedEdge> workingGraph;\n\n protected double bestCutWeight = Double.POSITIVE_INFINITY;\n protected Set bestCut;\n\n /**\n * Will compute the minimum cut in graph.\n *\n * @param graph graph over which to run algorithm\n *\n * @throws IllegalArgumentException if a negative weight edge is found\n * @throws IllegalArgumentException if graph has less than 2 vertices\n */\n public StoerWagnerMinimumCut(Graph graph)\n {\n GraphTests.requireUndirected(graph, \"Graph must be undirected\");\n\n if (graph.vertexSet().size() < 2) {\n throw new IllegalArgumentException(\"Graph has less than 2 vertices\");\n }\n\n // get a version of this graph where each vertex is wrapped with a list\n workingGraph = new SimpleWeightedGraph<>(DefaultWeightedEdge.class);\n Map> vertexMap = new HashMap<>();\n for (V v : graph.vertexSet()) {\n Set list = new HashSet<>();\n list.add(v);\n vertexMap.put(v, list);\n workingGraph.addVertex(list);\n }\n for (E e : graph.edgeSet()) {\n if (graph.getEdgeWeight(e) < 0.0) {\n throw new IllegalArgumentException(\"Negative edge weights not allowed\");\n }\n\n V s = graph.getEdgeSource(e);\n Set sNew = vertexMap.get(s);\n V t = graph.getEdgeTarget(e);\n Set tNew = vertexMap.get(t);\n\n // For multigraphs, we sum the edge weights (either all are\n // contained in a cut, or none)\n DefaultWeightedEdge eNew = workingGraph.getEdge(sNew, tNew);\n if (eNew == null) {\n eNew = workingGraph.addEdge(sNew, tNew);\n workingGraph.setEdgeWeight(eNew, graph.getEdgeWeight(e));\n } else {\n workingGraph\n .setEdgeWeight(eNew, workingGraph.getEdgeWeight(eNew) + graph.getEdgeWeight(e));\n }\n }\n\n // arbitrary vertex used to seed the algorithm.\n Set a = workingGraph.vertexSet().iterator().next();\n\n while (workingGraph.vertexSet().size() > 1) {\n minimumCutPhase(a);\n }\n }\n\n /**\n * Implements the MinimumCutPhase function of Stoer and Wagner.\n * \n * @param a the vertex\n */\n protected void minimumCutPhase(Set a)\n {\n // The last and before last vertices added to A.\n Set last = a, beforelast = null;\n\n // queue contains vertices not in A ordered by max weight of edges to A.\n PriorityQueue queue = new PriorityQueue<>();\n\n // Maps vertices to elements of queue\n Map, VertexAndWeight> dmap = new HashMap<>();\n\n // Initialize queue\n for (Set v : workingGraph.vertexSet()) {\n if (v == a) {\n continue;\n }\n DefaultWeightedEdge e = workingGraph.getEdge(v, a);\n Double w = (e == null) ? 0.0 : workingGraph.getEdgeWeight(e);\n VertexAndWeight vandw = new VertexAndWeight(v, w, e != null);\n queue.add(vandw);\n dmap.put(v, vandw);\n }\n\n // Now iteratively update the queue to get the required vertex ordering\n\n while (!queue.isEmpty()) {\n Set v = queue.poll().vertex;\n dmap.remove(v);\n\n beforelast = last;\n last = v;\n\n for (DefaultWeightedEdge e : workingGraph.edgesOf(v)) {\n Set vc = Graphs.getOppositeVertex(workingGraph, e, v);\n VertexAndWeight vcandw = dmap.get(vc);\n if (vcandw != null) {\n queue.remove(vcandw); // this is O(log n) but could be O(1)?\n vcandw.active = true;\n vcandw.weight += workingGraph.getEdgeWeight(e);\n queue.add(vcandw); // this is O(log n) but could be O(1)?\n }\n }\n }\n\n // Update the best cut\n double w = vertexWeight(last);\n if (w < bestCutWeight) {\n bestCutWeight = w;\n bestCut = last;\n }\n\n // merge the last added vertices\n mergeVertices(beforelast, last);\n }\n\n /**\n * Return the weight of the minimum cut\n * \n * @return the weight of the minimum cut\n */\n public double minCutWeight()\n {\n return bestCutWeight;\n }\n\n /**\n * Return a set of vertices on one side of the cut\n * \n * @return a set of vertices on one side of the cut\n */\n public Set minCut()\n {\n return bestCut;\n }\n\n /**\n * Merges vertex $t$ into vertex $s$, summing the weights as required. Returns the merged vertex\n * and the sum of its weights\n * \n * @param s the first vertex\n * @param t the second vertex\n * \n * @return the merged vertex and its weight\n */\n protected VertexAndWeight mergeVertices(Set s, Set t)\n {\n // construct the new combinedvertex\n Set set = new HashSet<>();\n set.addAll(s);\n set.addAll(t);\n workingGraph.addVertex(set);\n\n // add edges and weights to the combined vertex\n double wsum = 0.0;\n for (Set v : workingGraph.vertexSet()) {\n if ((s != v) && (t != v)) {\n double neww = 0.0;\n DefaultWeightedEdge etv = workingGraph.getEdge(t, v);\n DefaultWeightedEdge esv = workingGraph.getEdge(s, v);\n if (etv != null) {\n neww += workingGraph.getEdgeWeight(etv);\n }\n if (esv != null) {\n neww += workingGraph.getEdgeWeight(esv);\n }\n if ((etv != null) || (esv != null)) {\n wsum += neww;\n workingGraph.setEdgeWeight(workingGraph.addEdge(set, v), neww);\n }\n }\n }\n\n // remove original vertices\n workingGraph.removeVertex(t);\n workingGraph.removeVertex(s);\n\n return new VertexAndWeight(set, wsum, false);\n }\n\n /**\n * Compute the sum of the weights entering a vertex\n * \n * @param v the vertex\n * @return the sum of the weights entering a vertex\n */\n public double vertexWeight(Set v)\n {\n double wsum = 0.0;\n for (DefaultWeightedEdge e : workingGraph.edgesOf(v)) {\n wsum += workingGraph.getEdgeWeight(e);\n }\n return wsum;\n }\n\n /**\n * Class for weighted vertices\n */\n protected class VertexAndWeight\n implements\n Comparable\n {\n public Set vertex;\n public Double weight;\n public boolean active; // active == neighbour in A\n\n /**\n * Construct a new weighted vertex.\n * \n * @param v the vertex\n * @param w the weight of the vertex\n * @param active whether it is active\n */\n public VertexAndWeight(Set v, double w, boolean active)\n {\n this.vertex = v;\n this.weight = w;\n this.active = active;\n }\n\n /**\n * compareTo that sorts in reverse order because we need extract-max and queue provides\n * extract-min.\n */\n @Override\n public int compareTo(VertexAndWeight that)\n {\n if (this.active && that.active) {\n return -Double.compare(weight, that.weight);\n }\n if (this.active && !that.active) {\n return -1;\n }\n if (!this.active && that.active) {\n return +1;\n }\n\n // both inactive\n return 0;\n }\n\n @Override\n public String toString()\n {\n return \"(\" + vertex + \", \" + weight + \")\";\n }\n }\n}\n", "file_name": "StoerWagnerMinimumCut.java", "human_label": "Return the sum of the weights entering a vertex.", "level": "class_runnable", "lineno": "224", "name": "vertexWeight", "oracle_context": "{ \"apis\" : \"[edgesOf, getEdgeWeight]\", \"classes\" : \"[]\", \"vars\" : \"[workingGraph]\" }", "package": "org.jgrapht.alg", "project": "jgrapht-master" }, { "_id": "636767841a6d9265ec0183f2", "all_context": "{ \"class_level\" : \"import java.text.DateFormat;\\nimport java.util.ArrayList;\\nimport java.util.Comparator;\\nimport java.util.Date;\\nimport java.util.Iterator;\\nimport java.util.List;\\nimport java.util.SortedSet;\\nimport java.util.TreeSet;\\nimport javax.swing.table.AbstractTableModel;\\nimport org.apache.log4j.Priority;\\nimport org.apache.log4j.Logger;\\nLogger LOG;\\nComparator MY_COMP;\\nString[] COL_NAMES;\\nEventDetails[] EMPTY_LIST;\\nDateFormat DATE_FORMATTER;\\nObject mLock;\\nSortedSet mAllEvents;\\nEventDetails[] mFilteredEvents;\\nList mPendingEvents;\\nboolean mPaused;\\nString mThreadFilter;\\nString mMessageFilter;\\nString mNDCFilter;\\nString mCategoryFilter;\\nPriority mPriorityFilter;\\nrun();\\nMyTableModel();\\ngetRowCount();\\ngetColumnCount();\\ngetColumnName(int aCol);\\ngetColumnClass(int aCol);\\ngetValueAt(int aRow,int aCol);\\nsetPriorityFilter(Priority aPriority);\\nsetThreadFilter(String aStr);\\nsetMessageFilter(String aStr);\\nsetNDCFilter(String aStr);\\nsetCategoryFilter(String aStr);\\naddEvent(EventDetails aEvent);\\nclear();\\ntoggle();\\nisPaused();\\ngetEventDetails(int aRow);\\nupdateFilteredEvents(boolean aInsertedToFront);\\nmatchFilter(EventDetails aEvent);\\n\", \"repo_level\" : \"public interface Priority {public boolean equals(Object o);\\nfinal int getSyslogEquivalent();\\npublic boolean isGreaterOrEqual(Priority r);\\nstatic Priority[] getAllPossiblePriorities();\\npublic String toString();\\nfinal int toInt();\\nstatic Priority toPriority(String sArg);\\nstatic Priority toPriority(int val);\\nstatic Priority toPriority(int val,Priority defaultPriority);\\nstatic Priority toPriority(String sArg,Priority defaultPriority);\\n }\\npublic interface Logger {public Logger getLogger(String name);\\npublic Logger getLogger(Class clazz);\\nstatic Logger getRootLogger();\\nstatic Logger getLogger(String name,LoggerFactory factory);\\npublic void trace(Object message);\\npublic void trace(Object message,Throwable t);\\npublic boolean isTraceEnabled();\\n }\\n\" }", "class_name": "MyTableModel", "code": "public int compare(Object aObj1,Object aObj2){\n if ((aObj1 == null) && (aObj2 == null)) {\n return 0;\n }\n else if (aObj1 == null) {\n return -1;\n }\n else if (aObj2 == null) {\n return 1;\n }\n final EventDetails le1=(EventDetails)aObj1;\n final EventDetails le2=(EventDetails)aObj2;\n if (le1.getTimeStamp() < le2.getTimeStamp()) {\n return 1;\n }\n return -1;\n}\n", "docstring": "/** \n * @see Comparator \n */\n", "end_lineno": "66", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.log4j.chainsaw;\n\nimport java.text.DateFormat;\nimport java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.SortedSet;\nimport java.util.TreeSet;\nimport javax.swing.table.AbstractTableModel;\nimport org.apache.log4j.Priority;\nimport org.apache.log4j.Logger;\n\n/**\n * Represents a list of EventDetails objects that are sorted on\n * logging time. Methods are provided to filter the events that are visible.\n *\n * @author Oliver Burn\n */\nclass MyTableModel\n extends AbstractTableModel\n{\n\n /** used to log messages **/\n private static final Logger LOG = Logger.getLogger(MyTableModel.class);\n\n /** use the compare logging events **/\n private static final Comparator MY_COMP = new Comparator()\n {\n /** @see Comparator **/\n public int compare(Object aObj1, Object aObj2) {\n if ((aObj1 == null) && (aObj2 == null)) {\n return 0; // treat as equal\n } else if (aObj1 == null) {\n return -1; // null less than everything\n } else if (aObj2 == null) {\n return 1; // think about it. :->\n }\n\n // will assume only have LoggingEvent\n final EventDetails le1 = (EventDetails) aObj1;\n final EventDetails le2 = (EventDetails) aObj2;\n\n if (le1.getTimeStamp() < le2.getTimeStamp()) {\n return 1;\n }\n // assume not two events are logged at exactly the same time\n return -1;\n }\n };\n\n /**\n * Helper that actually processes incoming events.\n * @author Oliver Burn\n */\n private class Processor\n implements Runnable\n {\n /** loops getting the events **/\n public void run() {\n while (true) {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n // ignore\n }\n\n synchronized (mLock) {\n if (mPaused) {\n continue;\n }\n\n boolean toHead = true; // were events added to head\n boolean needUpdate = false;\n final Iterator it = mPendingEvents.iterator();\n while (it.hasNext()) {\n final EventDetails event = (EventDetails) it.next();\n mAllEvents.add(event);\n toHead = toHead && (event == mAllEvents.first());\n needUpdate = needUpdate || matchFilter(event);\n }\n mPendingEvents.clear();\n\n if (needUpdate) {\n updateFilteredEvents(toHead);\n }\n }\n }\n\n }\n }\n\n\n /** names of the columns in the table **/\n private static final String[] COL_NAMES = {\n \"Time\", \"Priority\", \"Trace\", \"Category\", \"NDC\", \"Message\"};\n\n /** definition of an empty list **/\n private static final EventDetails[] EMPTY_LIST = new EventDetails[] {};\n\n /** used to format dates **/\n private static final DateFormat DATE_FORMATTER =\n DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);\n\n /** the lock to control access **/\n private final Object mLock = new Object();\n /** set of all logged events - not filtered **/\n private final SortedSet mAllEvents = new TreeSet(MY_COMP);\n /** events that are visible after filtering **/\n private EventDetails[] mFilteredEvents = EMPTY_LIST;\n /** list of events that are buffered for processing **/\n private final List mPendingEvents = new ArrayList();\n /** indicates whether event collection is paused to the UI **/\n private boolean mPaused = false;\n\n /** filter for the thread **/\n private String mThreadFilter = \"\";\n /** filter for the message **/\n private String mMessageFilter = \"\";\n /** filter for the NDC **/\n private String mNDCFilter = \"\";\n /** filter for the category **/\n private String mCategoryFilter = \"\";\n /** filter for the priority **/\n private Priority mPriorityFilter = Priority.DEBUG;\n\n\n /**\n * Creates a new MyTableModel instance.\n *\n */\n MyTableModel() {\n final Thread t = new Thread(new Processor());\n t.setDaemon(true);\n t.start();\n }\n\n\n ////////////////////////////////////////////////////////////////////////////\n // Table Methods\n ////////////////////////////////////////////////////////////////////////////\n\n /** @see javax.swing.table.TableModel **/\n public int getRowCount() {\n synchronized (mLock) {\n return mFilteredEvents.length;\n }\n }\n\n /** @see javax.swing.table.TableModel **/\n public int getColumnCount() {\n // does not need to be synchronized\n return COL_NAMES.length;\n }\n\n /** @see javax.swing.table.TableModel **/\n public String getColumnName(int aCol) {\n // does not need to be synchronized\n return COL_NAMES[aCol];\n }\n\n /** @see javax.swing.table.TableModel **/\n public Class getColumnClass(int aCol) {\n // does not need to be synchronized\n return (aCol == 2) ? Boolean.class : Object.class;\n }\n\n /** @see javax.swing.table.TableModel **/\n public Object getValueAt(int aRow, int aCol) {\n synchronized (mLock) {\n final EventDetails event = mFilteredEvents[aRow];\n\n if (aCol == 0) {\n return DATE_FORMATTER.format(new Date(event.getTimeStamp()));\n } else if (aCol == 1) {\n return event.getPriority();\n } else if (aCol == 2) {\n return (event.getThrowableStrRep() == null)\n ? Boolean.FALSE : Boolean.TRUE;\n } else if (aCol == 3) {\n return event.getCategoryName();\n } else if (aCol == 4) {\n return event.getNDC();\n }\n return event.getMessage();\n }\n }\n\n ////////////////////////////////////////////////////////////////////////////\n // Public Methods\n ////////////////////////////////////////////////////////////////////////////\n\n /**\n * Sets the priority to filter events on. Only events of equal or higher\n * property are now displayed.\n *\n * @param aPriority the priority to filter on\n */\n public void setPriorityFilter(Priority aPriority) {\n synchronized (mLock) {\n mPriorityFilter = aPriority;\n updateFilteredEvents(false);\n }\n }\n\n /**\n * Set the filter for the thread field.\n *\n * @param aStr the string to match\n */\n public void setThreadFilter(String aStr) {\n synchronized (mLock) {\n mThreadFilter = aStr.trim();\n updateFilteredEvents(false);\n }\n }\n\n /**\n * Set the filter for the message field.\n *\n * @param aStr the string to match\n */\n public void setMessageFilter(String aStr) {\n synchronized (mLock) {\n mMessageFilter = aStr.trim();\n updateFilteredEvents(false);\n }\n }\n\n /**\n * Set the filter for the NDC field.\n *\n * @param aStr the string to match\n */\n public void setNDCFilter(String aStr) {\n synchronized (mLock) {\n mNDCFilter = aStr.trim();\n updateFilteredEvents(false);\n }\n }\n\n /**\n * Set the filter for the category field.\n *\n * @param aStr the string to match\n */\n public void setCategoryFilter(String aStr) {\n synchronized (mLock) {\n mCategoryFilter = aStr.trim();\n updateFilteredEvents(false);\n }\n }\n\n /**\n * Add an event to the list.\n *\n * @param aEvent a EventDetails value\n */\n public void addEvent(EventDetails aEvent) {\n synchronized (mLock) {\n mPendingEvents.add(aEvent);\n }\n }\n\n /**\n * Clear the list of all events.\n */\n public void clear() {\n synchronized (mLock) {\n mAllEvents.clear();\n mFilteredEvents = new EventDetails[0];\n mPendingEvents.clear();\n fireTableDataChanged();\n }\n }\n\n /** Toggle whether collecting events **/\n public void toggle() {\n synchronized (mLock) {\n mPaused = !mPaused;\n }\n }\n\n /** @return whether currently paused collecting events **/\n public boolean isPaused() {\n synchronized (mLock) {\n return mPaused;\n }\n }\n\n /**\n * Get the throwable information at a specified row in the filtered events.\n *\n * @param aRow the row index of the event\n * @return the throwable information\n */\n public EventDetails getEventDetails(int aRow) {\n synchronized (mLock) {\n return mFilteredEvents[aRow];\n }\n }\n\n ////////////////////////////////////////////////////////////////////////////\n // Private methods\n ////////////////////////////////////////////////////////////////////////////\n\n /**\n * Update the filtered events data structure.\n * @param aInsertedToFront indicates whether events were added to front of\n * the events. If true, then the current first event must still exist\n * in the list after the filter is applied.\n */\n private void updateFilteredEvents(boolean aInsertedToFront) {\n final long start = System.currentTimeMillis();\n final List filtered = new ArrayList();\n final int size = mAllEvents.size();\n final Iterator it = mAllEvents.iterator();\n\n while (it.hasNext()) {\n final EventDetails event = (EventDetails) it.next();\n if (matchFilter(event)) {\n filtered.add(event);\n }\n }\n\n final EventDetails lastFirst = (mFilteredEvents.length == 0)\n ? null\n : mFilteredEvents[0];\n mFilteredEvents = (EventDetails[]) filtered.toArray(EMPTY_LIST);\n\n if (aInsertedToFront && (lastFirst != null)) {\n final int index = filtered.indexOf(lastFirst);\n if (index < 1) {\n LOG.warn(\"In strange state\");\n fireTableDataChanged();\n } else {\n fireTableRowsInserted(0, index - 1);\n }\n } else {\n fireTableDataChanged();\n }\n\n final long end = System.currentTimeMillis();\n LOG.debug(\"Total time [ms]: \" + (end - start)\n + \" in update, size: \" + size);\n }\n\n /**\n * Returns whether an event matches the filters.\n *\n * @param aEvent the event to check for a match\n * @return whether the event matches\n */\n private boolean matchFilter(EventDetails aEvent) {\n if (aEvent.getPriority().isGreaterOrEqual(mPriorityFilter) &&\n (aEvent.getThreadName().indexOf(mThreadFilter) >= 0) &&\n (aEvent.getCategoryName().indexOf(mCategoryFilter) >= 0) &&\n ((mNDCFilter.length() == 0) ||\n ((aEvent.getNDC() != null) &&\n (aEvent.getNDC().indexOf(mNDCFilter) >= 0))))\n {\n final String rm = aEvent.getMessage();\n if (rm == null) {\n // only match if we have not filtering in place\n return (mMessageFilter.length() == 0);\n } else {\n return (rm.indexOf(mMessageFilter) >= 0);\n }\n }\n\n return false; // by default not match\n }\n}\n", "file_name": "MyTableModel.java", "human_label": "Compare two events by their timeStamp.", "level": "project_runnable", "lineno": "47", "name": "compare", "oracle_context": "{ \"apis\" : \"[getTimeStamp]\", \"classes\" : \"[EventDetails]\", \"vars\" : \"[]\" }", "package": "org.apache.log4j.chainsaw", "project": "logging-log4j1-main" }, { "_id": "636767861a6d9265ec01844c", "all_context": "{ \"class_level\" : \"import org.apache.log4j.spi.AppenderAttachable;\\nimport org.apache.log4j.spi.LoggingEvent;\\nimport org.apache.log4j.Appender;\\nimport java.util.Vector;\\nimport java.util.Enumeration;\\nVector appenderList;\\nappendLoopOnAppenders(LoggingEvent event);\\ngetAllAppenders();\\ngetAppender(String name);\\nisAttached(Appender appender);\\nremoveAllAppenders();\\nremoveAppender(Appender appender);\\nremoveAppender(String name);\\naddAppender(Appender newAppender);\\n\", \"repo_level\" : \"public interface AppenderAttachable {public void addAppender(Appender newAppender);\\npublic Enumeration getAllAppenders();\\npublic Appender getAppender(String name);\\npublic boolean isAttached(Appender appender);\\n void removeAllAppenders();\\n void removeAppender(Appender appender);\\n void removeAppender(String name);\\n }\\npublic interface LoggingEvent {public LocationInfo getLocationInformation();\\npublic Level getLevel();\\npublic String getLoggerName();\\npublic Category getLogger();\\npublic Object getMessage();\\npublic String getNDC();\\npublic Object getMDC(String key);\\npublic void getMDCCopy();\\npublic String getRenderedMessage();\\nstatic long getStartTime();\\npublic String getThreadName();\\npublic ThrowableInformation getThrowableInformation();\\npublic String[] getThrowableStrRep();\\nfinal void setProperty(String propName,String propValue);\\nfinal String getProperty(String key);\\nfinal boolean locationInformationExists();\\nfinal long getTimeStamp();\\npublic Set getPropertyKeySet();\\npublic Map getProperties();\\npublic String getFQNOfLoggerClass();\\npublic Object removeProperty(String propName);\\n }\\npublic interface Appender { void addFilter(Filter newFilter);\\npublic Filter getFilter();\\npublic void clearFilters();\\npublic void close();\\npublic void doAppend(LoggingEvent event);\\npublic String getName();\\npublic void setErrorHandler(ErrorHandler errorHandler);\\npublic ErrorHandler getErrorHandler();\\npublic void setLayout(Layout layout);\\npublic Layout getLayout();\\npublic void setName(String name);\\npublic boolean requiresLayout();\\n }\\n\" }", "class_name": "AppenderAttachableImpl", "code": "public void removeAppender(String name){\n if (name == null || appenderList == null) return;\n int size=appenderList.size();\n for (int i=0; i < size; i++) {\n if (name.equals(((Appender)appenderList.elementAt(i)).getName())) {\n appenderList.removeElementAt(i);\n break;\n }\n }\n}\n", "docstring": "/** \n * Remove the appender with the name passed as parameter form the list of appenders. \n */\n", "end_lineno": "174", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.log4j.helpers;\n\nimport org.apache.log4j.spi.AppenderAttachable;\nimport org.apache.log4j.spi.LoggingEvent;\n\nimport org.apache.log4j.Appender;\nimport java.util.Vector;\nimport java.util.Enumeration;\n\n/**\n A straightforward implementation of the {@link AppenderAttachable}\n interface.\n\n @author Ceki Gülcü\n @since version 0.9.1 */\npublic class AppenderAttachableImpl implements AppenderAttachable {\n \n /** Array of appenders. */\n protected Vector appenderList;\n\n /**\n Attach an appender. If the appender is already in the list in\n won't be added again.\n */\n public\n void addAppender(Appender newAppender) {\n // Null values for newAppender parameter are strictly forbidden.\n if(newAppender == null)\n return;\n \n if(appenderList == null) {\n appenderList = new Vector(1);\n }\n if(!appenderList.contains(newAppender))\n appenderList.addElement(newAppender);\n }\n\n /**\n Call the doAppend method on all attached appenders. */\n public\n int appendLoopOnAppenders(LoggingEvent event) {\n int size = 0;\n Appender appender;\n\n if(appenderList != null) {\n size = appenderList.size();\n for(int i = 0; i < size; i++) {\n\tappender = (Appender) appenderList.elementAt(i);\n\tappender.doAppend(event);\n }\n } \n return size;\n }\n\n\n /**\n Get all attached appenders as an Enumeration. If there are no\n attached appenders null is returned.\n \n @return Enumeration An enumeration of attached appenders.\n */\n public\n Enumeration getAllAppenders() {\n if(appenderList == null)\n return null;\n else \n return appenderList.elements(); \n }\n\n /**\n Look for an attached appender named as name.\n\n

      Return the appender with that name if in the list. Return null\n otherwise. \n \n */\n public\n Appender getAppender(String name) {\n if(appenderList == null || name == null)\n return null;\n\n int size = appenderList.size();\n Appender appender;\n for(int i = 0; i < size; i++) {\n appender = (Appender) appenderList.elementAt(i);\n if(name.equals(appender.getName()))\n\t return appender;\n }\n return null; \n }\n\n\n /**\n Returns true if the specified appender is in the\n list of attached appenders, false otherwise.\n\n @since 1.2 */\n public \n boolean isAttached(Appender appender) {\n if(appenderList == null || appender == null)\n return false;\n\n int size = appenderList.size();\n Appender a;\n for(int i = 0; i < size; i++) {\n a = (Appender) appenderList.elementAt(i);\n if(a == appender)\n\t return true;\n }\n return false; \n }\n\n\n\n /**\n * Remove and close all previously attached appenders.\n * */\n public\n void removeAllAppenders() {\n if(appenderList != null) {\n int len = appenderList.size(); \n for(int i = 0; i < len; i++) {\n\tAppender a = (Appender) appenderList.elementAt(i);\n\ta.close();\n }\n appenderList.removeAllElements();\n appenderList = null; \n }\n }\n\n\n /**\n Remove the appender passed as parameter form the list of attached\n appenders. */\n public\n void removeAppender(Appender appender) {\n if(appender == null || appenderList == null) \n return;\n appenderList.removeElement(appender); \n }\n\n\n /**\n Remove the appender with the name passed as parameter form the\n list of appenders. \n */\n public\n void removeAppender(String name) {\n if(name == null || appenderList == null) return;\n int size = appenderList.size();\n for(int i = 0; i < size; i++) {\n if(name.equals(((Appender)appenderList.elementAt(i)).getName())) {\n\t appenderList.removeElementAt(i);\n\t break;\n }\n }\n }\n\n}\n", "file_name": "AppenderAttachableImpl.java", "human_label": "Remove the appender by the given name from the list of appenders.", "level": "project_runnable", "lineno": "160", "name": "removeAppender", "oracle_context": "{ \"apis\" : \"[equals, getName, elementAt, removeElementAt]\", \"classes\" : \"[]\", \"vars\" : \"[appenderList]\" }", "package": "org.apache.log4j.helpers", "project": "logging-log4j1-main" }, { "_id": "636767781a6d9265ec018242", "all_context": "{ \"class_level\" : \"import org.apache.log4j.spi.AppenderAttachable;\\nimport org.apache.log4j.spi.LoggingEvent;\\nimport org.apache.log4j.Appender;\\nimport java.util.Vector;\\nimport java.util.Enumeration;\\nVector appenderList;\\nappendLoopOnAppenders(LoggingEvent event);\\ngetAllAppenders();\\ngetAppender(String name);\\nisAttached(Appender appender);\\nremoveAllAppenders();\\nremoveAppender(Appender appender);\\nremoveAppender(String name);\\naddAppender(Appender newAppender);\\n\", \"repo_level\" : \"public interface AppenderAttachable {public void addAppender(Appender newAppender);\\npublic Enumeration getAllAppenders();\\npublic Appender getAppender(String name);\\npublic boolean isAttached(Appender appender);\\n void removeAllAppenders();\\n void removeAppender(Appender appender);\\n void removeAppender(String name);\\n }\\npublic interface LoggingEvent {public LocationInfo getLocationInformation();\\npublic Level getLevel();\\npublic String getLoggerName();\\npublic Category getLogger();\\npublic Object getMessage();\\npublic String getNDC();\\npublic Object getMDC(String key);\\npublic void getMDCCopy();\\npublic String getRenderedMessage();\\nstatic long getStartTime();\\npublic String getThreadName();\\npublic ThrowableInformation getThrowableInformation();\\npublic String[] getThrowableStrRep();\\nfinal void setProperty(String propName,String propValue);\\nfinal String getProperty(String key);\\nfinal boolean locationInformationExists();\\nfinal long getTimeStamp();\\npublic Set getPropertyKeySet();\\npublic Map getProperties();\\npublic String getFQNOfLoggerClass();\\npublic Object removeProperty(String propName);\\n }\\npublic interface Appender { void addFilter(Filter newFilter);\\npublic Filter getFilter();\\npublic void clearFilters();\\npublic void close();\\npublic void doAppend(LoggingEvent event);\\npublic String getName();\\npublic void setErrorHandler(ErrorHandler errorHandler);\\npublic ErrorHandler getErrorHandler();\\npublic void setLayout(Layout layout);\\npublic Layout getLayout();\\npublic void setName(String name);\\npublic boolean requiresLayout();\\n }\\n\" }", "class_name": "AppenderAttachableImpl", "code": "public int appendLoopOnAppenders(LoggingEvent event){\n int size=0;\n Appender appender;\n if (appenderList != null) {\n size=appenderList.size();\n for (int i=0; i < size; i++) {\n appender=(Appender)appenderList.elementAt(i);\n appender.doAppend(event);\n }\n }\n return size;\n}\n", "docstring": "/** \n * Call the doAppend method on all attached appenders. \n */\n", "end_lineno": "70", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.log4j.helpers;\n\nimport org.apache.log4j.spi.AppenderAttachable;\nimport org.apache.log4j.spi.LoggingEvent;\n\nimport org.apache.log4j.Appender;\nimport java.util.Vector;\nimport java.util.Enumeration;\n\n/**\n A straightforward implementation of the {@link AppenderAttachable}\n interface.\n\n @author Ceki Gülcü\n @since version 0.9.1 */\npublic class AppenderAttachableImpl implements AppenderAttachable {\n \n /** Array of appenders. */\n protected Vector appenderList;\n\n /**\n Attach an appender. If the appender is already in the list in\n won't be added again.\n */\n public\n void addAppender(Appender newAppender) {\n // Null values for newAppender parameter are strictly forbidden.\n if(newAppender == null)\n return;\n \n if(appenderList == null) {\n appenderList = new Vector(1);\n }\n if(!appenderList.contains(newAppender))\n appenderList.addElement(newAppender);\n }\n\n /**\n Call the doAppend method on all attached appenders. */\n public\n int appendLoopOnAppenders(LoggingEvent event) {\n int size = 0;\n Appender appender;\n\n if(appenderList != null) {\n size = appenderList.size();\n for(int i = 0; i < size; i++) {\n\tappender = (Appender) appenderList.elementAt(i);\n\tappender.doAppend(event);\n }\n } \n return size;\n }\n\n\n /**\n Get all attached appenders as an Enumeration. If there are no\n attached appenders null is returned.\n \n @return Enumeration An enumeration of attached appenders.\n */\n public\n Enumeration getAllAppenders() {\n if(appenderList == null)\n return null;\n else \n return appenderList.elements(); \n }\n\n /**\n Look for an attached appender named as name.\n\n

      Return the appender with that name if in the list. Return null\n otherwise. \n \n */\n public\n Appender getAppender(String name) {\n if(appenderList == null || name == null)\n return null;\n\n int size = appenderList.size();\n Appender appender;\n for(int i = 0; i < size; i++) {\n appender = (Appender) appenderList.elementAt(i);\n if(name.equals(appender.getName()))\n\t return appender;\n }\n return null; \n }\n\n\n /**\n Returns true if the specified appender is in the\n list of attached appenders, false otherwise.\n\n @since 1.2 */\n public \n boolean isAttached(Appender appender) {\n if(appenderList == null || appender == null)\n return false;\n\n int size = appenderList.size();\n Appender a;\n for(int i = 0; i < size; i++) {\n a = (Appender) appenderList.elementAt(i);\n if(a == appender)\n\t return true;\n }\n return false; \n }\n\n\n\n /**\n * Remove and close all previously attached appenders.\n * */\n public\n void removeAllAppenders() {\n if(appenderList != null) {\n int len = appenderList.size(); \n for(int i = 0; i < len; i++) {\n\tAppender a = (Appender) appenderList.elementAt(i);\n\ta.close();\n }\n appenderList.removeAllElements();\n appenderList = null; \n }\n }\n\n\n /**\n Remove the appender passed as parameter form the list of attached\n appenders. */\n public\n void removeAppender(Appender appender) {\n if(appender == null || appenderList == null) \n return;\n appenderList.removeElement(appender); \n }\n\n\n /**\n Remove the appender with the name passed as parameter form the\n list of appenders. \n */\n public\n void removeAppender(String name) {\n if(name == null || appenderList == null) return;\n int size = appenderList.size();\n for(int i = 0; i < size; i++) {\n if(name.equals(((Appender)appenderList.elementAt(i)).getName())) {\n\t appenderList.removeElementAt(i);\n\t break;\n }\n }\n }\n\n}\n", "file_name": "AppenderAttachableImpl.java", "human_label": "Call the doAppend method on all attached appenders. ", "level": "project_runnable", "lineno": "55", "name": "appendLoopOnAppenders", "oracle_context": "{ \"apis\" : \"[elementAt, doAppend]\", \"classes\" : \"[Appender]\", \"vars\" : \"[appenderList]\" }", "package": "org.apache.log4j.helpers", "project": "logging-log4j1-main" }, { "_id": "6367670c1a6d9265ec017a2a", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static int[] toPrimitive(final Integer[] array){\n if (array == null) {\n return null;\n }\n else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result=new int[array.length];\n for (int i=0; i < array.length; i++) {\n result[i]=array[i].intValue();\n }\n return result;\n}\n", "docstring": "/** \n *

      Converts an array of object Integers to primitives.

      This method returns null for a null input array.

      \n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n", "end_lineno": "2668", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

      Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

      \n *\n *

      This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

      \n *\n *

      #ThreadSafe#

      \n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

      ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

      \n *\n *

      This constructor is public to permit tools that require a JavaBean instance\n * to operate.

      \n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

      \n *\n *

      This method can be used to initialize:

      \n *
      \n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

      Shallow clones an array returning a typecast result and handling\n * null.

      \n *\n *

      The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

      Produces a new array containing the elements between\n * the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n *

      The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

      \n *\n *
      \n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new long array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new int array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new short array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new char array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new byte array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new double array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new float array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new boolean array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

      Any multi-dimensional aspects of the arrays are ignored.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

      \n *\n *

      If the input array is null, 0 is returned.

      \n *\n *
      \n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
      \n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

      Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

      \n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      There is no special handling for multi-dimensional arrays.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given object in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

      Finds the index of the given object in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given object within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given object in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the object is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

      \n *\n *

      The method returns false if a null array\n * is passed in.

      \n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Characters to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Character to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive chars to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Longs to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Long to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive longs to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Integers to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Integer to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive ints to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Shorts to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Short to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive shorts to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Bytes to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Bytes to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive bytes to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Doubles to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Doubles to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive doubles to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Floats to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Floats to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive floats to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Booleans to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Booleans to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive booleans to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

      Checks if an array of Objects is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive longs is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive ints is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive shorts is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive chars is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive bytes is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive doubles is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive floats is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive booleans is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

      Checks if an array of Objects is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive longs is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive ints is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive shorts is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive chars is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive bytes is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive doubles is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive floats is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive booleans is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

      \n *\n *
      \n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
      \n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Convert the given Integer array to primitives. Return ArrayUtils.EMPTY_INT_ARRAY for an empty array, return null for null array.", "level": "self_contained", "lineno": "2648", "name": "toPrimitive", "oracle_context": "{ \"apis\" : \"[intValue, ArrayUtils]\", \"classes\" : \"[int[], ArrayUtils]\", \"vars\" : \"[length, EMPTY_INT_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636767041a6d9265ec017911", "all_context": "{ \"class_level\" : \"import net.hasor.utils.ClassUtils;\\nimport net.hasor.utils.ObjectUtils;\\nimport java.io.Serializable;\\nimport java.lang.reflect.Array;\\nimport java.util.Collection;\\nimport java.util.Map;\\nimport java.util.WeakHashMap;\\nToStringStyle DEFAULT_STYLE;\\nToStringStyle MULTI_LINE_STYLE;\\nToStringStyle NO_FIELD_NAMES_STYLE;\\nToStringStyle SHORT_PREFIX_STYLE;\\nToStringStyle SIMPLE_STYLE;\\nThreadLocal REGISTRY;\\nboolean useFieldNames;\\nboolean useClassName;\\nboolean useShortClassName;\\nboolean useIdentityHashCode;\\nString contentStart;\\nString contentEnd;\\nString fieldNameValueSeparator;\\nboolean fieldSeparatorAtStart;\\nboolean fieldSeparatorAtEnd;\\nString fieldSeparator;\\nString arrayStart;\\nString arraySeparator;\\nboolean arrayContentDetail;\\nString arrayEnd;\\nboolean defaultFullDetail;\\nString nullText;\\nString sizeStartText;\\nString sizeEndText;\\nString summaryObjectStartText;\\nString summaryObjectEndText;\\nlong serialVersionUID;\\ngetRegistry();\\nregister(Object value);\\nunregister(Object value);\\nToStringStyle();\\nappendSuper(StringBuffer buffer,String superToString);\\nappendToString(StringBuffer buffer,String toString);\\nappendStart(StringBuffer buffer,Object object);\\nappendEnd(StringBuffer buffer,Object object);\\nremoveLastFieldSeparator(StringBuffer buffer);\\nappend(StringBuffer buffer,String fieldName,Object value,Boolean fullDetail);\\nappendInternal(StringBuffer buffer,String fieldName,Object value,boolean detail);\\nappendCyclicObject(StringBuffer buffer,String fieldName,Object value);\\nappendDetail(StringBuffer buffer,String fieldName,Object value);\\nappendDetail(StringBuffer buffer,String fieldName,Collection coll);\\nappendDetail(StringBuffer buffer,String fieldName,Map map);\\nappendSummary(StringBuffer buffer,String fieldName,Object value);\\nappend(StringBuffer buffer,String fieldName,long value);\\nappendDetail(StringBuffer buffer,String fieldName,long value);\\nappend(StringBuffer buffer,String fieldName,int value);\\nappendDetail(StringBuffer buffer,String fieldName,int value);\\nappend(StringBuffer buffer,String fieldName,short value);\\nappendDetail(StringBuffer buffer,String fieldName,short value);\\nappend(StringBuffer buffer,String fieldName,byte value);\\nappendDetail(StringBuffer buffer,String fieldName,byte value);\\nappend(StringBuffer buffer,String fieldName,char value);\\nappendDetail(StringBuffer buffer,String fieldName,char value);\\nappend(StringBuffer buffer,String fieldName,double value);\\nappendDetail(StringBuffer buffer,String fieldName,double value);\\nappend(StringBuffer buffer,String fieldName,float value);\\nappendDetail(StringBuffer buffer,String fieldName,float value);\\nappend(StringBuffer buffer,String fieldName,boolean value);\\nappendDetail(StringBuffer buffer,String fieldName,boolean value);\\nappend(StringBuffer buffer,String fieldName,Object[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,Object[] array);\\nreflectionAppendArrayDetail(StringBuffer buffer,String fieldName,Object array);\\nappendSummary(StringBuffer buffer,String fieldName,Object[] array);\\nappend(StringBuffer buffer,String fieldName,long[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,long[] array);\\nappendSummary(StringBuffer buffer,String fieldName,long[] array);\\nappend(StringBuffer buffer,String fieldName,int[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,int[] array);\\nappendSummary(StringBuffer buffer,String fieldName,int[] array);\\nappend(StringBuffer buffer,String fieldName,short[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,short[] array);\\nappendSummary(StringBuffer buffer,String fieldName,short[] array);\\nappend(StringBuffer buffer,String fieldName,byte[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,byte[] array);\\nappendSummary(StringBuffer buffer,String fieldName,byte[] array);\\nappend(StringBuffer buffer,String fieldName,char[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,char[] array);\\nappendSummary(StringBuffer buffer,String fieldName,char[] array);\\nappend(StringBuffer buffer,String fieldName,double[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,double[] array);\\nappendSummary(StringBuffer buffer,String fieldName,double[] array);\\nappend(StringBuffer buffer,String fieldName,float[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,float[] array);\\nappendSummary(StringBuffer buffer,String fieldName,float[] array);\\nappend(StringBuffer buffer,String fieldName,boolean[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,boolean[] array);\\nappendSummary(StringBuffer buffer,String fieldName,boolean[] array);\\nappendClassName(StringBuffer buffer,Object object);\\nappendIdentityHashCode(StringBuffer buffer,Object object);\\nappendContentStart(StringBuffer buffer);\\nappendContentEnd(StringBuffer buffer);\\nappendNullText(StringBuffer buffer,String fieldName);\\nappendFieldSeparator(StringBuffer buffer);\\nappendFieldStart(StringBuffer buffer,String fieldName);\\nappendFieldEnd(StringBuffer buffer,String fieldName);\\nappendSummarySize(StringBuffer buffer,String fieldName,int size);\\nisFullDetail(Boolean fullDetailRequest);\\ngetShortClassName(Class cls);\\nisUseClassName();\\nsetUseClassName(boolean useClassName);\\nisUseShortClassName();\\nisShortClassName();\\nsetUseShortClassName(boolean useShortClassName);\\nsetShortClassName(boolean shortClassName);\\nisUseIdentityHashCode();\\nsetUseIdentityHashCode(boolean useIdentityHashCode);\\nisUseFieldNames();\\nsetUseFieldNames(boolean useFieldNames);\\nisDefaultFullDetail();\\nsetDefaultFullDetail(boolean defaultFullDetail);\\nisArrayContentDetail();\\nsetArrayContentDetail(boolean arrayContentDetail);\\ngetArrayStart();\\nsetArrayStart(String arrayStart);\\ngetArrayEnd();\\nsetArrayEnd(String arrayEnd);\\ngetArraySeparator();\\nsetArraySeparator(String arraySeparator);\\ngetContentStart();\\nsetContentStart(String contentStart);\\ngetContentEnd();\\nsetContentEnd(String contentEnd);\\ngetFieldNameValueSeparator();\\nsetFieldNameValueSeparator(String fieldNameValueSeparator);\\ngetFieldSeparator();\\nsetFieldSeparator(String fieldSeparator);\\nisFieldSeparatorAtStart();\\nsetFieldSeparatorAtStart(boolean fieldSeparatorAtStart);\\nisFieldSeparatorAtEnd();\\nsetFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd);\\ngetNullText();\\nsetNullText(String nullText);\\ngetSizeStartText();\\nsetSizeStartText(String sizeStartText);\\ngetSizeEndText();\\nsetSizeEndText(String sizeEndText);\\ngetSummaryObjectStartText();\\nsetSummaryObjectStartText(String summaryObjectStartText);\\ngetSummaryObjectEndText();\\nsetSummaryObjectEndText(String summaryObjectEndText);\\nDefaultToStringStyle();\\nreadResolve();\\nNoFieldNameToStringStyle();\\nShortPrefixToStringStyle();\\nSimpleToStringStyle();\\nMultiLineToStringStyle();\\ngetSystemProperty(String property);\\nisRegistered(Object value);\\n\", \"repo_level\" : \"public interface ClassUtils {static String getShortClassName(Object object,String valueIfNull);\\nstatic String getShortClassName(Class cls);\\nstatic String getShortClassName(String className);\\nstatic String getPackageName(Object object,String valueIfNull);\\nstatic String getPackageName(Class cls);\\nstatic String getPackageName(String className);\\nstatic List> getAllSuperclasses(Class cls);\\nstatic List> getAllInterfaces(Class cls);\\nstatic List> convertClassNamesToClasses(List classNames);\\nstatic List convertClassesToClassNames(List classes);\\nstatic boolean isAssignable(Class[] classArray,Class[] toClassArray);\\nstatic boolean isAssignable(Class[] classArray,Class[] toClassArray,boolean autoboxing);\\nstatic boolean isAssignable(Class cls,Class toClass);\\nstatic boolean isAssignable(Class cls,Class toClass,boolean autoboxing);\\nstatic Class primitiveToWrapper(Class cls);\\nstatic Class[] primitivesToWrappers(Class[] classes);\\nstatic Class wrapperToPrimitive(Class cls);\\nstatic Class[] wrappersToPrimitives(Class[] classes);\\nstatic boolean isInnerClass(Class cls);\\nstatic Class getClass(ClassLoader classLoader,String className,boolean initialize);\\nstatic Class getClass(ClassLoader classLoader,String className);\\nstatic Class getClass(String className);\\nstatic Class getClass(String className,boolean initialize);\\nstatic Method getPublicMethod(Class cls,String methodName,Class parameterTypes);\\nstatic Class[] toClass(Object[] array);\\nstatic String getShortCanonicalName(Object object,String valueIfNull);\\nstatic String getShortCanonicalName(Class cls);\\nstatic String getShortCanonicalName(String canonicalName);\\nstatic String getPackageCanonicalName(Object object,String valueIfNull);\\nstatic String getPackageCanonicalName(Class cls);\\nstatic String getPackageCanonicalName(String canonicalName);\\nstatic ClassLoader getClassLoader(ClassLoader classLoader);\\nstatic boolean isLangClass(Class target);\\nstatic String getDescName(Class type);\\nstatic String getDescNameWithOutModifiers(Method method);\\nstatic String getDescName(Method method);\\nstatic Class getSuperClassGenricType(Class clazz,int index);\\nstatic T newInstance(Class clazz);\\n }\\npublic interface ObjectUtils {static Object defaultIfNull(Object object,Object defaultValue);\\nstatic boolean equals(Object object1,Object object2);\\nstatic boolean notEqual(Object object1,Object object2);\\nstatic int hashCode(Object obj);\\nstatic String identityToString(Object object);\\nstatic void identityToString(StringBuffer buffer,Object object);\\nstatic String toString(Object obj);\\nstatic String toString(Object obj,String nullStr);\\nstatic Object min(Comparable c1,Comparable c2);\\nstatic Object max(Comparable c1,Comparable c2);\\nstatic int compare(Comparable c1,Comparable c2);\\nstatic int compare(Comparable c1,Comparable c2,boolean nullGreater);\\n }\\n\" }", "class_name": "ToStringStyle", "code": "static void register(Object value){\n if (value != null) {\n Map m=getRegistry();\n if (m == null) {\n m=new WeakHashMap();\n REGISTRY.set(m);\n }\n m.put(value,null);\n }\n}\n", "docstring": "/** \n *

      Registers the given object. Used by the reflection methods to avoid infinite loops.

      \n * @param value The object to register.\n */\n", "end_lineno": "175", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.builder;\nimport net.hasor.utils.ClassUtils;\nimport net.hasor.utils.ObjectUtils;\n\nimport java.io.Serializable;\nimport java.lang.reflect.Array;\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.WeakHashMap;\n\n/**\n *

      Controls String formatting for {@link ToStringBuilder}.\n * The main public interface is always via ToStringBuilder.

      \n *\n *

      These classes are intended to be used as Singletons.\n * There is no need to instantiate a new style each time. A program\n * will generally use one of the predefined constants on this class.\n * Alternatively, the {@link StandardToStringStyle} class can be used\n * to set the individual settings. Thus most styles can be achieved\n * without subclassing.

      \n *\n *

      If required, a subclass can override as many or as few of the\n * methods as it requires. Each object type (from boolean\n * to long to Object to int[]) has\n * its own methods to output it. Most have two versions, detail and summary.\n *\n *

      For example, the detail version of the array based methods will\n * output the whole array, whereas the summary method will just output\n * the array length.

      \n *\n *

      If you want to format the output of certain objects, such as dates, you\n * must create a subclass and override a method.\n *

      \n * public class MyStyle extends ToStringStyle {\n *   protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {\n *     if (value instanceof Date) {\n *       value = new SimpleDateFormat(\"yyyy-MM-dd\").format(value);\n *     }\n *     buffer.append(value);\n *   }\n * }\n * 
      \n *

      \n *\n * @author Apache Software Foundation\n * @author Gary Gregory\n * @author Pete Gieser\n * @author Masato Tezuka\n * @since 1.0\n * @version $Id: ToStringStyle.java 907168 2010-02-06 03:33:50Z mbenson $\n */\npublic abstract class ToStringStyle implements Serializable {\n /**\n * The default toString style. Using the Using the Person\n * example from {@link ToStringBuilder}, the output would look like this:\n *\n *
      \n     * Person@182f0db[name=John Doe,age=33,smoker=false]\n     * 
      \n */\n public static final ToStringStyle DEFAULT_STYLE = new DefaultToStringStyle();\n /**\n * The multi line toString style. Using the Using the Person\n * example from {@link ToStringBuilder}, the output would look like this:\n *\n *
      \n     * Person@182f0db[\n     *   name=John Doe\n     *   age=33\n     *   smoker=false\n     * ]\n     * 
      \n */\n public static final ToStringStyle MULTI_LINE_STYLE = new MultiLineToStringStyle();\n /**\n * The no field names toString style. Using the Using the\n * Person example from {@link ToStringBuilder}, the output\n * would look like this:\n *\n *
      \n     * Person@182f0db[John Doe,33,false]\n     * 
      \n */\n public static final ToStringStyle NO_FIELD_NAMES_STYLE = new NoFieldNameToStringStyle();\n /**\n * The short prefix toString style. Using the Person example\n * from {@link ToStringBuilder}, the output would look like this:\n *\n *
      \n     * Person[name=John Doe,age=33,smoker=false]\n     * 
      \n *\n * @since 2.1\n */\n public static final ToStringStyle SHORT_PREFIX_STYLE = new ShortPrefixToStringStyle();\n /**\n * The simple toString style. Using the Using the Person\n * example from {@link ToStringBuilder}, the output would look like this:\n *\n *
      \n     * John Doe,33,false\n     * 
      \n */\n public static final ToStringStyle SIMPLE_STYLE = new SimpleToStringStyle();\n /**\n *

      \n * A registry of objects used by reflectionToString methods\n * to detect cyclical object references and avoid infinite loops.\n *

      \n */\n private static final ThreadLocal REGISTRY = new ThreadLocal();\n\n /**\n *

      \n * Returns the registry of objects being traversed by the reflectionToString\n * methods in the current thread.\n *

      \n *\n * @return Set the registry of objects being traversed\n */\n static Map getRegistry() {\n return (Map) REGISTRY.get();\n }\n\n /**\n *

      \n * Returns true if the registry contains the given object.\n * Used by the reflection methods to avoid infinite loops.\n *

      \n *\n * @param value\n * The object to lookup in the registry.\n * @return boolean true if the registry contains the given\n * object.\n */\n static boolean isRegistered(Object value) {\n Map m = getRegistry();\n return m != null && m.containsKey(value);\n }\n\n /**\n *

      \n * Registers the given object. Used by the reflection methods to avoid\n * infinite loops.\n *

      \n *\n * @param value\n * The object to register.\n */\n static void register(Object value) {\n if (value != null) {\n Map m = getRegistry();\n if (m == null) {\n m = new WeakHashMap();\n REGISTRY.set(m);\n }\n m.put(value, null);\n }\n }\n\n /**\n *

      \n * Unregisters the given object.\n *

      \n *\n *

      \n * Used by the reflection methods to avoid infinite loops.\n *

      \n *\n * @param value\n * The object to unregister.\n */\n static void unregister(Object value) {\n if (value != null) {\n Map m = getRegistry();\n if (m != null) {\n m.remove(value);\n if (m.isEmpty()) {\n REGISTRY.set(null);\n }\n }\n }\n }\n\n /**\n * Whether to use the field names, the default is true.\n */\n private boolean useFieldNames = true;\n /**\n * Whether to use the class name, the default is true.\n */\n private boolean useClassName = true;\n /**\n * Whether to use short class names, the default is false.\n */\n private boolean useShortClassName = false;\n /**\n * Whether to use the identity hash code, the default is true.\n */\n private boolean useIdentityHashCode = true;\n /**\n * The content start '['.\n */\n private String contentStart = \"[\";\n /**\n * The content end ']'.\n */\n private String contentEnd = \"]\";\n /**\n * The field name value separator '='.\n */\n private String fieldNameValueSeparator = \"=\";\n /**\n * Whether the field separator should be added before any other fields.\n */\n private boolean fieldSeparatorAtStart = false;\n /**\n * Whether the field separator should be added after any other fields.\n */\n private boolean fieldSeparatorAtEnd = false;\n /**\n * The field separator ','.\n */\n private String fieldSeparator = \",\";\n /**\n * The array start '{'.\n */\n private String arrayStart = \"{\";\n /**\n * The array separator ','.\n */\n private String arraySeparator = \",\";\n /**\n * The detail for array content.\n */\n private boolean arrayContentDetail = true;\n /**\n * The array end '}'.\n */\n private String arrayEnd = \"}\";\n /**\n * The value to use when fullDetail is null,\n * the default value is true.\n */\n private boolean defaultFullDetail = true;\n /**\n * The null text '<null>'.\n */\n private String nullText = \"\";\n /**\n * The summary size text start '.\n */\n private String sizeStartText = \"'>'.\n */\n private String sizeEndText = \">\";\n /**\n * The summary object text start '<'.\n */\n private String summaryObjectStartText = \"<\";\n /**\n * The summary object text start '>'.\n */\n private String summaryObjectEndText = \">\";\n //----------------------------------------------------------------------------\n\n /**\n *

      Constructor.

      \n */\n protected ToStringStyle() {\n super();\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString the superclass toString.

      \n *

      NOTE: It assumes that the toString has been created from the same ToStringStyle.

      \n *\n *

      A null superToString is ignored.

      \n *\n * @param buffer the StringBuffer to populate\n * @param superToString the super.toString()\n * @since 2.0\n */\n public void appendSuper(StringBuffer buffer, String superToString) {\n appendToString(buffer, superToString);\n }\n\n /**\n *

      Append to the toString another toString.

      \n *

      NOTE: It assumes that the toString has been created from the same ToStringStyle.

      \n *\n *

      A null toString is ignored.

      \n *\n * @param buffer the StringBuffer to populate\n * @param toString the additional toString\n * @since 2.0\n */\n public void appendToString(StringBuffer buffer, String toString) {\n if (toString != null) {\n int pos1 = toString.indexOf(contentStart) + contentStart.length();\n int pos2 = toString.lastIndexOf(contentEnd);\n if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) {\n String data = toString.substring(pos1, pos2);\n if (fieldSeparatorAtStart) {\n removeLastFieldSeparator(buffer);\n }\n buffer.append(data);\n appendFieldSeparator(buffer);\n }\n }\n }\n\n /**\n *

      Append to the toString the start of data indicator.

      \n *\n * @param buffer the StringBuffer to populate\n * @param object the Object to build a toString for\n */\n public void appendStart(StringBuffer buffer, Object object) {\n if (object != null) {\n appendClassName(buffer, object);\n appendIdentityHashCode(buffer, object);\n appendContentStart(buffer);\n if (fieldSeparatorAtStart) {\n appendFieldSeparator(buffer);\n }\n }\n }\n\n /**\n *

      Append to the toString the end of data indicator.

      \n *\n * @param buffer the StringBuffer to populate\n * @param object the Object to build a\n * toString for.\n */\n public void appendEnd(StringBuffer buffer, Object object) {\n if (this.fieldSeparatorAtEnd == false) {\n removeLastFieldSeparator(buffer);\n }\n appendContentEnd(buffer);\n unregister(object);\n }\n\n /**\n *

      Remove the last field separator from the buffer.

      \n *\n * @param buffer the StringBuffer to populate\n * @since 2.0\n */\n protected void removeLastFieldSeparator(StringBuffer buffer) {\n int len = buffer.length();\n int sepLen = fieldSeparator.length();\n if (len > 0 && sepLen > 0 && len >= sepLen) {\n boolean match = true;\n for (int i = 0; i < sepLen; i++) {\n if (buffer.charAt(len - 1 - i) != fieldSeparator.charAt(sepLen - 1 - i)) {\n match = false;\n break;\n }\n }\n if (match) {\n buffer.setLength(len - sepLen);\n }\n }\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString an Object\n * value, printing the full toString of the\n * Object passed in.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (value == null) {\n appendNullText(buffer, fieldName);\n } else {\n appendInternal(buffer, fieldName, value, isFullDetail(fullDetail));\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString an Object,\n * correctly interpreting its type.

      \n *\n *

      This method performs the main lookup by Class type to correctly\n * route arrays, Collections, Maps and\n * Objects to the appropriate method.

      \n *\n *

      Either detail or summary views can be specified.

      \n *\n *

      If a cycle is detected, an object will be appended with the\n * Object.toString() format.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString,\n * not null\n * @param detail output detail or not\n */\n protected void appendInternal(StringBuffer buffer, String fieldName, Object value, boolean detail) {\n if (isRegistered(value) && !(value instanceof Number || value instanceof Boolean || value instanceof Character)) {\n appendCyclicObject(buffer, fieldName, value);\n return;\n }\n register(value);\n try {\n if (value instanceof Collection) {\n if (detail) {\n appendDetail(buffer, fieldName, (Collection) value);\n } else {\n appendSummarySize(buffer, fieldName, ((Collection) value).size());\n }\n } else if (value instanceof Map) {\n if (detail) {\n appendDetail(buffer, fieldName, (Map) value);\n } else {\n appendSummarySize(buffer, fieldName, ((Map) value).size());\n }\n } else if (value instanceof long[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (long[]) value);\n } else {\n appendSummary(buffer, fieldName, (long[]) value);\n }\n } else if (value instanceof int[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (int[]) value);\n } else {\n appendSummary(buffer, fieldName, (int[]) value);\n }\n } else if (value instanceof short[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (short[]) value);\n } else {\n appendSummary(buffer, fieldName, (short[]) value);\n }\n } else if (value instanceof byte[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (byte[]) value);\n } else {\n appendSummary(buffer, fieldName, (byte[]) value);\n }\n } else if (value instanceof char[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (char[]) value);\n } else {\n appendSummary(buffer, fieldName, (char[]) value);\n }\n } else if (value instanceof double[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (double[]) value);\n } else {\n appendSummary(buffer, fieldName, (double[]) value);\n }\n } else if (value instanceof float[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (float[]) value);\n } else {\n appendSummary(buffer, fieldName, (float[]) value);\n }\n } else if (value instanceof boolean[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (boolean[]) value);\n } else {\n appendSummary(buffer, fieldName, (boolean[]) value);\n }\n } else if (value.getClass().isArray()) {\n if (detail) {\n appendDetail(buffer, fieldName, (Object[]) value);\n } else {\n appendSummary(buffer, fieldName, (Object[]) value);\n }\n } else {\n if (detail) {\n appendDetail(buffer, fieldName, value);\n } else {\n appendSummary(buffer, fieldName, value);\n }\n }\n } finally {\n unregister(value);\n }\n }\n\n /**\n *

      Append to the toString an Object\n * value that has been detected to participate in a cycle. This\n * implementation will print the standard string value of the value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString,\n * not null\n *\n * @since 2.2\n */\n protected void appendCyclicObject(StringBuffer buffer, String fieldName, Object value) {\n ObjectUtils.identityToString(buffer, value);\n }\n\n /**\n *

      Append to the toString an Object\n * value, printing the full detail of the Object.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {\n buffer.append(value);\n }\n\n /**\n *

      Append to the toString a Collection.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param coll the Collection to add to the\n * toString, not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, Collection coll) {\n buffer.append(coll);\n }\n\n /**\n *

      Append to the toString a Map.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param map the Map to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, Map map) {\n buffer.append(map);\n }\n\n /**\n *

      Append to the toString an Object\n * value, printing a summary of the Object.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, Object value) {\n buffer.append(summaryObjectStartText);\n buffer.append(getShortClassName(value.getClass()));\n buffer.append(summaryObjectEndText);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a long\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, long value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a long\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, long value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString an int\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, int value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString an int\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, int value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a short\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, short value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a short\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, short value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a byte\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, byte value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a byte\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, byte value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a char\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, char value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a char\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, char value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a double\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, double value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a double\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, double value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a float\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, float value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a float\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, float value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a boolean\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, boolean value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a boolean\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, boolean value) {\n buffer.append(value);\n }\n\n /**\n *

      Append to the toString an Object\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, Object[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString the detail of an\n * Object array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, Object[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n Object item = array[i];\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n if (item == null) {\n appendNullText(buffer, fieldName);\n } else {\n appendInternal(buffer, fieldName, item, arrayContentDetail);\n }\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString the detail of an array type.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n * @since 2.0\n */\n protected void reflectionAppendArrayDetail(StringBuffer buffer, String fieldName, Object array) {\n buffer.append(arrayStart);\n int length = Array.getLength(array);\n for (int i = 0; i < length; i++) {\n Object item = Array.get(array, i);\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n if (item == null) {\n appendNullText(buffer, fieldName);\n } else {\n appendInternal(buffer, fieldName, item, arrayContentDetail);\n }\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of an\n * Object array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, Object[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a long\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, long[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * long array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, long[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * long array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, long[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString an int\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, int[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of an\n * int array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, int[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of an\n * int array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, int[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a short\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, short[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * short array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, short[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * short array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, short[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a byte\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, byte[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * byte array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, byte[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * byte array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, byte[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a char\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, char[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * char array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, char[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * char array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, char[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a double\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * double array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, double[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * double array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, double[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a float\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, float[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * float array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, float[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * float array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, float[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a boolean\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, boolean[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * boolean array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, boolean[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * boolean array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, boolean[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString the class name.

      \n *\n * @param buffer the StringBuffer to populate\n * @param object the Object whose name to output\n */\n protected void appendClassName(StringBuffer buffer, Object object) {\n if (useClassName && object != null) {\n register(object);\n if (useShortClassName) {\n buffer.append(getShortClassName(object.getClass()));\n } else {\n buffer.append(object.getClass().getName());\n }\n }\n }\n\n /**\n *

      Append the {@link System#identityHashCode(java.lang.Object)}.

      \n *\n * @param buffer the StringBuffer to populate\n * @param object the Object whose id to output\n */\n protected void appendIdentityHashCode(StringBuffer buffer, Object object) {\n if (this.isUseIdentityHashCode() && object != null) {\n register(object);\n buffer.append('@');\n buffer.append(Integer.toHexString(System.identityHashCode(object)));\n }\n }\n\n /**\n *

      Append to the toString the content start.

      \n *\n * @param buffer the StringBuffer to populate\n */\n protected void appendContentStart(StringBuffer buffer) {\n buffer.append(contentStart);\n }\n\n /**\n *

      Append to the toString the content end.

      \n *\n * @param buffer the StringBuffer to populate\n */\n protected void appendContentEnd(StringBuffer buffer) {\n buffer.append(contentEnd);\n }\n\n /**\n *

      Append to the toString an indicator for null.

      \n *\n *

      The default indicator is '<null>'.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n */\n protected void appendNullText(StringBuffer buffer, String fieldName) {\n buffer.append(nullText);\n }\n\n /**\n *

      Append to the toString the field separator.

      \n *\n * @param buffer the StringBuffer to populate\n */\n protected void appendFieldSeparator(StringBuffer buffer) {\n buffer.append(fieldSeparator);\n }\n\n /**\n *

      Append to the toString the field start.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n */\n protected void appendFieldStart(StringBuffer buffer, String fieldName) {\n if (useFieldNames && fieldName != null) {\n buffer.append(fieldName);\n buffer.append(fieldNameValueSeparator);\n }\n }\n\n /**\n *

      Append to the toString the field end.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n */\n protected void appendFieldEnd(StringBuffer buffer, String fieldName) {\n appendFieldSeparator(buffer);\n }\n\n /**\n *

      Append to the toString a size summary.

      \n *\n *

      The size summary is used to summarize the contents of\n * Collections, Maps and arrays.

      \n *\n *

      The output consists of a prefix, the passed in size\n * and a suffix.

      \n *\n *

      The default format is '<size=n>'.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param size the size to append\n */\n protected void appendSummarySize(StringBuffer buffer, String fieldName, int size) {\n buffer.append(sizeStartText);\n buffer.append(size);\n buffer.append(sizeEndText);\n }\n\n /**\n *

      Is this field to be output in full detail.

      \n *\n *

      This method converts a detail request into a detail level.\n * The calling code may request full detail (true),\n * but a subclass might ignore that and always return\n * false. The calling code may pass in\n * null indicating that it doesn't care about\n * the detail level. In this case the default detail level is\n * used.

      \n *\n * @param fullDetailRequest the detail level requested\n * @return whether full detail is to be shown\n */\n protected boolean isFullDetail(Boolean fullDetailRequest) {\n if (fullDetailRequest == null) {\n return defaultFullDetail;\n }\n return fullDetailRequest;\n }\n\n /**\n *

      Gets the short class name for a class.

      \n *\n *

      The short class name is the classname excluding\n * the package name.

      \n *\n * @param cls the Class to get the short name of\n * @return the short name\n */\n protected String getShortClassName(Class cls) {\n return ClassUtils.getShortClassName(cls);\n }\n // Setters and getters for the customizable parts of the style\n // These methods are not expected to be overridden, except to make public\n // (They are not public so that immutable subclasses can be written)\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether to use the class name.

      \n *\n * @return the current useClassName flag\n */\n protected boolean isUseClassName() {\n return useClassName;\n }\n\n /**\n *

      Sets whether to use the class name.

      \n *\n * @param useClassName the new useClassName flag\n */\n protected void setUseClassName(boolean useClassName) {\n this.useClassName = useClassName;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether to output short or long class names.

      \n *\n * @return the current useShortClassName flag\n * @since 2.0\n */\n protected boolean isUseShortClassName() {\n return useShortClassName;\n }\n\n /**\n *

      Gets whether to output short or long class names.

      \n *\n * @return the current shortClassName flag\n * @deprecated Use {@link #isUseShortClassName()}\n * Method will be removed in Commons Lang 3.0.\n */\n protected boolean isShortClassName() {\n return useShortClassName;\n }\n\n /**\n *

      Sets whether to output short or long class names.

      \n *\n * @param useShortClassName the new useShortClassName flag\n * @since 2.0\n */\n protected void setUseShortClassName(boolean useShortClassName) {\n this.useShortClassName = useShortClassName;\n }\n\n /**\n *

      Sets whether to output short or long class names.

      \n *\n * @param shortClassName the new shortClassName flag\n * @deprecated Use {@link #setUseShortClassName(boolean)}\n * Method will be removed in Commons Lang 3.0.\n */\n protected void setShortClassName(boolean shortClassName) {\n this.useShortClassName = shortClassName;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether to use the identity hash code.

      \n *\n * @return the current useIdentityHashCode flag\n */\n protected boolean isUseIdentityHashCode() {\n return useIdentityHashCode;\n }\n\n /**\n *

      Sets whether to use the identity hash code.

      \n *\n * @param useIdentityHashCode the new useIdentityHashCode flag\n */\n protected void setUseIdentityHashCode(boolean useIdentityHashCode) {\n this.useIdentityHashCode = useIdentityHashCode;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether to use the field names passed in.

      \n *\n * @return the current useFieldNames flag\n */\n protected boolean isUseFieldNames() {\n return useFieldNames;\n }\n\n /**\n *

      Sets whether to use the field names passed in.

      \n *\n * @param useFieldNames the new useFieldNames flag\n */\n protected void setUseFieldNames(boolean useFieldNames) {\n this.useFieldNames = useFieldNames;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether to use full detail when the caller doesn't\n * specify.

      \n *\n * @return the current defaultFullDetail flag\n */\n protected boolean isDefaultFullDetail() {\n return defaultFullDetail;\n }\n\n /**\n *

      Sets whether to use full detail when the caller doesn't\n * specify.

      \n *\n * @param defaultFullDetail the new defaultFullDetail flag\n */\n protected void setDefaultFullDetail(boolean defaultFullDetail) {\n this.defaultFullDetail = defaultFullDetail;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether to output array content detail.

      \n *\n * @return the current array content detail setting\n */\n protected boolean isArrayContentDetail() {\n return arrayContentDetail;\n }\n\n /**\n *

      Sets whether to output array content detail.

      \n *\n * @param arrayContentDetail the new arrayContentDetail flag\n */\n protected void setArrayContentDetail(boolean arrayContentDetail) {\n this.arrayContentDetail = arrayContentDetail;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the array start text.

      \n *\n * @return the current array start text\n */\n protected String getArrayStart() {\n return arrayStart;\n }\n\n /**\n *

      Sets the array start text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param arrayStart the new array start text\n */\n protected void setArrayStart(String arrayStart) {\n if (arrayStart == null) {\n arrayStart = \"\";\n }\n this.arrayStart = arrayStart;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the array end text.

      \n *\n * @return the current array end text\n */\n protected String getArrayEnd() {\n return arrayEnd;\n }\n\n /**\n *

      Sets the array end text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param arrayEnd the new array end text\n */\n protected void setArrayEnd(String arrayEnd) {\n if (arrayEnd == null) {\n arrayEnd = \"\";\n }\n this.arrayEnd = arrayEnd;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the array separator text.

      \n *\n * @return the current array separator text\n */\n protected String getArraySeparator() {\n return arraySeparator;\n }\n\n /**\n *

      Sets the array separator text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param arraySeparator the new array separator text\n */\n protected void setArraySeparator(String arraySeparator) {\n if (arraySeparator == null) {\n arraySeparator = \"\";\n }\n this.arraySeparator = arraySeparator;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the content start text.

      \n *\n * @return the current content start text\n */\n protected String getContentStart() {\n return contentStart;\n }\n\n /**\n *

      Sets the content start text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param contentStart the new content start text\n */\n protected void setContentStart(String contentStart) {\n if (contentStart == null) {\n contentStart = \"\";\n }\n this.contentStart = contentStart;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the content end text.

      \n *\n * @return the current content end text\n */\n protected String getContentEnd() {\n return contentEnd;\n }\n\n /**\n *

      Sets the content end text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param contentEnd the new content end text\n */\n protected void setContentEnd(String contentEnd) {\n if (contentEnd == null) {\n contentEnd = \"\";\n }\n this.contentEnd = contentEnd;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the field name value separator text.

      \n *\n * @return the current field name value separator text\n */\n protected String getFieldNameValueSeparator() {\n return fieldNameValueSeparator;\n }\n\n /**\n *

      Sets the field name value separator text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param fieldNameValueSeparator the new field name value separator text\n */\n protected void setFieldNameValueSeparator(String fieldNameValueSeparator) {\n if (fieldNameValueSeparator == null) {\n fieldNameValueSeparator = \"\";\n }\n this.fieldNameValueSeparator = fieldNameValueSeparator;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the field separator text.

      \n *\n * @return the current field separator text\n */\n protected String getFieldSeparator() {\n return fieldSeparator;\n }\n\n /**\n *

      Sets the field separator text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param fieldSeparator the new field separator text\n */\n protected void setFieldSeparator(String fieldSeparator) {\n if (fieldSeparator == null) {\n fieldSeparator = \"\";\n }\n this.fieldSeparator = fieldSeparator;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether the field separator should be added at the start\n * of each buffer.

      \n *\n * @return the fieldSeparatorAtStart flag\n * @since 2.0\n */\n protected boolean isFieldSeparatorAtStart() {\n return fieldSeparatorAtStart;\n }\n\n /**\n *

      Sets whether the field separator should be added at the start\n * of each buffer.

      \n *\n * @param fieldSeparatorAtStart the fieldSeparatorAtStart flag\n * @since 2.0\n */\n protected void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) {\n this.fieldSeparatorAtStart = fieldSeparatorAtStart;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether the field separator should be added at the end\n * of each buffer.

      \n *\n * @return fieldSeparatorAtEnd flag\n * @since 2.0\n */\n protected boolean isFieldSeparatorAtEnd() {\n return fieldSeparatorAtEnd;\n }\n\n /**\n *

      Sets whether the field separator should be added at the end\n * of each buffer.

      \n *\n * @param fieldSeparatorAtEnd the fieldSeparatorAtEnd flag\n * @since 2.0\n */\n protected void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) {\n this.fieldSeparatorAtEnd = fieldSeparatorAtEnd;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the text to output when null found.

      \n *\n * @return the current text to output when null found\n */\n protected String getNullText() {\n return nullText;\n }\n\n /**\n *

      Sets the text to output when null found.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param nullText the new text to output when null found\n */\n protected void setNullText(String nullText) {\n if (nullText == null) {\n nullText = \"\";\n }\n this.nullText = nullText;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the start text to output when a Collection,\n * Map or array size is output.

      \n *\n *

      This is output before the size value.

      \n *\n * @return the current start of size text\n */\n protected String getSizeStartText() {\n return sizeStartText;\n }\n\n /**\n *

      Sets the start text to output when a Collection,\n * Map or array size is output.

      \n *\n *

      This is output before the size value.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param sizeStartText the new start of size text\n */\n protected void setSizeStartText(String sizeStartText) {\n if (sizeStartText == null) {\n sizeStartText = \"\";\n }\n this.sizeStartText = sizeStartText;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the end text to output when a Collection,\n * Map or array size is output.

      \n *\n *

      This is output after the size value.

      \n *\n * @return the current end of size text\n */\n protected String getSizeEndText() {\n return sizeEndText;\n }\n\n /**\n *

      Sets the end text to output when a Collection,\n * Map or array size is output.

      \n *\n *

      This is output after the size value.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param sizeEndText the new end of size text\n */\n protected void setSizeEndText(String sizeEndText) {\n if (sizeEndText == null) {\n sizeEndText = \"\";\n }\n this.sizeEndText = sizeEndText;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the start text to output when an Object is\n * output in summary mode.

      \n *\n *

      This is output before the size value.

      \n *\n * @return the current start of summary text\n */\n protected String getSummaryObjectStartText() {\n return summaryObjectStartText;\n }\n\n /**\n *

      Sets the start text to output when an Object is\n * output in summary mode.

      \n *\n *

      This is output before the size value.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param summaryObjectStartText the new start of summary text\n */\n protected void setSummaryObjectStartText(String summaryObjectStartText) {\n if (summaryObjectStartText == null) {\n summaryObjectStartText = \"\";\n }\n this.summaryObjectStartText = summaryObjectStartText;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the end text to output when an Object is\n * output in summary mode.

      \n *\n *

      This is output after the size value.

      \n *\n * @return the current end of summary text\n */\n protected String getSummaryObjectEndText() {\n return summaryObjectEndText;\n }\n\n /**\n *

      Sets the end text to output when an Object is\n * output in summary mode.

      \n *\n *

      This is output after the size value.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param summaryObjectEndText the new end of summary text\n */\n protected void setSummaryObjectEndText(String summaryObjectEndText) {\n if (summaryObjectEndText == null) {\n summaryObjectEndText = \"\";\n }\n this.summaryObjectEndText = summaryObjectEndText;\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Default ToStringStyle.

      \n *\n *

      This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.

      \n */\n private static final class DefaultToStringStyle extends ToStringStyle {\n /**\n * Required for serialization support.\n *\n * @see java.io.Serializable\n */\n private static final long serialVersionUID = 1L;\n\n /**\n *

      Constructor.

      \n *\n *

      Use the static constant rather than instantiating.

      \n */\n DefaultToStringStyle() {\n super();\n }\n\n /**\n *

      Ensure Singleton after serialization.

      \n *\n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.DEFAULT_STYLE;\n }\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      ToStringStyle that does not print out\n * the field names.

      \n *\n *

      This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.\n */\n private static final class NoFieldNameToStringStyle extends ToStringStyle {\n private static final long serialVersionUID = 1L;\n\n /**\n *

      Constructor.

      \n *\n *

      Use the static constant rather than instantiating.

      \n */\n NoFieldNameToStringStyle() {\n super();\n this.setUseFieldNames(false);\n }\n\n /**\n *

      Ensure Singleton after serialization.

      \n *\n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.NO_FIELD_NAMES_STYLE;\n }\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      ToStringStyle that prints out the short\n * class name and no identity hashcode.

      \n *\n *

      This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.

      \n */\n private static final class ShortPrefixToStringStyle extends ToStringStyle {\n private static final long serialVersionUID = 1L;\n\n /**\n *

      Constructor.

      \n *\n *

      Use the static constant rather than instantiating.

      \n */\n ShortPrefixToStringStyle() {\n super();\n this.setUseShortClassName(true);\n this.setUseIdentityHashCode(false);\n }\n\n /**\n *

      Ensure Singleton after serialization.

      \n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.SHORT_PREFIX_STYLE;\n }\n }\n\n /**\n *

      ToStringStyle that does not print out the\n * classname, identity hashcode, content start or field name.

      \n *\n *

      This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.

      \n */\n private static final class SimpleToStringStyle extends ToStringStyle {\n private static final long serialVersionUID = 1L;\n\n /**\n *

      Constructor.

      \n *\n *

      Use the static constant rather than instantiating.

      \n */\n SimpleToStringStyle() {\n super();\n this.setUseClassName(false);\n this.setUseIdentityHashCode(false);\n this.setUseFieldNames(false);\n this.setContentStart(\"\");\n this.setContentEnd(\"\");\n }\n\n /**\n *

      Ensure Singleton after serialization.

      \n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.SIMPLE_STYLE;\n }\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      ToStringStyle that outputs on multiple lines.

      \n *\n *

      This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.

      \n */\n private static final class MultiLineToStringStyle extends ToStringStyle {\n private static final long serialVersionUID = 1L;\n\n /**\n *

      Constructor.

      \n *\n *

      Use the static constant rather than instantiating.

      \n */\n MultiLineToStringStyle() {\n super();\n String separator = getSystemProperty(\"line.separator\");\n this.setContentStart(\"[\");\n this.setFieldSeparator(separator + \" \");\n this.setFieldSeparatorAtStart(true);\n this.setContentEnd(separator + \"]\");\n }\n\n private String getSystemProperty(final String property) {\n try {\n return System.getProperty(property);\n } catch (SecurityException ex) {\n // we are not allowed to look at this property\n System.err.println(\"Caught a SecurityException reading the system property '\" + property + \"'; the SystemUtils property value will default to null.\");\n return null;\n }\n }\n\n /**\n *

      Ensure Singleton after serialization.

      \n *\n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.MULTI_LINE_STYLE;\n }\n }\n}", "file_name": "ToStringStyle.java", "human_label": "Register the value in REGISTRY if the value is not null.", "level": "class_runnable", "lineno": "157", "name": "register", "oracle_context": "{ \"apis\" : \"[getRegistry, set, put]\", \"classes\" : \"[Map]\", \"vars\" : \"[REGISTRY]\" }", "package": "net.hasor.utils.builder", "project": "hasor-master" }, { "_id": "636767511a6d9265ec017eb0", "all_context": "{ \"class_level\" : \"import org.jgrapht.alg.util.*;\\nimport java.io.*;\\nimport java.util.*;\\nlong serialVersionUID;\\nComparator> INTEGER_PAIR_LEX_COMPARATOR;\\nint columns;\\nint[] rowOffsets;\\nint[] columnIndices;\\nint curPos;\\nint toPos;\\nCSRBooleanMatrix(int rows,int columns,List entries);\\nrows();\\nnonZeros(int row);\\nnonZerosPositionIterator(int row);\\nnonZerosSet(int row);\\nNonZerosIterator(int row);\\nhasNext();\\nnext();\\ncolumns();\\n\", \"repo_level\" : \"\" }", "class_name": "CSRBooleanMatrix", "code": "public int nonZeros(int row){\n assert row >= 0 && row < rowOffsets.length;\n return rowOffsets[row + 1] - rowOffsets[row];\n}\n", "docstring": "/** \n * Get the number of non-zero entries of a row.\n * @param row the row\n * @return the number of non-zero entries of a row\n */\n", "end_lineno": "134", "file_content": "/*\n * (C) Copyright 2019-2021, by Dimitrios Michail and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.opt.graph.sparse.specifics;\n\nimport org.jgrapht.alg.util.*;\n\nimport java.io.*;\nimport java.util.*;\n\n/**\n * A sparse boolean matrix in Compressed Sparse Row (CSR) format.\n * \n *

      \n * This is a helper class for graph representation and thus does not provide a fully fledged matrix.\n * \n * @author Dimitrios Michail\n */\nclass CSRBooleanMatrix\n implements\n Serializable\n{\n private static final long serialVersionUID = -8639339411487665967L;\n\n private static final Comparator> INTEGER_PAIR_LEX_COMPARATOR =\n (o1, o2) -> {\n if (o1.getFirst() < o2.getFirst()) {\n return -1;\n } else if (o1.getFirst() > o2.getFirst()) {\n return 1;\n } else if (o1.getSecond() < o2.getSecond()) {\n return -1;\n } else if (o1.getSecond() > o2.getSecond()) {\n return 1;\n }\n return 0;\n };\n\n private int columns;\n private int[] rowOffsets;\n private int[] columnIndices;\n\n /**\n * Create a new CSR boolean matrix\n * \n * @param rows the number of rows\n * @param columns the number of columns\n * @param entries the position of the entries of the matrix\n */\n public CSRBooleanMatrix(int rows, int columns, List> entries)\n {\n if (rows < 1) {\n throw new IllegalArgumentException(\"Rows must be positive\");\n }\n if (columns < 1) {\n throw new IllegalArgumentException(\"Columns must be positive\");\n }\n if (entries == null) {\n throw new IllegalArgumentException(\"Entries cannot be null\");\n }\n\n this.columns = columns;\n this.rowOffsets = new int[rows + 1];\n this.columnIndices = new int[entries.size()];\n\n Iterator> it =\n entries.stream().sorted(INTEGER_PAIR_LEX_COMPARATOR).iterator();\n\n int cIndex = 0;\n while (it.hasNext()) {\n Pair e = it.next();\n\n // add column index\n int column = e.getSecond();\n if (column < 0 || column >= columns) {\n throw new IllegalArgumentException(\"Entry at invalid column: \" + column);\n }\n columnIndices[cIndex++] = column;\n\n // count non-zero per row\n int row = e.getFirst();\n rowOffsets[row + 1]++;\n }\n\n // prefix sum\n Arrays.parallelPrefix(rowOffsets, (x, y) -> x + y);\n }\n\n /**\n * Get the number of columns of the matrix.\n * \n * @return the number of columns\n */\n public int columns()\n {\n return columns;\n }\n\n /**\n * Get the number of rows of the matrix.\n * \n * @return the number of rows\n */\n public int rows()\n {\n return rowOffsets.length - 1;\n }\n\n /**\n * Get the number of non-zero entries of a row.\n * \n * @param row the row\n * @return the number of non-zero entries of a row\n */\n public int nonZeros(int row)\n {\n assert row >= 0 && row < rowOffsets.length;\n\n return rowOffsets[row + 1] - rowOffsets[row];\n }\n\n /**\n * Get an iterator over the non-zero entries of a row.\n * \n * @param row the row\n * @return an iterator over the non-zero entries of a row\n */\n public Iterator nonZerosPositionIterator(int row)\n {\n assert row >= 0 && row < rowOffsets.length;\n\n return new NonZerosIterator(row);\n }\n\n /**\n * Get the position of non-zero entries of a row as a set.\n * \n * @param row the row\n * @return the position of non-zero entries of a row as a set.\n */\n public Set nonZerosSet(int row)\n {\n assert row >= 0 && row < rowOffsets.length;\n\n Set nonZeros = new LinkedHashSet<>();\n new NonZerosIterator(row).forEachRemaining(nonZeros::add);\n return nonZeros;\n }\n\n private class NonZerosIterator\n implements\n Iterator\n {\n private int curPos;\n private int toPos;\n\n public NonZerosIterator(int row)\n {\n this.curPos = rowOffsets[row];\n this.toPos = rowOffsets[row + 1];\n }\n\n @Override\n public boolean hasNext()\n {\n return (curPos < toPos);\n }\n\n @Override\n public Integer next()\n {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n return columnIndices[curPos++];\n }\n\n }\n\n}\n", "file_name": "CSRBooleanMatrix.java", "human_label": "Return the number of non-zero entries of a row.", "level": "class_runnable", "lineno": "123", "name": "nonZeros", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[rowOffsets]\", \"vars\" : \"[length, rowOffsets]\" }", "package": "org.jgrapht.opt.graph.sparse.specifics", "project": "jgrapht-master" }, { "_id": "6367676c1a6d9265ec018223", "all_context": "{ \"class_level\" : \"import java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.List;\\nimport java.util.Map;\\nimport java.util.Properties;\\nEnumeration enumeration;\\nCollections();\\nsize(Collection collection);\\nsize(Map map);\\nisEmpty(Map map);\\narrayToList(Object source);\\nmergeArrayIntoCollection(Object array,Collection collection);\\nmergePropertiesIntoMap(Properties props,Map map);\\ncontains(Iterator iterator,Object element);\\ncontains(Enumeration enumeration,Object element);\\ncontainsInstance(Collection collection,Object element);\\ncontainsAny(Collection source,Collection candidates);\\nfindFirstMatch(Collection source,Collection candidates);\\nfindValueOfType(Collection collection,Class type);\\nfindValueOfType(Collection collection,Class[] types);\\nhasUniqueObject(Collection collection);\\nfindCommonElementType(Collection collection);\\ntoArray(Enumeration enumeration,A[] array);\\ntoIterator(Enumeration enumeration);\\nEnumerationIterator(Enumeration enumeration);\\nhasNext();\\nnext();\\nremove();\\nisEmpty(Collection collection);\\n\", \"repo_level\" : \"\" }", "class_name": "Collections", "code": "public static boolean containsInstance(Collection collection,Object element){\n if (collection != null) {\n for ( Object candidate : collection) {\n if (candidate == element) {\n return true;\n }\n }\n }\n return false;\n}\n", "docstring": "/** \n * Check whether the given Collection contains the given element instance.

      Enforces the given instance to be present, rather than returning true for an equal element as well.\n * @param collection the Collection to check\n * @param element the element to look for\n * @return true if found, false else\n */\n", "end_lineno": "182", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\npublic final class Collections {\n\n private Collections(){} //prevent instantiation\n\n /**\n * Return true if the supplied Collection is null\n * or empty. Otherwise, return false.\n * @param collection the Collection to check\n * @return whether the given Collection is empty\n */\n public static boolean isEmpty(Collection collection) {\n return (collection == null || collection.isEmpty());\n }\n\n /**\n * Returns the collection's size or {@code 0} if the collection is {@code null}.\n *\n * @param collection the collection to check.\n * @return the collection's size or {@code 0} if the collection is {@code null}.\n * @since 0.9.2\n */\n public static int size(Collection collection) {\n return collection == null ? 0 : collection.size();\n }\n\n /**\n * Returns the map's size or {@code 0} if the map is {@code null}.\n *\n * @param map the map to check\n * @return the map's size or {@code 0} if the map is {@code null}.\n * @since 0.9.2\n */\n public static int size(Map map) {\n return map == null ? 0 : map.size();\n }\n\n /**\n * Return true if the supplied Map is null\n * or empty. Otherwise, return false.\n * @param map the Map to check\n * @return whether the given Map is empty\n */\n public static boolean isEmpty(Map map) {\n return (map == null || map.isEmpty());\n }\n\n /**\n * Convert the supplied array into a List. A primitive array gets\n * converted into a List of the appropriate wrapper type.\n *

      A null source value will be converted to an\n * empty List.\n * @param source the (potentially primitive) array\n * @return the converted List result\n * @see Objects#toObjectArray(Object)\n */\n public static List arrayToList(Object source) {\n return Arrays.asList(Objects.toObjectArray(source));\n }\n\n /**\n * Merge the given array into the given Collection.\n * @param array the array to merge (may be null)\n * @param collection the target Collection to merge the array into\n */\n @SuppressWarnings(\"unchecked\")\n public static void mergeArrayIntoCollection(Object array, Collection collection) {\n if (collection == null) {\n throw new IllegalArgumentException(\"Collection must not be null\");\n }\n Object[] arr = Objects.toObjectArray(array);\n for (Object elem : arr) {\n collection.add(elem);\n }\n }\n\n /**\n * Merge the given Properties instance into the given Map,\n * copying all properties (key-value pairs) over.\n *

      Uses Properties.propertyNames() to even catch\n * default properties linked into the original Properties instance.\n * @param props the Properties instance to merge (may be null)\n * @param map the target Map to merge the properties into\n */\n @SuppressWarnings(\"unchecked\")\n public static void mergePropertiesIntoMap(Properties props, Map map) {\n if (map == null) {\n throw new IllegalArgumentException(\"Map must not be null\");\n }\n if (props != null) {\n for (Enumeration en = props.propertyNames(); en.hasMoreElements();) {\n String key = (String) en.nextElement();\n Object value = props.getProperty(key);\n if (value == null) {\n // Potentially a non-String value...\n value = props.get(key);\n }\n map.put(key, value);\n }\n }\n }\n\n\n /**\n * Check whether the given Iterator contains the given element.\n * @param iterator the Iterator to check\n * @param element the element to look for\n * @return true if found, false else\n */\n public static boolean contains(Iterator iterator, Object element) {\n if (iterator != null) {\n while (iterator.hasNext()) {\n Object candidate = iterator.next();\n if (Objects.nullSafeEquals(candidate, element)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Check whether the given Enumeration contains the given element.\n * @param enumeration the Enumeration to check\n * @param element the element to look for\n * @return true if found, false else\n */\n public static boolean contains(Enumeration enumeration, Object element) {\n if (enumeration != null) {\n while (enumeration.hasMoreElements()) {\n Object candidate = enumeration.nextElement();\n if (Objects.nullSafeEquals(candidate, element)) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Check whether the given Collection contains the given element instance.\n *

      Enforces the given instance to be present, rather than returning\n * true for an equal element as well.\n * @param collection the Collection to check\n * @param element the element to look for\n * @return true if found, false else\n */\n public static boolean containsInstance(Collection collection, Object element) {\n if (collection != null) {\n for (Object candidate : collection) {\n if (candidate == element) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Return true if any element in 'candidates' is\n * contained in 'source'; otherwise returns false.\n * @param source the source Collection\n * @param candidates the candidates to search for\n * @return whether any of the candidates has been found\n */\n public static boolean containsAny(Collection source, Collection candidates) {\n if (isEmpty(source) || isEmpty(candidates)) {\n return false;\n }\n for (Object candidate : candidates) {\n if (source.contains(candidate)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Return the first element in 'candidates' that is contained in\n * 'source'. If no element in 'candidates' is present in\n * 'source' returns null. Iteration order is\n * {@link Collection} implementation specific.\n * @param source the source Collection\n * @param candidates the candidates to search for\n * @return the first present object, or null if not found\n */\n public static Object findFirstMatch(Collection source, Collection candidates) {\n if (isEmpty(source) || isEmpty(candidates)) {\n return null;\n }\n for (Object candidate : candidates) {\n if (source.contains(candidate)) {\n return candidate;\n }\n }\n return null;\n }\n\n /**\n * Find a single value of the given type in the given Collection.\n * @param collection the Collection to search\n * @param type the type to look for\n * @param the generic type parameter for {@code type}\n * @return a value of the given type found if there is a clear match,\n * or null if none or more than one such value found\n */\n @SuppressWarnings(\"unchecked\")\n public static T findValueOfType(Collection collection, Class type) {\n if (isEmpty(collection)) {\n return null;\n }\n T value = null;\n for (Object element : collection) {\n if (type == null || type.isInstance(element)) {\n if (value != null) {\n // More than one value found... no clear single value.\n return null;\n }\n value = (T) element;\n }\n }\n return value;\n }\n\n /**\n * Find a single value of one of the given types in the given Collection:\n * searching the Collection for a value of the first type, then\n * searching for a value of the second type, etc.\n * @param collection the collection to search\n * @param types the types to look for, in prioritized order\n * @return a value of one of the given types found if there is a clear match,\n * or null if none or more than one such value found\n */\n public static Object findValueOfType(Collection collection, Class[] types) {\n if (isEmpty(collection) || Objects.isEmpty(types)) {\n return null;\n }\n for (Class type : types) {\n Object value = findValueOfType(collection, type);\n if (value != null) {\n return value;\n }\n }\n return null;\n }\n\n /**\n * Determine whether the given Collection only contains a single unique object.\n * @param collection the Collection to check\n * @return true if the collection contains a single reference or\n * multiple references to the same instance, false else\n */\n public static boolean hasUniqueObject(Collection collection) {\n if (isEmpty(collection)) {\n return false;\n }\n boolean hasCandidate = false;\n Object candidate = null;\n for (Object elem : collection) {\n if (!hasCandidate) {\n hasCandidate = true;\n candidate = elem;\n }\n else if (candidate != elem) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Find the common element type of the given Collection, if any.\n * @param collection the Collection to check\n * @return the common element type, or null if no clear\n * common type has been found (or the collection was empty)\n */\n public static Class findCommonElementType(Collection collection) {\n if (isEmpty(collection)) {\n return null;\n }\n Class candidate = null;\n for (Object val : collection) {\n if (val != null) {\n if (candidate == null) {\n candidate = val.getClass();\n }\n else if (candidate != val.getClass()) {\n return null;\n }\n }\n }\n return candidate;\n }\n\n /**\n * Marshal the elements from the given enumeration into an array of the given type.\n * Enumeration elements must be assignable to the type of the given array. The array\n * returned will be a different instance than the array given.\n * @param enumeration the collection to convert to an array\n * @param array an array instance that matches the type of array to return\n * @param the element type of the array that will be created\n * @param the element type contained within the enumeration.\n * @return a new array of type {@code A} that contains the elements in the specified {@code enumeration}.\n */\n public static A[] toArray(Enumeration enumeration, A[] array) {\n ArrayList elements = new ArrayList();\n while (enumeration.hasMoreElements()) {\n elements.add(enumeration.nextElement());\n }\n return elements.toArray(array);\n }\n\n /**\n * Adapt an enumeration to an iterator.\n * @param enumeration the enumeration\n * @param the type of elements in the enumeration\n * @return the iterator\n */\n public static Iterator toIterator(Enumeration enumeration) {\n return new EnumerationIterator(enumeration);\n }\n\n /**\n * Iterator wrapping an Enumeration.\n */\n private static class EnumerationIterator implements Iterator {\n\n private Enumeration enumeration;\n\n public EnumerationIterator(Enumeration enumeration) {\n this.enumeration = enumeration;\n }\n\n public boolean hasNext() {\n return this.enumeration.hasMoreElements();\n }\n\n public E next() {\n return this.enumeration.nextElement();\n }\n\n public void remove() throws UnsupportedOperationException {\n throw new UnsupportedOperationException(\"Not supported\");\n }\n }\n}\n\n", "file_name": "Collections.java", "human_label": "Check whether the element exists in the collection. ", "level": "slib_runnable", "lineno": "165", "name": "containsInstance", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636766fa1a6d9265ec01779d", "all_context": "{ \"class_level\" : \"String CHAR_STRING;\\nString[] CHAR_STRING_ARRAY;\\nCharacter[] CHAR_ARRAY;\\nchar LF;\\nchar CR;\\nCharUtils();\\ntoCharacterObject(String str);\\ntoChar(Character ch);\\ntoChar(Character ch,char defaultValue);\\ntoChar(String str);\\ntoChar(String str,char defaultValue);\\ntoIntValue(char ch);\\ntoIntValue(char ch,int defaultValue);\\ntoIntValue(Character ch);\\ntoIntValue(Character ch,int defaultValue);\\ntoString(char ch);\\ntoString(Character ch);\\nunicodeEscaped(char ch);\\nunicodeEscaped(Character ch);\\nisAscii(char ch);\\nisAsciiPrintable(char ch);\\nisAsciiControl(char ch);\\nisAsciiAlpha(char ch);\\nisAsciiAlphaUpper(char ch);\\nisAsciiAlphaLower(char ch);\\nisAsciiNumeric(char ch);\\nisAsciiAlphanumeric(char ch);\\nisHighSurrogate(char ch);\\nisCharType(Class targetType);\\ntoCharacterObject(char ch);\\n\", \"repo_level\" : \"\" }", "class_name": "CharUtils", "code": "public static boolean isAsciiControl(final char ch){\n return ch < 32 || ch == 127;\n}\n", "docstring": "/** \n *

      Checks whether the character is ASCII 7 bit control.

       CharUtils.isAsciiControl('a')  = false CharUtils.isAsciiControl('A')  = false CharUtils.isAsciiControl('3')  = false CharUtils.isAsciiControl('-')  = false CharUtils.isAsciiControl('\\n') = true CharUtils.isAsciiControl('©') = false 
      \n * @param ch the character to check\n * @return true if less than 32 or equals 127\n */\n", "end_lineno": "459", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\n/**\n *

      Operations on char primitives and Character objects.

      \n *\n *

      This class tries to handle null input gracefully.\n * An exception will not be thrown for a null input.\n * Each method documents its behaviour in more detail.

      \n *\n *

      #ThreadSafe#

      \n * @author Apache Software Foundation\n * @since 2.1\n * @version $Id: CharUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class CharUtils {\n private static final String CHAR_STRING = //\n \"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\" +//\n \"\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\" + //\n \"\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\" + //\n \"\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\" +//\n \"\\u0020\\u0021\\\"\\u0023\\u0024\\u0025\\u0026\\u0027\" + //\n \"\\u0028\\u0029\\u002a\\u002b\\u002c\\u002d\\u002e\\u002f\" + //\n \"\\u0030\\u0031\\u0032\\u0033\\u0034\\u0035\\u0036\\u0037\" + //\n \"\\u0038\\u0039\\u003a\\u003b\\u003c\\u003d\\u003e\\u003f\" + //\n \"\\u0040\\u0041\\u0042\\u0043\\u0044\\u0045\\u0046\\u0047\" + //\n \"\\u0048\\u0049\\u004a\\u004b\\u004c\\u004d\\u004e\\u004f\" + //\n \"\\u0050\\u0051\\u0052\\u0053\\u0054\\u0055\\u0056\\u0057\" +//\n \"\\u0058\\u0059\\u005a\\u005b\\\\\\u005d\\u005e\\u005f\" + //\n \"\\u0060\\u0061\\u0062\\u0063\\u0064\\u0065\\u0066\\u0067\" +//\n \"\\u0068\\u0069\\u006a\\u006b\\u006c\\u006d\\u006e\\u006f\" +//\n \"\\u0070\\u0071\\u0072\\u0073\\u0074\\u0075\\u0076\\u0077\" +//\n \"\\u0078\\u0079\\u007a\\u007b\\u007c\\u007d\\u007e\\u007f\";\n private static final String[] CHAR_STRING_ARRAY = new String[128];\n private static final Character[] CHAR_ARRAY = new Character[128];\n /**\n * \n linefeed LF ('\\n').\n *\n * @see
      JLF: Escape Sequences\n * for Character and String Literals\n * @since 2.2\n */\n public static final char LF = '\\n';\n /**\n * carriage return CR ('\\r').\n *\n * @see JLF: Escape Sequences\n * for Character and String Literals\n * @since 2.2\n */\n public static final char CR = '\\r';\n\n static {\n for (int i = 127; i >= 0; i--) {\n CharUtils.CHAR_STRING_ARRAY[i] = CharUtils.CHAR_STRING.substring(i, i + 1);\n CharUtils.CHAR_ARRAY[i] = new Character((char) i);\n }\n }\n\n /**\n *

      CharUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as CharUtils.toString('c');.

      \n *\n *

      This constructor i public to permit tools that require a JavaBean instance\n * to operate.

      \n */\n public CharUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the character to a Character.

      \n *\n *

      For ASCII 7 bit characters, this uses a cache that will return the\n * same Character object each time.

      \n *\n *
      \n     *   CharUtils.toCharacterObject(' ')  = ' '\n     *   CharUtils.toCharacterObject('A')  = 'A'\n     * 
      \n *\n * @param ch the character to convert\n * @return a Character of the specified character\n */\n public static Character toCharacterObject(final char ch) {\n if (ch < CharUtils.CHAR_ARRAY.length) {\n return CharUtils.CHAR_ARRAY[ch];\n }\n return new Character(ch);\n }\n\n /**\n *

      Converts the String to a Character using the first character, returning\n * null for empty Strings.

      \n *\n *

      For ASCII 7 bit characters, this uses a cache that will return the\n * same Character object each time.

      \n *\n *
      \n     *   CharUtils.toCharacterObject(null) = null\n     *   CharUtils.toCharacterObject(\"\")   = null\n     *   CharUtils.toCharacterObject(\"A\")  = 'A'\n     *   CharUtils.toCharacterObject(\"BA\") = 'B'\n     * 
      \n *\n * @param str the character to convert\n * @return the Character value of the first letter of the String\n */\n public static Character toCharacterObject(final String str) {\n if (StringUtils.isEmpty(str)) {\n return null;\n }\n return CharUtils.toCharacterObject(str.charAt(0));\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the Character to a char throwing an exception for null.

      \n *\n *
      \n     *   CharUtils.toChar(null) = IllegalArgumentException\n     *   CharUtils.toChar(' ')  = ' '\n     *   CharUtils.toChar('A')  = 'A'\n     * 
      \n *\n * @param ch the character to convert\n * @return the char value of the Character\n * @throws IllegalArgumentException if the Character is null\n */\n public static char toChar(final Character ch) {\n if (ch == null) {\n throw new IllegalArgumentException(\"The Character must not be null\");\n }\n return ch.charValue();\n }\n\n /**\n *

      Converts the Character to a char handling null.

      \n *\n *
      \n     *   CharUtils.toChar(null, 'X') = 'X'\n     *   CharUtils.toChar(' ', 'X')  = ' '\n     *   CharUtils.toChar('A', 'X')  = 'A'\n     * 
      \n *\n * @param ch the character to convert\n * @param defaultValue the value to use if the Character is null\n * @return the char value of the Character or the default if null\n */\n public static char toChar(final Character ch, final char defaultValue) {\n if (ch == null) {\n return defaultValue;\n }\n return ch.charValue();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the String to a char using the first character, throwing\n * an exception on empty Strings.

      \n *\n *
      \n     *   CharUtils.toChar(null) = IllegalArgumentException\n     *   CharUtils.toChar(\"\")   = IllegalArgumentException\n     *   CharUtils.toChar(\"A\")  = 'A'\n     *   CharUtils.toChar(\"BA\") = 'B'\n     * 
      \n *\n * @param str the character to convert\n * @return the char value of the first letter of the String\n * @throws IllegalArgumentException if the String is empty\n */\n public static char toChar(final String str) {\n if (StringUtils.isEmpty(str)) {\n throw new IllegalArgumentException(\"The String must not be empty\");\n }\n return str.charAt(0);\n }\n\n /**\n *

      Converts the String to a char using the first character, defaulting\n * the value on empty Strings.

      \n *\n *
      \n     *   CharUtils.toChar(null, 'X') = 'X'\n     *   CharUtils.toChar(\"\", 'X')   = 'X'\n     *   CharUtils.toChar(\"A\", 'X')  = 'A'\n     *   CharUtils.toChar(\"BA\", 'X') = 'B'\n     * 
      \n *\n * @param str the character to convert\n * @param defaultValue the value to use if the Character is null\n * @return the char value of the first letter of the String or the default if null\n */\n public static char toChar(final String str, final char defaultValue) {\n if (StringUtils.isEmpty(str)) {\n return defaultValue;\n }\n return str.charAt(0);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

      \n *\n *

      This method coverts the char '1' to the int 1 and so on.

      \n *\n *
      \n     *   CharUtils.toIntValue('3')  = 3\n     *   CharUtils.toIntValue('A')  = IllegalArgumentException\n     * 
      \n *\n * @param ch the character to convert\n * @return the int value of the character\n * @throws IllegalArgumentException if the character is not ASCII numeric\n */\n public static int toIntValue(final char ch) {\n if (CharUtils.isAsciiNumeric(ch) == false) {\n throw new IllegalArgumentException(\"The character \" + ch + \" is not in the range '0' - '9'\");\n }\n return ch - 48;\n }\n\n /**\n *

      Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

      \n *\n *

      This method coverts the char '1' to the int 1 and so on.

      \n *\n *
      \n     *   CharUtils.toIntValue('3', -1)  = 3\n     *   CharUtils.toIntValue('A', -1)  = -1\n     * 
      \n *\n * @param ch the character to convert\n * @param defaultValue the default value to use if the character is not numeric\n * @return the int value of the character\n */\n public static int toIntValue(final char ch, final int defaultValue) {\n if (CharUtils.isAsciiNumeric(ch) == false) {\n return defaultValue;\n }\n return ch - 48;\n }\n\n /**\n *

      Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

      \n *\n *

      This method coverts the char '1' to the int 1 and so on.

      \n *\n *
      \n     *   CharUtils.toIntValue(null) = IllegalArgumentException\n     *   CharUtils.toIntValue('3')  = 3\n     *   CharUtils.toIntValue('A')  = IllegalArgumentException\n     * 
      \n *\n * @param ch the character to convert, not null\n * @return the int value of the character\n * @throws IllegalArgumentException if the Character is not ASCII numeric or is null\n */\n public static int toIntValue(final Character ch) {\n if (ch == null) {\n throw new IllegalArgumentException(\"The character must not be null\");\n }\n return CharUtils.toIntValue(ch.charValue());\n }\n\n /**\n *

      Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

      \n *\n *

      This method coverts the char '1' to the int 1 and so on.

      \n *\n *
      \n     *   CharUtils.toIntValue(null, -1) = -1\n     *   CharUtils.toIntValue('3', -1)  = 3\n     *   CharUtils.toIntValue('A', -1)  = -1\n     * 
      \n *\n * @param ch the character to convert\n * @param defaultValue the default value to use if the character is not numeric\n * @return the int value of the character\n */\n public static int toIntValue(final Character ch, final int defaultValue) {\n if (ch == null) {\n return defaultValue;\n }\n return CharUtils.toIntValue(ch.charValue(), defaultValue);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the character to a String that contains the one character.

      \n *\n *

      For ASCII 7 bit characters, this uses a cache that will return the\n * same String object each time.

      \n *\n *
      \n     *   CharUtils.toString(' ')  = \" \"\n     *   CharUtils.toString('A')  = \"A\"\n     * 
      \n *\n * @param ch the character to convert\n * @return a String containing the one specified character\n */\n public static String toString(final char ch) {\n if (ch < 128) {\n return CharUtils.CHAR_STRING_ARRAY[ch];\n }\n return new String(new char[] { ch });\n }\n\n /**\n *

      Converts the character to a String that contains the one character.

      \n *\n *

      For ASCII 7 bit characters, this uses a cache that will return the\n * same String object each time.

      \n *\n *

      If null is passed in, null will be returned.

      \n *\n *
      \n     *   CharUtils.toString(null) = null\n     *   CharUtils.toString(' ')  = \" \"\n     *   CharUtils.toString('A')  = \"A\"\n     * 
      \n *\n * @param ch the character to convert\n * @return a String containing the one specified character\n */\n public static String toString(final Character ch) {\n if (ch == null) {\n return null;\n }\n return CharUtils.toString(ch.charValue());\n }\n //--------------------------------------------------------------------------\n\n /**\n *

      Converts the string to the unicode format '\\u0020'.

      \n *\n *

      This format is the Java source code format.

      \n *\n *
      \n     *   CharUtils.unicodeEscaped(' ') = \"\\u0020\"\n     *   CharUtils.unicodeEscaped('A') = \"\\u0041\"\n     * 
      \n *\n * @param ch the character to convert\n * @return the escaped unicode string\n */\n public static String unicodeEscaped(final char ch) {\n if (ch < 0x10) {\n return \"\\\\u000\" + Integer.toHexString(ch);\n } else if (ch < 0x100) {\n return \"\\\\u00\" + Integer.toHexString(ch);\n } else if (ch < 0x1000) {\n return \"\\\\u0\" + Integer.toHexString(ch);\n }\n return \"\\\\u\" + Integer.toHexString(ch);\n }\n\n /**\n *

      Converts the string to the unicode format '\\u0020'.

      \n *\n *

      This format is the Java source code format.

      \n *\n *

      If null is passed in, null will be returned.

      \n *\n *
      \n     *   CharUtils.unicodeEscaped(null) = null\n     *   CharUtils.unicodeEscaped(' ')  = \"\\u0020\"\n     *   CharUtils.unicodeEscaped('A')  = \"\\u0041\"\n     * 
      \n *\n * @param ch the character to convert, may be null\n * @return the escaped unicode string, null if null input\n */\n public static String unicodeEscaped(final Character ch) {\n if (ch == null) {\n return null;\n }\n return CharUtils.unicodeEscaped(ch.charValue());\n }\n //--------------------------------------------------------------------------\n\n /**\n *

      Checks whether the character is ASCII 7 bit.

      \n *\n *
      \n     *   CharUtils.isAscii('a')  = true\n     *   CharUtils.isAscii('A')  = true\n     *   CharUtils.isAscii('3')  = true\n     *   CharUtils.isAscii('-')  = true\n     *   CharUtils.isAscii('\\n') = true\n     *   CharUtils.isAscii('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if less than 128\n */\n public static boolean isAscii(final char ch) {\n return ch < 128;\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit printable.

      \n *\n *
      \n     *   CharUtils.isAsciiPrintable('a')  = true\n     *   CharUtils.isAsciiPrintable('A')  = true\n     *   CharUtils.isAsciiPrintable('3')  = true\n     *   CharUtils.isAsciiPrintable('-')  = true\n     *   CharUtils.isAsciiPrintable('\\n') = false\n     *   CharUtils.isAsciiPrintable('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 32 and 126 inclusive\n */\n public static boolean isAsciiPrintable(final char ch) {\n return ch >= 32 && ch < 127;\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit control.

      \n *\n *
      \n     *   CharUtils.isAsciiControl('a')  = false\n     *   CharUtils.isAsciiControl('A')  = false\n     *   CharUtils.isAsciiControl('3')  = false\n     *   CharUtils.isAsciiControl('-')  = false\n     *   CharUtils.isAsciiControl('\\n') = true\n     *   CharUtils.isAsciiControl('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if less than 32 or equals 127\n */\n public static boolean isAsciiControl(final char ch) {\n return ch < 32 || ch == 127;\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit alphabetic.

      \n *\n *
      \n     *   CharUtils.isAsciiAlpha('a')  = true\n     *   CharUtils.isAsciiAlpha('A')  = true\n     *   CharUtils.isAsciiAlpha('3')  = false\n     *   CharUtils.isAsciiAlpha('-')  = false\n     *   CharUtils.isAsciiAlpha('\\n') = false\n     *   CharUtils.isAsciiAlpha('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 65 and 90 or 97 and 122 inclusive\n */\n public static boolean isAsciiAlpha(final char ch) {\n return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z';\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit alphabetic upper case.

      \n *\n *
      \n     *   CharUtils.isAsciiAlphaUpper('a')  = false\n     *   CharUtils.isAsciiAlphaUpper('A')  = true\n     *   CharUtils.isAsciiAlphaUpper('3')  = false\n     *   CharUtils.isAsciiAlphaUpper('-')  = false\n     *   CharUtils.isAsciiAlphaUpper('\\n') = false\n     *   CharUtils.isAsciiAlphaUpper('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 65 and 90 inclusive\n */\n public static boolean isAsciiAlphaUpper(final char ch) {\n return ch >= 'A' && ch <= 'Z';\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit alphabetic lower case.

      \n *\n *
      \n     *   CharUtils.isAsciiAlphaLower('a')  = true\n     *   CharUtils.isAsciiAlphaLower('A')  = false\n     *   CharUtils.isAsciiAlphaLower('3')  = false\n     *   CharUtils.isAsciiAlphaLower('-')  = false\n     *   CharUtils.isAsciiAlphaLower('\\n') = false\n     *   CharUtils.isAsciiAlphaLower('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 97 and 122 inclusive\n */\n public static boolean isAsciiAlphaLower(final char ch) {\n return ch >= 'a' && ch <= 'z';\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit numeric.

      \n *\n *
      \n     *   CharUtils.isAsciiNumeric('a')  = false\n     *   CharUtils.isAsciiNumeric('A')  = false\n     *   CharUtils.isAsciiNumeric('3')  = true\n     *   CharUtils.isAsciiNumeric('-')  = false\n     *   CharUtils.isAsciiNumeric('\\n') = false\n     *   CharUtils.isAsciiNumeric('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 48 and 57 inclusive\n */\n public static boolean isAsciiNumeric(final char ch) {\n return ch >= '0' && ch <= '9';\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit numeric.

      \n *\n *
      \n     *   CharUtils.isAsciiAlphanumeric('a')  = true\n     *   CharUtils.isAsciiAlphanumeric('A')  = true\n     *   CharUtils.isAsciiAlphanumeric('3')  = true\n     *   CharUtils.isAsciiAlphanumeric('-')  = false\n     *   CharUtils.isAsciiAlphanumeric('\\n') = false\n     *   CharUtils.isAsciiAlphanumeric('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive\n */\n public static boolean isAsciiAlphanumeric(final char ch) {\n return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9';\n }\n // ----------------- Following code copied from Apache Harmony (Character class)\n\n /**\n * Indicates whether {@code ch} is a high- (or leading-) surrogate code unit\n * that is used for representing supplementary characters in UTF-16\n * encoding.\n *\n * @param ch\n * the character to test.\n * @return {@code true} if {@code ch} is a high-surrogate code unit;\n * {@code false} otherwise.\n */\n static boolean isHighSurrogate(final char ch) {\n return '\\uD800' <= ch && '\\uDBFF' >= ch;\n }\n\n //\n public static boolean isCharType(Class targetType) {\n return targetType.equals(Character.class) || targetType.equals(Character.TYPE);\n }\n}\n", "file_name": "CharUtils.java", "human_label": "Check whether the character is ASCII 7 bit control.", "level": "self_contained", "lineno": "442", "name": "isAsciiControl", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "6367670b1a6d9265ec0179f2", "all_context": "{ \"class_level\" : \"import java.util.*;\\nMap map;\\nboolean fast;\\nMap expected;\\nMap.Entry lastReturned;\\nIterator iterator;\\nWeakFastHashMap();\\nWeakFastHashMap(int capacity);\\nWeakFastHashMap(int capacity,float factor);\\nWeakFastHashMap(Map map);\\ngetFast();\\nsetFast(boolean fast);\\nget(Object key);\\nisEmpty();\\ncontainsKey(Object key);\\ncontainsValue(Object value);\\nput(Object key,Object value);\\nputAll(Map in);\\nremove(Object key);\\nclear();\\nequals(Object o);\\nhashCode();\\nclone();\\nentrySet();\\nkeySet();\\nvalues();\\ncreateMap();\\ncreateMap(int capacity);\\ncreateMap(int capacity,float factor);\\ncreateMap(Map map);\\ncloneMap(Map map);\\nCollectionView();\\nget(Map map);\\niteratorNext(Entry entry);\\nremove(Object o);\\nremoveAll(Collection o);\\nretainAll(Collection o);\\ncontains(Object o);\\ncontainsAll(Collection o);\\ntoArray(Object[] o);\\ntoArray();\\nadd(Object o);\\naddAll(Collection c);\\niterator();\\nCollectionViewIterator();\\nhasNext();\\nnext();\\nremove();\\nsize();\\n\", \"repo_level\" : \"\" }", "class_name": "WeakFastHashMap", "code": "@Override public boolean containsKey(final Object key){\n if (this.fast) {\n return this.map.containsKey(key);\n }\n else {\nsynchronized (this.map) {\n return this.map.containsKey(key);\n }\n }\n}\n", "docstring": "/** \n * Return true if this map contains a mapping for the specified key.\n * @param key the key to be searched for\n * @return true if the map contains the key\n */\n", "end_lineno": "193", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.convert;\nimport java.util.*;\n\n/**\n *

      A customized implementation of java.util.HashMap designed\n * to operate in a multithreaded environment where the large majority of\n * method calls are read-only, instead of structural changes. When operating\n * in \"fast\" mode, read calls are non-synchronized and write calls perform the\n * following steps:

      \n *
        \n *
      • Clone the existing collection\n *
      • Perform the modification on the clone\n *
      • Replace the existing collection with the (modified) clone\n *
      \n *

      When first created, objects of this class default to \"slow\" mode, where\n * all accesses of any type are synchronized but no cloning takes place. This\n * is appropriate for initially populating the collection, followed by a switch\n * to \"fast\" mode (by calling setFast(true)) after initialization\n * is complete.

      \n *\n *

      NOTE: If you are creating and accessing a\n * HashMap only within a single thread, you should use\n * java.util.HashMap directly (with no synchronization), for\n * maximum performance.

      \n *\n *

      NOTE: This class is not cross-platform. \n * Using it may cause unexpected failures on some architectures.\n * It suffers from the same problems as the double-checked locking idiom. \n * In particular, the instruction that clones the internal collection and the \n * instruction that sets the internal reference to the clone can be executed \n * or perceived out-of-order. This means that any read operation might fail \n * unexpectedly, as it may be reading the state of the internal collection\n * before the internal collection is fully formed.\n * For more information on the double-checked locking idiom, see the\n * \n * Double-Checked Locking Idiom Is Broken Declaration.

      \n *\n * @since Commons Collections 1.0\n * @version $Revision: 687089 $ $Date: 2008-08-19 17:33:30 +0100 (Tue, 19 Aug 2008) $\n *\n * @author Craig R. McClanahan\n * @author Stephen Colebourne\n */\n@SuppressWarnings({ \"rawtypes\", \"serial\", \"unchecked\" })\nclass WeakFastHashMap extends HashMap {\n /** The underlying map we are managing. */\n private Map map = null;\n /** Are we currently operating in \"fast\" mode? */\n private boolean fast = false;\n // Constructors\n // ----------------------------------------------------------------------\n\n /** Construct an empty map. */\n public WeakFastHashMap() {\n super();\n this.map = this.createMap();\n }\n\n /**\n * Construct an empty map with the specified capacity.\n * @param capacity the initial capacity of the empty map\n */\n public WeakFastHashMap(final int capacity) {\n super();\n this.map = this.createMap(capacity);\n }\n\n /**\n * Construct an empty map with the specified capacity and load factor.\n * @param capacity the initial capacity of the empty map\n * @param factor the load factor of the new map\n */\n public WeakFastHashMap(final int capacity, final float factor) {\n super();\n this.map = this.createMap(capacity, factor);\n }\n\n /**\n * Construct a new map with the same mappings as the specified map.\n * @param map the map whose mappings are to be copied\n */\n public WeakFastHashMap(final Map map) {\n super();\n this.map = this.createMap(map);\n }\n // Property access\n // ----------------------------------------------------------------------\n\n /**\n * Returns true if this map is operating in fast mode.\n * @return true if this map is operating in fast mode\n */\n public boolean getFast() {\n return this.fast;\n }\n\n /**\n * Sets whether this map is operating in fast mode.\n * @param fast true if this map should operate in fast mode\n */\n public void setFast(final boolean fast) {\n this.fast = fast;\n }\n // Map access\n // ----------------------------------------------------------------------\n // These methods can forward straight to the wrapped Map in 'fast' mode.\n // (because they are query methods)\n\n /**\n * Return the value to which this map maps the specified key. Returns\n * null if the map contains no mapping for this key, or if\n * there is a mapping with a value of null. Use the\n * containsKey() method to disambiguate these cases.\n *\n * @param key the key whose value is to be returned\n * @return the value mapped to that key, or null\n */\n @Override\n public Object get(final Object key) {\n if (this.fast) {\n return this.map.get(key);\n } else {\n synchronized (this.map) {\n return this.map.get(key);\n }\n }\n }\n\n /**\n * Return the number of key-value mappings in this map.\n *\n * @return the current size of the map\n */\n @Override\n public int size() {\n if (this.fast) {\n return this.map.size();\n } else {\n synchronized (this.map) {\n return this.map.size();\n }\n }\n }\n\n /**\n * Return true if this map contains no mappings.\n *\n * @return is the map currently empty\n */\n @Override\n public boolean isEmpty() {\n if (this.fast) {\n return this.map.isEmpty();\n } else {\n synchronized (this.map) {\n return this.map.isEmpty();\n }\n }\n }\n\n /**\n * Return true if this map contains a mapping for the\n * specified key.\n *\n * @param key the key to be searched for\n * @return true if the map contains the key\n */\n @Override\n public boolean containsKey(final Object key) {\n if (this.fast) {\n return this.map.containsKey(key);\n } else {\n synchronized (this.map) {\n return this.map.containsKey(key);\n }\n }\n }\n\n /**\n * Return true if this map contains one or more keys mapping\n * to the specified value.\n *\n * @param value the value to be searched for\n * @return true if the map contains the value\n */\n @Override\n public boolean containsValue(final Object value) {\n if (this.fast) {\n return this.map.containsValue(value);\n } else {\n synchronized (this.map) {\n return this.map.containsValue(value);\n }\n }\n }\n // Map modification\n // ----------------------------------------------------------------------\n // These methods perform special behaviour in 'fast' mode.\n // The map is cloned, updated and then assigned back.\n // See the comments at the top as to why this won't always work.\n\n /**\n * Associate the specified value with the specified key in this map.\n * If the map previously contained a mapping for this key, the old\n * value is replaced and returned.\n *\n * @param key the key with which the value is to be associated\n * @param value the value to be associated with this key\n * @return the value previously mapped to the key, or null\n */\n @Override\n public Object put(final Object key, final Object value) {\n if (this.fast) {\n synchronized (this) {\n Map temp = this.cloneMap(this.map);\n Object result = temp.put(key, value);\n this.map = temp;\n return result;\n }\n } else {\n synchronized (this.map) {\n return this.map.put(key, value);\n }\n }\n }\n\n /**\n * Copy all of the mappings from the specified map to this one, replacing\n * any mappings with the same keys.\n *\n * @param in the map whose mappings are to be copied\n */\n @Override\n public void putAll(final Map in) {\n if (this.fast) {\n synchronized (this) {\n Map temp = this.cloneMap(this.map);\n temp.putAll(in);\n this.map = temp;\n }\n } else {\n synchronized (this.map) {\n this.map.putAll(in);\n }\n }\n }\n\n /**\n * Remove any mapping for this key, and return any previously\n * mapped value.\n *\n * @param key the key whose mapping is to be removed\n * @return the value removed, or null\n */\n @Override\n public Object remove(final Object key) {\n if (this.fast) {\n synchronized (this) {\n Map temp = this.cloneMap(this.map);\n Object result = temp.remove(key);\n this.map = temp;\n return result;\n }\n } else {\n synchronized (this.map) {\n return this.map.remove(key);\n }\n }\n }\n\n /**\n * Remove all mappings from this map.\n */\n @Override\n public void clear() {\n if (this.fast) {\n synchronized (this) {\n this.map = this.createMap();\n }\n } else {\n synchronized (this.map) {\n this.map.clear();\n }\n }\n }\n // Basic object methods\n // ----------------------------------------------------------------------\n\n /**\n * Compare the specified object with this list for equality. This\n * implementation uses exactly the code that is used to define the\n * list equals function in the documentation for the\n * Map.equals method.\n *\n * @param o the object to be compared to this list\n * @return true if the two maps are equal\n */\n @Override\n public boolean equals(final Object o) {\n // Simple tests that require no synchronization\n if (o == this) {\n return true;\n } else if (!(o instanceof Map)) {\n return false;\n }\n Map mo = (Map) o;\n // Compare the two maps for equality\n if (this.fast) {\n if (mo.size() != this.map.size()) {\n return false;\n }\n Iterator i = this.map.entrySet().iterator();\n while (i.hasNext()) {\n Map.Entry e = (Map.Entry) i.next();\n Object key = e.getKey();\n Object value = e.getValue();\n if (value == null) {\n if (!(mo.get(key) == null && mo.containsKey(key))) {\n return false;\n }\n } else {\n if (!value.equals(mo.get(key))) {\n return false;\n }\n }\n }\n return true;\n } else {\n synchronized (this.map) {\n if (mo.size() != this.map.size()) {\n return false;\n }\n Iterator i = this.map.entrySet().iterator();\n while (i.hasNext()) {\n Map.Entry e = (Map.Entry) i.next();\n Object key = e.getKey();\n Object value = e.getValue();\n if (value == null) {\n if (!(mo.get(key) == null && mo.containsKey(key))) {\n return false;\n }\n } else {\n if (!value.equals(mo.get(key))) {\n return false;\n }\n }\n }\n return true;\n }\n }\n }\n\n /**\n * Return the hash code value for this map. This implementation uses\n * exactly the code that is used to define the list hash function in the\n * documentation for the Map.hashCode method.\n *\n * @return suitable integer hash code\n */\n @Override\n public int hashCode() {\n if (this.fast) {\n int h = 0;\n Iterator i = this.map.entrySet().iterator();\n while (i.hasNext()) {\n h += i.next().hashCode();\n }\n return h;\n } else {\n synchronized (this.map) {\n int h = 0;\n Iterator i = this.map.entrySet().iterator();\n while (i.hasNext()) {\n h += i.next().hashCode();\n }\n return h;\n }\n }\n }\n\n /**\n * Return a shallow copy of this FastHashMap instance.\n * The keys and values themselves are not copied.\n *\n * @return a clone of this map\n */\n @Override\n public Object clone() {\n WeakFastHashMap results = null;\n if (this.fast) {\n results = new WeakFastHashMap(this.map);\n } else {\n synchronized (this.map) {\n results = new WeakFastHashMap(this.map);\n }\n }\n results.setFast(this.getFast());\n return results;\n }\n // Map views\n // ----------------------------------------------------------------------\n\n /**\n * Return a collection view of the mappings contained in this map. Each\n * element in the returned collection is a Map.Entry.\n * @return the set of map Map entries\n */\n @Override\n public Set entrySet() {\n return new EntrySet();\n }\n\n /**\n * Return a set view of the keys contained in this map.\n * @return the set of the Map's keys\n */\n @Override\n public Set keySet() {\n return new KeySet();\n }\n\n /**\n * Return a collection view of the values contained in this map.\n * @return the set of the Map's values\n */\n @Override\n public Collection values() {\n return new Values();\n }\n\n // Abstractions on Map creations (for subclasses such as WeakFastHashMap)\n // ----------------------------------------------------------------------\n protected Map createMap() {\n return new WeakHashMap();\n }\n\n protected Map createMap(final int capacity) {\n return new WeakHashMap(capacity);\n }\n\n protected Map createMap(final int capacity, final float factor) {\n return new WeakHashMap(capacity, factor);\n }\n\n protected Map createMap(final Map map) {\n return new WeakHashMap(map);\n }\n\n protected Map cloneMap(final Map map) {\n return this.createMap(map);\n }\n // Map view inner classes\n // ----------------------------------------------------------------------\n\n /**\n * Abstract collection implementation shared by keySet(), values() and entrySet().\n */\n private abstract class CollectionView implements Collection {\n public CollectionView() {\n }\n\n protected abstract Collection get(Map map);\n\n protected abstract Object iteratorNext(Map.Entry entry);\n\n @Override\n public void clear() {\n if (WeakFastHashMap.this.fast) {\n synchronized (WeakFastHashMap.this) {\n WeakFastHashMap.this.map = WeakFastHashMap.this.createMap();\n }\n } else {\n synchronized (WeakFastHashMap.this.map) {\n this.get(WeakFastHashMap.this.map).clear();\n }\n }\n }\n\n @Override\n public boolean remove(final Object o) {\n if (WeakFastHashMap.this.fast) {\n synchronized (WeakFastHashMap.this) {\n Map temp = WeakFastHashMap.this.cloneMap(WeakFastHashMap.this.map);\n boolean r = this.get(temp).remove(o);\n WeakFastHashMap.this.map = temp;\n return r;\n }\n } else {\n synchronized (WeakFastHashMap.this.map) {\n return this.get(WeakFastHashMap.this.map).remove(o);\n }\n }\n }\n\n @Override\n public boolean removeAll(final Collection o) {\n if (WeakFastHashMap.this.fast) {\n synchronized (WeakFastHashMap.this) {\n Map temp = WeakFastHashMap.this.cloneMap(WeakFastHashMap.this.map);\n boolean r = this.get(temp).removeAll(o);\n WeakFastHashMap.this.map = temp;\n return r;\n }\n } else {\n synchronized (WeakFastHashMap.this.map) {\n return this.get(WeakFastHashMap.this.map).removeAll(o);\n }\n }\n }\n\n @Override\n public boolean retainAll(final Collection o) {\n if (WeakFastHashMap.this.fast) {\n synchronized (WeakFastHashMap.this) {\n Map temp = WeakFastHashMap.this.cloneMap(WeakFastHashMap.this.map);\n boolean r = this.get(temp).retainAll(o);\n WeakFastHashMap.this.map = temp;\n return r;\n }\n } else {\n synchronized (WeakFastHashMap.this.map) {\n return this.get(WeakFastHashMap.this.map).retainAll(o);\n }\n }\n }\n\n @Override\n public int size() {\n if (WeakFastHashMap.this.fast) {\n return this.get(WeakFastHashMap.this.map).size();\n } else {\n synchronized (WeakFastHashMap.this.map) {\n return this.get(WeakFastHashMap.this.map).size();\n }\n }\n }\n\n @Override\n public boolean isEmpty() {\n if (WeakFastHashMap.this.fast) {\n return this.get(WeakFastHashMap.this.map).isEmpty();\n } else {\n synchronized (WeakFastHashMap.this.map) {\n return this.get(WeakFastHashMap.this.map).isEmpty();\n }\n }\n }\n\n @Override\n public boolean contains(final Object o) {\n if (WeakFastHashMap.this.fast) {\n return this.get(WeakFastHashMap.this.map).contains(o);\n } else {\n synchronized (WeakFastHashMap.this.map) {\n return this.get(WeakFastHashMap.this.map).contains(o);\n }\n }\n }\n\n @Override\n public boolean containsAll(final Collection o) {\n if (WeakFastHashMap.this.fast) {\n return this.get(WeakFastHashMap.this.map).containsAll(o);\n } else {\n synchronized (WeakFastHashMap.this.map) {\n return this.get(WeakFastHashMap.this.map).containsAll(o);\n }\n }\n }\n\n @Override\n public Object[] toArray(final Object[] o) {\n if (WeakFastHashMap.this.fast) {\n return this.get(WeakFastHashMap.this.map).toArray(o);\n } else {\n synchronized (WeakFastHashMap.this.map) {\n return this.get(WeakFastHashMap.this.map).toArray(o);\n }\n }\n }\n\n @Override\n public Object[] toArray() {\n if (WeakFastHashMap.this.fast) {\n return this.get(WeakFastHashMap.this.map).toArray();\n } else {\n synchronized (WeakFastHashMap.this.map) {\n return this.get(WeakFastHashMap.this.map).toArray();\n }\n }\n }\n\n @Override\n public boolean equals(final Object o) {\n if (o.equals(this)) {\n return true;\n }\n if (WeakFastHashMap.this.fast) {\n return this.get(WeakFastHashMap.this.map).equals(o);\n } else {\n synchronized (WeakFastHashMap.this.map) {\n return this.get(WeakFastHashMap.this.map).equals(o);\n }\n }\n }\n\n @Override\n public int hashCode() {\n if (WeakFastHashMap.this.fast) {\n return this.get(WeakFastHashMap.this.map).hashCode();\n } else {\n synchronized (WeakFastHashMap.this.map) {\n return this.get(WeakFastHashMap.this.map).hashCode();\n }\n }\n }\n\n @Override\n public boolean add(final Object o) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean addAll(final Collection c) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public Iterator iterator() {\n return new CollectionViewIterator();\n }\n\n private class CollectionViewIterator implements Iterator {\n private Map expected;\n private Map.Entry lastReturned = null;\n private Iterator iterator;\n\n public CollectionViewIterator() {\n this.expected = WeakFastHashMap.this.map;\n this.iterator = this.expected.entrySet().iterator();\n }\n\n @Override\n public boolean hasNext() {\n if (this.expected != WeakFastHashMap.this.map) {\n throw new ConcurrentModificationException();\n }\n return this.iterator.hasNext();\n }\n\n @Override\n public Object next() {\n if (this.expected != WeakFastHashMap.this.map) {\n throw new ConcurrentModificationException();\n }\n this.lastReturned = (Map.Entry) this.iterator.next();\n return CollectionView.this.iteratorNext(this.lastReturned);\n }\n\n @Override\n public void remove() {\n if (this.lastReturned == null) {\n throw new IllegalStateException();\n }\n if (WeakFastHashMap.this.fast) {\n synchronized (WeakFastHashMap.this) {\n if (this.expected != WeakFastHashMap.this.map) {\n throw new ConcurrentModificationException();\n }\n WeakFastHashMap.this.remove(this.lastReturned.getKey());\n this.lastReturned = null;\n this.expected = WeakFastHashMap.this.map;\n }\n } else {\n this.iterator.remove();\n this.lastReturned = null;\n }\n }\n }\n }\n\n /**\n * Set implementation over the keys of the FastHashMap\n */\n private class KeySet extends CollectionView implements Set {\n @Override\n protected Collection get(final Map map) {\n return map.keySet();\n }\n\n @Override\n protected Object iteratorNext(final Map.Entry entry) {\n return entry.getKey();\n }\n }\n\n /**\n * Collection implementation over the values of the FastHashMap\n */\n private class Values extends CollectionView {\n @Override\n protected Collection get(final Map map) {\n return map.values();\n }\n\n @Override\n protected Object iteratorNext(final Map.Entry entry) {\n return entry.getValue();\n }\n }\n\n /**\n * Set implementation over the entries of the FastHashMap\n */\n private class EntrySet extends CollectionView implements Set {\n @Override\n protected Collection get(final Map map) {\n return map.entrySet();\n }\n\n @Override\n protected Object iteratorNext(final Map.Entry entry) {\n return entry;\n }\n }\n}", "file_name": "WeakFastHashMap.java", "human_label": "Check whether a map contains a mapping for the specified key.", "level": "class_runnable", "lineno": "177", "name": "containsKey", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[fast, map]\" }", "package": "net.hasor.utils.convert", "project": "hasor-master" }, { "_id": "636766fa1a6d9265ec017796", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static Boolean[] toObject(final boolean[] array){\n if (array == null) {\n return null;\n }\n else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result=new Boolean[array.length];\n for (int i=0; i < array.length; i++) {\n result[i]=array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n}\n", "docstring": "/** \n *

      Converts an array of primitive booleans to objects.

      This method returns null for a null input array.

      \n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n", "end_lineno": "3052", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

      Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

      \n *\n *

      This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

      \n *\n *

      #ThreadSafe#

      \n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

      ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

      \n *\n *

      This constructor is public to permit tools that require a JavaBean instance\n * to operate.

      \n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

      \n *\n *

      This method can be used to initialize:

      \n *
      \n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

      Shallow clones an array returning a typecast result and handling\n * null.

      \n *\n *

      The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

      Produces a new array containing the elements between\n * the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n *

      The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

      \n *\n *
      \n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new long array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new int array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new short array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new char array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new byte array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new double array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new float array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new boolean array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

      Any multi-dimensional aspects of the arrays are ignored.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

      \n *\n *

      If the input array is null, 0 is returned.

      \n *\n *
      \n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
      \n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

      Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

      \n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      There is no special handling for multi-dimensional arrays.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given object in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

      Finds the index of the given object in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given object within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given object in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the object is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

      \n *\n *

      The method returns false if a null array\n * is passed in.

      \n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Characters to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Character to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive chars to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Longs to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Long to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive longs to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Integers to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Integer to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive ints to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Shorts to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Short to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive shorts to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Bytes to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Bytes to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive bytes to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Doubles to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Doubles to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive doubles to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Floats to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Floats to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive floats to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Booleans to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Booleans to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive booleans to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

      Checks if an array of Objects is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive longs is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive ints is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive shorts is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive chars is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive bytes is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive doubles is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive floats is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive booleans is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

      Checks if an array of Objects is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive longs is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive ints is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive shorts is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive chars is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive bytes is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive doubles is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive floats is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive booleans is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

      \n *\n *
      \n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
      \n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Convert an array of primitive booleans to objects.", "level": "class_runnable", "lineno": "3033", "name": "toObject", "oracle_context": "{ \"apis\" : \"[ArrayUtils]\", \"classes\" : \"[Boolean[], ArrayUtils, Boolean]\", \"vars\" : \"[length, EMPTY_BOOLEAN_OBJECT_ARRAY, TRUE, FALSE]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636767aa1a6d9265ec01864a", "all_context": "{ \"class_level\" : \"import static io.protostuff.StringSerializer.STRING;\\nimport java.io.DataOutput;\\nimport java.io.IOException;\\nimport java.io.OutputStream;\\nimport java.io.UnsupportedEncodingException;\\nimport java.nio.ByteBuffer;\\nbyte[] bytes;\\nString EMPTY_STRING;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByteString EMPTY;\\nint hash;\\nwrap(byte[] bytes);\\ngetBytes();\\nwriteTo(DataOutput out,ByteString bs);\\nwriteTo(Output output,ByteString bs,int fieldNumber,boolean repeated);\\ntoString();\\nByteString(byte[] bytes);\\nbyteAt(int index);\\nsize();\\nisEmpty();\\ncopyFrom(byte[] bytes,int offset,int size);\\ncopyFrom(byte[] bytes);\\ncopyFrom(String text,String charsetName);\\ncopyFromUtf8(String text);\\ncopyTo(byte[] target,int offset);\\ncopyTo(byte[] target,int sourceOffset,int targetOffset,int size);\\ntoByteArray();\\nasReadOnlyByteBuffer();\\ntoStringUtf8();\\nequals(Object o);\\nequals(ByteString bs,ByteString other,boolean checkHash);\\nequals(byte[] data);\\nequals(byte[] data,int offset,int len);\\nhashCode();\\nstringDefaultValue(String bytes);\\nbytesDefaultValue(String bytes);\\nbyteArrayDefaultValue(String bytes);\\nwriteTo(OutputStream out,ByteString bs);\\n\", \"repo_level\" : \"\" }", "class_name": "ByteString", "code": "public byte[] toByteArray(){\n final int size=bytes.length;\n final byte[] copy=new byte[size];\n System.arraycopy(bytes,0,copy,0,size);\n return copy;\n}\n", "docstring": "/** \n * Copies bytes to a {@code byte[]}.\n */\n", "end_lineno": "253", "file_content": "//========================================================================\n//Copyright 2007-2009 David Yu dyuproject@gmail.com\n//------------------------------------------------------------------------\n//Licensed under the Apache License, Version 2.0 (the \"License\");\n//you may not use this file except in compliance with the License.\n//You may obtain a copy of the License at \n//http://www.apache.org/licenses/LICENSE-2.0\n//Unless required by applicable law or agreed to in writing, software\n//distributed under the License is distributed on an \"AS IS\" BASIS,\n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//See the License for the specific language governing permissions and\n//limitations under the License.\n//========================================================================\n\n// Protocol Buffers - Google's data interchange format\n// Copyright 2008 Google Inc. All rights reserved.\n// http://code.google.com/p/protobuf/\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\npackage io.protostuff;\n\nimport static io.protostuff.StringSerializer.STRING;\n\nimport java.io.DataOutput;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.nio.ByteBuffer;\n\n/**\n * Immutable array of bytes.\n * \n * @author crazybob@google.com Bob Lee\n * @author kenton@google.com Kenton Varda\n * @author David Yu\n */\npublic final class ByteString\n{\n // START EXTRA\n // internal package access to avoid double memory allocation\n static ByteString wrap(byte[] bytes)\n {\n return new ByteString(bytes);\n }\n\n // internal package access to avoid double memory allocation\n byte[] getBytes()\n {\n return bytes;\n }\n\n /**\n * Writes the bytes to the {@link OutputStream}.\n */\n public static void writeTo(OutputStream out, ByteString bs) throws IOException\n {\n out.write(bs.bytes);\n }\n\n /**\n * Writes the bytes to the {@link DataOutput}.\n */\n public static void writeTo(DataOutput out, ByteString bs) throws IOException\n {\n out.write(bs.bytes);\n }\n\n /**\n * Writes the bytes to the {@link Output}.\n */\n public static void writeTo(Output output, ByteString bs, int fieldNumber,\n boolean repeated) throws IOException\n {\n output.writeByteArray(fieldNumber, bs.bytes, repeated);\n }\n\n @Override\n public String toString()\n {\n return String.format(\"\",\n Integer.toHexString(System.identityHashCode(this)), size());\n }\n\n // END EXTRA\n private final byte[] bytes;\n\n private ByteString(final byte[] bytes)\n {\n this.bytes = bytes;\n }\n\n /**\n * Gets the byte at the given index.\n * \n * @throws ArrayIndexOutOfBoundsException\n * {@code index} is < 0 or >= size\n */\n public byte byteAt(final int index)\n {\n return bytes[index];\n }\n\n /**\n * Gets the number of bytes.\n */\n public int size()\n {\n return bytes.length;\n }\n\n /**\n * Returns {@code true} if the size is {@code 0}, {@code false} otherwise.\n */\n public boolean isEmpty()\n {\n return bytes.length == 0;\n }\n\n // =================================================================\n // byte[] -> ByteString\n\n /**\n * Empty String.\n */\n public static final String EMPTY_STRING = \"\";\n\n /**\n * Empty byte array.\n */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n\n /**\n * Empty ByteString.\n */\n public static final ByteString EMPTY = new ByteString(EMPTY_BYTE_ARRAY);\n\n /**\n * Copies the given bytes into a {@code ByteString}.\n */\n public static ByteString copyFrom(final byte[] bytes, final int offset,\n final int size)\n {\n final byte[] copy = new byte[size];\n System.arraycopy(bytes, offset, copy, 0, size);\n return new ByteString(copy);\n }\n\n /**\n * Copies the given bytes into a {@code ByteString}.\n */\n public static ByteString copyFrom(final byte[] bytes)\n {\n return copyFrom(bytes, 0, bytes.length);\n }\n\n /**\n * Encodes {@code text} into a sequence of bytes using the named charset and returns the result as a\n * {@code ByteString}.\n */\n public static ByteString copyFrom(final String text, final String charsetName)\n {\n try\n {\n return new ByteString(text.getBytes(charsetName));\n }\n catch (UnsupportedEncodingException e)\n {\n throw new RuntimeException(charsetName + \" not supported?\", e);\n }\n }\n\n /**\n * Encodes {@code text} into a sequence of UTF-8 bytes and returns the result as a {@code ByteString}.\n */\n public static ByteString copyFromUtf8(final String text)\n {\n return new ByteString(STRING.ser(text));\n /*\n * @try { return new ByteString(text.getBytes(\"UTF-8\")); } catch (UnsupportedEncodingException e) { throw new\n * RuntimeException(\"UTF-8 not supported?\", e); }\n */\n }\n\n // =================================================================\n // ByteString -> byte[]\n\n /**\n * Copies bytes into a buffer at the given offset.\n * \n * @param target\n * buffer to copy into\n * @param offset\n * in the target buffer\n */\n public void copyTo(final byte[] target, final int offset)\n {\n System.arraycopy(bytes, 0, target, offset, bytes.length);\n }\n\n /**\n * Copies bytes into a buffer.\n * \n * @param target\n * buffer to copy into\n * @param sourceOffset\n * offset within these bytes\n * @param targetOffset\n * offset within the target buffer\n * @param size\n * number of bytes to copy\n */\n public void copyTo(final byte[] target, final int sourceOffset,\n final int targetOffset,\n final int size)\n {\n System.arraycopy(bytes, sourceOffset, target, targetOffset, size);\n }\n\n /**\n * Copies bytes to a {@code byte[]}.\n */\n public byte[] toByteArray()\n {\n final int size = bytes.length;\n final byte[] copy = new byte[size];\n System.arraycopy(bytes, 0, copy, 0, size);\n return copy;\n }\n\n /**\n * Constructs a new read-only {@code java.nio.ByteBuffer} with the same backing byte array.\n */\n public ByteBuffer asReadOnlyByteBuffer()\n {\n final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);\n return byteBuffer.asReadOnlyBuffer();\n }\n\n /*\n * @ Constructs a new {@code String} by decoding the bytes using the specified charset.\n */\n /*\n * @public String unsignedIntToString(final String charsetName) throws UnsupportedEncodingException { return new String(bytes,\n * charsetName); }\n */\n\n /**\n * Constructs a new {@code String} by decoding the bytes as UTF-8.\n */\n public String toStringUtf8()\n {\n return STRING.deser(bytes);\n /*\n * @try { return new String(bytes, \"UTF-8\"); } catch (UnsupportedEncodingException e) { throw new\n * RuntimeException(\"UTF-8 not supported?\", e); }\n */\n }\n\n // =================================================================\n // equals() and hashCode()\n\n @Override\n public boolean equals(final Object o)\n {\n return o == this || (o instanceof ByteString && equals(this, (ByteString) o, false));\n }\n\n /**\n * Returns true if the contents of both match.\n */\n public static boolean equals(ByteString bs, ByteString other, boolean checkHash)\n {\n final int size = bs.bytes.length;\n if (size != other.bytes.length)\n {\n return false;\n }\n\n if (checkHash)\n {\n // volatile reads\n final int h1 = bs.hash, h2 = other.hash;\n if (h1 != 0 && h2 != 0 && h1 != h2)\n {\n return false;\n }\n }\n\n final byte[] thisBytes = bs.bytes;\n final byte[] otherBytes = other.bytes;\n for (int i = 0; i < size; i++)\n {\n if (thisBytes[i] != otherBytes[i])\n {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Returns true if the contents of the internal array and the provided array match.\n */\n public boolean equals(final byte[] data)\n {\n return equals(data, 0, data.length);\n }\n\n /**\n * Returns true if the contents of the internal array and the provided array match.\n */\n public boolean equals(final byte[] data, int offset, final int len)\n {\n final byte[] bytes = this.bytes;\n if (len != bytes.length)\n return false;\n\n for (int i = 0; i < len;)\n {\n if (bytes[i++] != data[offset++])\n {\n return false;\n }\n }\n\n return true;\n }\n\n private volatile int hash = 0;\n\n @Override\n public int hashCode()\n {\n int h = hash;\n\n if (h == 0)\n {\n final byte[] thisBytes = bytes;\n final int size = bytes.length;\n\n h = size;\n for (int i = 0; i < size; i++)\n {\n h = h * 31 + thisBytes[i];\n }\n if (h == 0)\n {\n h = 1;\n }\n\n hash = h;\n }\n\n return h;\n }\n\n // =================================================================\n // Input stream\n\n /*\n * @ Creates an {@code InputStream} which can be used to read the bytes.\n */\n /*\n * @public InputStream newInput() { return new ByteArrayInputStream(bytes); }\n */\n\n /*\n * @ Creates a {@link CodedInputStream} which can be used to read the bytes. Using this is more efficient than\n * creating a {@link CodedInputStream} wrapping the result of {@link #newInput()}.\n */\n /*\n * @public CodedInputStream newCodedInput() { // We trust CodedInputStream not to modify the bytes, or to give\n * anyone // else access to them. return CodedInputStream.newInstance(bytes); }\n */\n\n // =================================================================\n // Output stream\n\n /*\n * @ Creates a new {@link Output} with the given initial capacity.\n */\n /*\n * @public static Output newOutput(final int initialCapacity) { return new Output(new\n * ByteArrayOutputStream(initialCapacity)); }\n */\n\n /*\n * @ Creates a new {@link Output}.\n */\n /*\n * @public static Output newOutput() { return newOutput(32); }\n */\n\n /*\n * @ Outputs to a {@code ByteString} instance. Call {@link #toByteString()} to create the {@code ByteString}\n * instance.\n */\n /*\n * @public static final class Output extends FilterOutputStream { private final ByteArrayOutputStream bout;\n * \n * /** Constructs a new output with the given initial capacity.\n * \n * @ private Output(final ByteArrayOutputStream bout) { super(bout); this.bout = bout; }\n * \n * /** Creates a {@code ByteString} instance from this {@code Output}.\n * \n * @ public ByteString toByteString() { final byte[] byteArray = bout.toByteArray(); return new\n * ByteString(byteArray); } }\n * \n * /** Constructs a new ByteString builder, which allows you to efficiently construct a {@code ByteString} by\n * writing to a {@link CodedOutputStream}. Using this is much more efficient than calling {@code newOutput()} and\n * wrapping that in a {@code CodedOutputStream}.\n * \n *

      This is package-private because it's a somewhat confusing interface. Users can call {@link\n * Message#toByteString()} instead of calling this directly.\n * \n * @param size The target byte size of the {@code ByteString}. You must write exactly this many bytes before\n * building the result.\n * \n * @ static CodedBuilder newCodedBuilder(final int size) { return new CodedBuilder(size); }\n * \n * /** See {@link ByteString#newCodedBuilder(int)}. *@ static final class CodedBuilder { private final\n * CodedOutputStream output; private final byte[] buffer;\n * \n * private CodedBuilder(final int size) { buffer = new byte[size]; output = CodedOutputStream.newInstance(buffer); }\n * \n * public ByteString build() { output.checkNoSpaceLeft();\n * \n * // We can be confident that the CodedOutputStream will not modify the // underlying bytes anymore because it\n * already wrote all of them. So, // no need to make a copy. return new ByteString(buffer); }\n * \n * public CodedOutputStream getCodedOutput() { return output; } }\n */\n\n // moved from Internal.java\n\n /**\n * Helper called by generated code to construct default values for string fields.\n *

      \n * The protocol compiler does not actually contain a UTF-8 decoder -- it just pushes UTF-8-encoded text around\n * without touching it. The one place where this presents a problem is when generating Java string literals. Unicode\n * characters in the string literal would normally need to be encoded using a Unicode escape sequence, which would\n * require decoding them. To get around this, protoc instead embeds the UTF-8 bytes into the generated code and\n * leaves it to the runtime library to decode them.\n *

      \n * It gets worse, though. If protoc just generated a byte array, like: new byte[] {0x12, 0x34, 0x56, 0x78} Java\n * actually generates *code* which allocates an array and then fills in each value. This is much less efficient than\n * just embedding the bytes directly into the bytecode. To get around this, we need another work-around. String\n * literals are embedded directly, so protoc actually generates a string literal corresponding to the bytes. The\n * easiest way to do this is to use the ISO-8859-1 character set, which corresponds to the first 256 characters of\n * the Unicode range. Protoc can then use good old CEscape to generate the string.\n *

      \n * So we have a string literal which represents a set of bytes which represents another string. This function --\n * stringDefaultValue -- converts from the generated string to the string we actually want. The generated code calls\n * this automatically.\n */\n public static String stringDefaultValue(String bytes)\n {\n try\n {\n return new String(bytes.getBytes(\"ISO-8859-1\"), \"UTF-8\");\n }\n catch (UnsupportedEncodingException e)\n {\n // This should never happen since all JVMs are required to implement\n // both of the above character sets.\n throw new IllegalStateException(\n \"Java VM does not support a standard character set.\", e);\n }\n }\n\n /**\n * Helper called by generated code to construct default values for bytes fields.\n *

      \n * This is a lot like {@link #stringDefaultValue}, but for bytes fields. In this case we only need the second of the\n * two hacks -- allowing us to embed raw bytes as a string literal with ISO-8859-1 encoding.\n */\n public static ByteString bytesDefaultValue(String bytes)\n {\n return new ByteString(byteArrayDefaultValue(bytes));\n }\n\n /**\n * Helper called by generated code to construct default values for byte array fields.\n *

      \n * This is a lot like {@link #stringDefaultValue}, but for bytes fields. In this case we only need the second of the\n * two hacks -- allowing us to embed raw bytes as a string literal with ISO-8859-1 encoding.\n */\n public static byte[] byteArrayDefaultValue(String bytes)\n {\n try\n {\n return bytes.getBytes(\"ISO-8859-1\");\n }\n catch (UnsupportedEncodingException e)\n {\n // This should never happen since all JVMs are required to implement\n // ISO-8859-1.\n throw new IllegalStateException(\n \"Java VM does not support a standard character set.\", e);\n }\n }\n}\n", "file_name": "ByteString.java", "human_label": "Copy bytes to a byte array.", "level": "self_contained", "lineno": "244", "name": "toByteArray", "oracle_context": "{ \"apis\" : \"[arraycopy]\", \"classes\" : \"[byte[], bytes]\", \"vars\" : \"[length, bytes]\" }", "package": "io.protostuff", "project": "protostuff-master" }, { "_id": "636767561a6d9265ec017f7c", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.alg.interfaces.*;\\nimport org.jgrapht.graph.*;\\nimport org.jgrapht.traverse.*;\\nimport java.util.*;\\nclosedVertexListToTour(List tour,Graph graph);\\nedgeSetToTour(Set tour,Graph graph);\\ngetSingletonTour(Graph graph);\\ncheckGraph(Graph graph);\\nrequireNotEmpty(Graph graph);\\nvertexListToTour(List tour,Graph graph);\\n\", \"repo_level\" : \"\" }", "class_name": "HamiltonianCycleAlgorithmBase", "code": "protected GraphPath edgeSetToTour(Set tour,Graph graph){\n List vertices=new ArrayList<>(tour.size() + 1);\n MaskSubgraph tourGraph=new MaskSubgraph<>(graph,v -> false,e -> !tour.contains(e));\n new DepthFirstIterator<>(tourGraph).forEachRemaining(vertices::add);\n return vertexListToTour(vertices,graph);\n}\n", "docstring": "/** \n * Transform from a Set representation to a graph path.\n * @param tour a set containing the edges of the tour\n * @param graph the graph\n * @return a graph path\n */\n", "end_lineno": "98", "file_content": "/*\n * (C) Copyright 2019-2021, by Peter Harman and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.tour;\n\nimport org.jgrapht.*;\nimport org.jgrapht.alg.interfaces.*;\nimport org.jgrapht.graph.*;\nimport org.jgrapht.traverse.*;\n\nimport java.util.*;\n\n/**\n * Base class for TSP solver algorithms.\n *\n *

      \n * This class provides implementations of utilities for TSP solver classes.\n *

      \n *\n * @param the graph vertex type\n * @param the graph edge type\n *\n * @author Peter Harman\n * @author Hannes Wellmann\n */\npublic abstract class HamiltonianCycleAlgorithmBase\n implements\n HamiltonianCycleAlgorithm\n{\n\n /**\n * Transform from a List representation to a graph path.\n *\n * @param tour a list containing the vertices of the tour (is modified)\n * @param graph the graph\n * @return a graph path\n */\n protected GraphPath vertexListToTour(List tour, Graph graph)\n {\n tour.add(tour.get(0));\n return closedVertexListToTour(tour, graph);\n }\n\n /**\n * Transform from a closed List representation (first and last vertex element are the same) to a\n * graph path.\n *\n * @param tour a closed list containing the vertices of the tour\n * @param graph the graph\n * @return a graph path\n */\n protected GraphPath closedVertexListToTour(List tour, Graph graph)\n {\n assert tour.get(0) == tour.get(tour.size() - 1);\n\n List edges = new ArrayList<>(tour.size() - 1);\n double tourWeight = 0d;\n V u = tour.get(0);\n for (V v : tour.subList(1, tour.size())) {\n E e = graph.getEdge(u, v);\n edges.add(e);\n tourWeight += graph.getEdgeWeight(e);\n u = v;\n }\n return new GraphWalk<>(graph, tour.get(0), tour.get(0), tour, edges, tourWeight);\n }\n\n /**\n * Transform from a Set representation to a graph path.\n *\n * @param tour a set containing the edges of the tour\n * @param graph the graph\n * @return a graph path\n */\n protected GraphPath edgeSetToTour(Set tour, Graph graph)\n {\n List vertices = new ArrayList<>(tour.size() + 1);\n\n MaskSubgraph tourGraph =\n new MaskSubgraph<>(graph, v -> false, e -> !tour.contains(e));\n new DepthFirstIterator<>(tourGraph).forEachRemaining(vertices::add);\n\n return vertexListToTour(vertices, graph);\n }\n\n /**\n * Creates a tour for a graph with 1 vertex\n *\n * @param graph The graph\n * @return A tour with a single vertex\n */\n protected GraphPath getSingletonTour(Graph graph)\n {\n assert graph.vertexSet().size() == 1;\n V start = graph.vertexSet().iterator().next();\n return new GraphWalk<>(\n graph, start, start, Collections.singletonList(start), Collections.emptyList(), 0d);\n }\n\n /**\n * Checks that graph is undirected, complete, and non-empty\n *\n * @param graph the graph\n * @throws IllegalArgumentException if graph is not undirected\n * @throws IllegalArgumentException if graph is not complete\n * @throws IllegalArgumentException if graph contains no vertices\n */\n protected void checkGraph(Graph graph)\n {\n GraphTests.requireUndirected(graph);\n\n requireNotEmpty(graph);\n\n if (!GraphTests.isComplete(graph)) {\n throw new IllegalArgumentException(\"Graph is not complete\");\n }\n }\n\n /**\n * Checks that graph is not empty\n *\n * @param graph the graph\n * @throws IllegalArgumentException if graph contains no vertices\n */\n protected void requireNotEmpty(Graph graph)\n {\n if (graph.vertexSet().isEmpty()) {\n throw new IllegalArgumentException(\"Graph contains no vertices\");\n }\n }\n}\n", "file_name": "HamiltonianCycleAlgorithmBase.java", "human_label": "Convert a set representation to a graph path.", "level": "class_runnable", "lineno": "82", "name": "edgeSetToTour", "oracle_context": "{ \"apis\" : \"[size, contains, forEachRemaining, vertexListToTour]\", \"classes\" : \"[List, MaskSubgraph]\", \"vars\" : \"[]\" }", "package": "org.jgrapht.alg.tour", "project": "jgrapht-master" }, { "_id": "6367670a1a6d9265ec0179f1", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static Short[] toObject(final short[] array){\n if (array == null) {\n return null;\n }\n else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result=new Short[array.length];\n for (int i=0; i < array.length; i++) {\n result[i]=new Short(array[i]);\n }\n return result;\n}\n", "docstring": "/** \n *

      Converts an array of primitive shorts to objects.

      This method returns null for a null input array.

      \n * @param array a short array\n * @return a Short array, null if null array input\n */\n", "end_lineno": "2780", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

      Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

      \n *\n *

      This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

      \n *\n *

      #ThreadSafe#

      \n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

      ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

      \n *\n *

      This constructor is public to permit tools that require a JavaBean instance\n * to operate.

      \n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

      \n *\n *

      This method can be used to initialize:

      \n *
      \n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

      Shallow clones an array returning a typecast result and handling\n * null.

      \n *\n *

      The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

      Produces a new array containing the elements between\n * the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n *

      The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

      \n *\n *
      \n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new long array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new int array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new short array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new char array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new byte array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new double array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new float array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new boolean array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

      Any multi-dimensional aspects of the arrays are ignored.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

      \n *\n *

      If the input array is null, 0 is returned.

      \n *\n *
      \n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
      \n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

      Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

      \n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      There is no special handling for multi-dimensional arrays.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given object in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

      Finds the index of the given object in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given object within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given object in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the object is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

      \n *\n *

      The method returns false if a null array\n * is passed in.

      \n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Characters to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Character to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive chars to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Longs to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Long to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive longs to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Integers to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Integer to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive ints to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Shorts to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Short to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive shorts to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Bytes to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Bytes to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive bytes to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Doubles to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Doubles to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive doubles to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Floats to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Floats to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive floats to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Booleans to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Booleans to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive booleans to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

      Checks if an array of Objects is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive longs is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive ints is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive shorts is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive chars is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive bytes is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive doubles is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive floats is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive booleans is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

      Checks if an array of Objects is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive longs is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive ints is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive shorts is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive chars is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive bytes is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive doubles is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive floats is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive booleans is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

      \n *\n *
      \n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
      \n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Convert an array of primitive shorts to objects.", "level": "class_runnable", "lineno": "2761", "name": "toObject", "oracle_context": "{ \"apis\" : \"[ArrayUtils]\", \"classes\" : \"[Short[], ArrayUtils]\", \"vars\" : \"[length, EMPTY_SHORT_OBJECT_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636766fe1a6d9265ec017823", "all_context": "{ \"class_level\" : \"ClassWriter classWriter;\\nClassReader sourceClassReader;\\nint majorVersion;\\nString className;\\nint entryCount;\\nEntry[] entries;\\nint constantPoolCount;\\nByteVector constantPool;\\nint bootstrapMethodCount;\\nByteVector bootstrapMethods;\\nint typeCount;\\nEntry[] typeTable;\\nint hashCode;\\nEntry next;\\nSymbolTable(ClassWriter classWriter);\\nSymbolTable(ClassWriter classWriter,ClassReader classReader);\\ngetSource();\\ngetMajorVersion();\\ngetClassName();\\nsetMajorVersionAndClassName(int majorVersion,String className);\\ngetConstantPoolCount();\\ngetConstantPoolLength();\\nputConstantPool(ByteVector output);\\ncomputeBootstrapMethodsSize();\\nputBootstrapMethods(ByteVector output);\\nget(int hashCode);\\nput(Entry entry);\\nadd(Entry entry);\\naddConstant(Object value);\\naddConstantClass(String value);\\naddConstantFieldref(String owner,String name,String descriptor);\\naddConstantMethodref(String owner,String name,String descriptor,boolean isInterface);\\naddConstantMemberReference(int tag,String owner,String name,String descriptor);\\naddConstantMemberReference(int index,int tag,String owner,String name,String descriptor);\\naddConstantString(String value);\\naddConstantInteger(int value);\\naddConstantFloat(float value);\\naddConstantIntegerOrFloat(int tag,int value);\\naddConstantIntegerOrFloat(int index,int tag,int value);\\naddConstantLong(long value);\\naddConstantDouble(double value);\\naddConstantLongOrDouble(int tag,long value);\\naddConstantLongOrDouble(int index,int tag,long value);\\naddConstantNameAndType(String name,String descriptor);\\naddConstantNameAndType(int index,String name,String descriptor);\\naddConstantUtf8(String value);\\naddConstantUtf8(int index,String value);\\naddConstantMethodHandle(int referenceKind,String owner,String name,String descriptor,boolean isInterface);\\naddConstantMethodHandle(int index,int referenceKind,String owner,String name,String descriptor);\\naddConstantMethodType(String methodDescriptor);\\naddConstantDynamic(String name,String descriptor,Handle bootstrapMethodHandle,Object bootstrapMethodArguments);\\naddConstantInvokeDynamic(String name,String descriptor,Handle bootstrapMethodHandle,Object bootstrapMethodArguments);\\naddConstantDynamicOrInvokeDynamicReference(int tag,String name,String descriptor,int bootstrapMethodIndex);\\naddConstantDynamicOrInvokeDynamicReference(int tag,int index,String name,String descriptor,int bootstrapMethodIndex);\\naddConstantModule(String moduleName);\\naddConstantPackage(String packageName);\\naddConstantUtf8Reference(int tag,String value);\\naddConstantUtf8Reference(int index,int tag,String value);\\naddBootstrapMethod(Handle bootstrapMethodHandle,Object bootstrapMethodArguments);\\naddBootstrapMethod(int offset,int length,int hashCode);\\ngetType(int typeIndex);\\naddType(String value);\\naddUninitializedType(String value,int bytecodeOffset);\\naddMergedType(int typeTableIndex1,int typeTableIndex2);\\naddTypeInternal(Entry entry);\\nhash(int tag,int value);\\nhash(int tag,long value);\\nhash(int tag,String value);\\nhash(int tag,String value1,int value2);\\nhash(int tag,String value1,String value2);\\nhash(int tag,String value1,String value2,int value3);\\nhash(int tag,String value1,String value2,String value3);\\nhash(int tag,String value1,String value2,String value3,int value4);\\nEntry(int index,int tag,String owner,String name,String value,long data,int hashCode);\\nEntry(int index,int tag,String value,int hashCode);\\nEntry(int index,int tag,String value,long data,int hashCode);\\nEntry(int index,int tag,String name,String value,int hashCode);\\nEntry(int index,int tag,long data,int hashCode);\\ncopyBootstrapMethods(ClassReader classReader,char[] charBuffer);\\n\", \"repo_level\" : \"\" }", "class_name": "SymbolTable", "code": "int addConstantNameAndType(final String name,final String descriptor){\n final int tag=Symbol.CONSTANT_NAME_AND_TYPE_TAG;\n int hashCode=hash(tag,name,descriptor);\n Entry entry=get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.name.equals(name) && entry.value.equals(descriptor)) {\n return entry.index;\n }\n entry=entry.next;\n }\n constantPool.put122(tag,addConstantUtf8(name),addConstantUtf8(descriptor));\n return put(new Entry(constantPoolCount++,tag,name,descriptor,hashCode)).index;\n}\n", "docstring": "/** \n * Adds a CONSTANT_NameAndType_info to the constant pool of this symbol table. Does nothing if the constant pool already contains a similar item.\n * @param name a field or method name.\n * @param descriptor a field or method descriptor.\n * @return a new or already existing Symbol with the given value.\n */\n", "end_lineno": "669", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage net.hasor.utils.asm;\n/**\n * The constant pool entries, the BootstrapMethods attribute entries and the (ASM specific) type\n * table entries of a class.\n *\n * @see JVMS 4.4\n * @see JVMS 4.7.23\n * @author Eric Bruneton\n */\nfinal class SymbolTable {\n /**\n * The ClassWriter to which this SymbolTable belongs. This is only used to get access to {@link\n * ClassWriter#getCommonSuperClass} and to serialize custom attributes with {@link\n * Attribute#write}.\n */\n final ClassWriter classWriter;\n /**\n * The ClassReader from which this SymbolTable was constructed, or {@literal null} if it was\n * constructed from scratch.\n */\n private final ClassReader sourceClassReader;\n /** The major version number of the class to which this symbol table belongs. */\n private int majorVersion;\n /** The internal name of the class to which this symbol table belongs. */\n private String className;\n /**\n * The total number of {@link Entry} instances in {@link #entries}. This includes entries that are\n * accessible (recursively) via {@link Entry#next}.\n */\n private int entryCount;\n /**\n * A hash set of all the entries in this SymbolTable (this includes the constant pool entries, the\n * bootstrap method entries and the type table entries). Each {@link Entry} instance is stored at\n * the array index given by its hash code modulo the array size. If several entries must be stored\n * at the same array index, they are linked together via their {@link Entry#next} field. The\n * factory methods of this class make sure that this table does not contain duplicated entries.\n */\n private Entry[] entries;\n /**\n * The number of constant pool items in {@link #constantPool}, plus 1. The first constant pool\n * item has index 1, and long and double items count for two items.\n */\n private int constantPoolCount;\n /**\n * The content of the ClassFile's constant_pool JVMS structure corresponding to this SymbolTable.\n * The ClassFile's constant_pool_count field is not included.\n */\n private ByteVector constantPool;\n /**\n * The number of bootstrap methods in {@link #bootstrapMethods}. Corresponds to the\n * BootstrapMethods_attribute's num_bootstrap_methods field value.\n */\n private int bootstrapMethodCount;\n /**\n * The content of the BootstrapMethods attribute 'bootstrap_methods' array corresponding to this\n * SymbolTable. Note that the first 6 bytes of the BootstrapMethods_attribute, and its\n * num_bootstrap_methods field, are not included.\n */\n private ByteVector bootstrapMethods;\n /**\n * The actual number of elements in {@link #typeTable}. These elements are stored from index 0 to\n * typeCount (excluded). The other array entries are empty.\n */\n private int typeCount;\n /**\n * An ASM specific type table used to temporarily store internal names that will not necessarily\n * be stored in the constant pool. This type table is used by the control flow and data flow\n * analysis algorithm used to compute stack map frames from scratch. This array stores {@link\n * Symbol#TYPE_TAG} and {@link Symbol#UNINITIALIZED_TYPE_TAG}) Symbol. The type symbol at index\n * {@code i} has its {@link Symbol#index} equal to {@code i} (and vice versa).\n */\n private Entry[] typeTable;\n\n /**\n * Constructs a new, empty SymbolTable for the given ClassWriter.\n *\n * @param classWriter a ClassWriter.\n */\n SymbolTable(final ClassWriter classWriter) {\n this.classWriter = classWriter;\n this.sourceClassReader = null;\n this.entries = new Entry[256];\n this.constantPoolCount = 1;\n this.constantPool = new ByteVector();\n }\n\n /**\n * Constructs a new SymbolTable for the given ClassWriter, initialized with the constant pool and\n * bootstrap methods of the given ClassReader.\n *\n * @param classWriter a ClassWriter.\n * @param classReader the ClassReader whose constant pool and bootstrap methods must be copied to\n * initialize the SymbolTable.\n */\n SymbolTable(final ClassWriter classWriter, final ClassReader classReader) {\n this.classWriter = classWriter;\n this.sourceClassReader = classReader;\n // Copy the constant pool binary content.\n byte[] inputBytes = classReader.classFileBuffer;\n int constantPoolOffset = classReader.getItem(1) - 1;\n int constantPoolLength = classReader.header - constantPoolOffset;\n constantPoolCount = classReader.getItemCount();\n constantPool = new ByteVector(constantPoolLength);\n constantPool.putByteArray(inputBytes, constantPoolOffset, constantPoolLength);\n // Add the constant pool items in the symbol table entries. Reserve enough space in 'entries' to\n // avoid too many hash set collisions (entries is not dynamically resized by the addConstant*\n // method calls below), and to account for bootstrap method entries.\n entries = new Entry[constantPoolCount * 2];\n char[] charBuffer = new char[classReader.getMaxStringLength()];\n boolean hasBootstrapMethods = false;\n int itemIndex = 1;\n while (itemIndex < constantPoolCount) {\n int itemOffset = classReader.getItem(itemIndex);\n int itemTag = inputBytes[itemOffset - 1];\n int nameAndTypeItemOffset;\n switch (itemTag) {\n case Symbol.CONSTANT_FIELDREF_TAG:\n case Symbol.CONSTANT_METHODREF_TAG:\n case Symbol.CONSTANT_INTERFACE_METHODREF_TAG:\n nameAndTypeItemOffset = classReader.getItem(classReader.readUnsignedShort(itemOffset + 2));\n addConstantMemberReference(itemIndex, itemTag, classReader.readClass(itemOffset, charBuffer), classReader.readUTF8(nameAndTypeItemOffset, charBuffer), classReader.readUTF8(nameAndTypeItemOffset + 2, charBuffer));\n break;\n case Symbol.CONSTANT_INTEGER_TAG:\n case Symbol.CONSTANT_FLOAT_TAG:\n addConstantIntegerOrFloat(itemIndex, itemTag, classReader.readInt(itemOffset));\n break;\n case Symbol.CONSTANT_NAME_AND_TYPE_TAG:\n addConstantNameAndType(itemIndex, classReader.readUTF8(itemOffset, charBuffer), classReader.readUTF8(itemOffset + 2, charBuffer));\n break;\n case Symbol.CONSTANT_LONG_TAG:\n case Symbol.CONSTANT_DOUBLE_TAG:\n addConstantLongOrDouble(itemIndex, itemTag, classReader.readLong(itemOffset));\n break;\n case Symbol.CONSTANT_UTF8_TAG:\n addConstantUtf8(itemIndex, classReader.readUtf(itemIndex, charBuffer));\n break;\n case Symbol.CONSTANT_METHOD_HANDLE_TAG:\n int memberRefItemOffset = classReader.getItem(classReader.readUnsignedShort(itemOffset + 1));\n nameAndTypeItemOffset = classReader.getItem(classReader.readUnsignedShort(memberRefItemOffset + 2));\n addConstantMethodHandle(itemIndex, classReader.readByte(itemOffset), classReader.readClass(memberRefItemOffset, charBuffer), classReader.readUTF8(nameAndTypeItemOffset, charBuffer), classReader.readUTF8(nameAndTypeItemOffset + 2, charBuffer));\n break;\n case Symbol.CONSTANT_DYNAMIC_TAG:\n case Symbol.CONSTANT_INVOKE_DYNAMIC_TAG:\n hasBootstrapMethods = true;\n nameAndTypeItemOffset = classReader.getItem(classReader.readUnsignedShort(itemOffset + 2));\n addConstantDynamicOrInvokeDynamicReference(itemTag, itemIndex, classReader.readUTF8(nameAndTypeItemOffset, charBuffer), classReader.readUTF8(nameAndTypeItemOffset + 2, charBuffer), classReader.readUnsignedShort(itemOffset));\n break;\n case Symbol.CONSTANT_STRING_TAG:\n case Symbol.CONSTANT_CLASS_TAG:\n case Symbol.CONSTANT_METHOD_TYPE_TAG:\n case Symbol.CONSTANT_MODULE_TAG:\n case Symbol.CONSTANT_PACKAGE_TAG:\n addConstantUtf8Reference(itemIndex, itemTag, classReader.readUTF8(itemOffset, charBuffer));\n break;\n default:\n throw new IllegalArgumentException();\n }\n itemIndex += (itemTag == Symbol.CONSTANT_LONG_TAG || itemTag == Symbol.CONSTANT_DOUBLE_TAG) ? 2 : 1;\n }\n // Copy the BootstrapMethods, if any.\n if (hasBootstrapMethods) {\n copyBootstrapMethods(classReader, charBuffer);\n }\n }\n\n /**\n * Read the BootstrapMethods 'bootstrap_methods' array binary content and add them as entries of\n * the SymbolTable.\n *\n * @param classReader the ClassReader whose bootstrap methods must be copied to initialize the\n * SymbolTable.\n * @param charBuffer a buffer used to read strings in the constant pool.\n */\n private void copyBootstrapMethods(final ClassReader classReader, final char[] charBuffer) {\n // Find attributOffset of the 'bootstrap_methods' array.\n byte[] inputBytes = classReader.classFileBuffer;\n int currentAttributeOffset = classReader.getFirstAttributeOffset();\n for (int i = classReader.readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) {\n String attributeName = classReader.readUTF8(currentAttributeOffset, charBuffer);\n if (Constants.BOOTSTRAP_METHODS.equals(attributeName)) {\n bootstrapMethodCount = classReader.readUnsignedShort(currentAttributeOffset + 6);\n break;\n }\n currentAttributeOffset += 6 + classReader.readInt(currentAttributeOffset + 2);\n }\n if (bootstrapMethodCount > 0) {\n // Compute the offset and the length of the BootstrapMethods 'bootstrap_methods' array.\n int bootstrapMethodsOffset = currentAttributeOffset + 8;\n int bootstrapMethodsLength = classReader.readInt(currentAttributeOffset + 2) - 2;\n bootstrapMethods = new ByteVector(bootstrapMethodsLength);\n bootstrapMethods.putByteArray(inputBytes, bootstrapMethodsOffset, bootstrapMethodsLength);\n // Add each bootstrap method in the symbol table entries.\n int currentOffset = bootstrapMethodsOffset;\n for (int i = 0; i < bootstrapMethodCount; i++) {\n int offset = currentOffset - bootstrapMethodsOffset;\n int bootstrapMethodRef = classReader.readUnsignedShort(currentOffset);\n currentOffset += 2;\n int numBootstrapArguments = classReader.readUnsignedShort(currentOffset);\n currentOffset += 2;\n int hashCode = classReader.readConst(bootstrapMethodRef, charBuffer).hashCode();\n while (numBootstrapArguments-- > 0) {\n int bootstrapArgument = classReader.readUnsignedShort(currentOffset);\n currentOffset += 2;\n hashCode ^= classReader.readConst(bootstrapArgument, charBuffer).hashCode();\n }\n add(new Entry(i, Symbol.BOOTSTRAP_METHOD_TAG, offset, hashCode & 0x7FFFFFFF));\n }\n }\n }\n\n /**\n * Returns the ClassReader from which this SymbolTable was constructed.\n *\n * @return the ClassReader from which this SymbolTable was constructed, or {@literal null} if it\n * was constructed from scratch.\n */\n ClassReader getSource() {\n return sourceClassReader;\n }\n\n /**\n * Returns the major version of the class to which this symbol table belongs.\n *\n * @return the major version of the class to which this symbol table belongs.\n */\n int getMajorVersion() {\n return majorVersion;\n }\n\n /**\n * Returns the internal name of the class to which this symbol table belongs.\n *\n * @return the internal name of the class to which this symbol table belongs.\n */\n String getClassName() {\n return className;\n }\n\n /**\n * Sets the major version and the name of the class to which this symbol table belongs. Also adds\n * the class name to the constant pool.\n *\n * @param majorVersion a major ClassFile version number.\n * @param className an internal class name.\n * @return the constant pool index of a new or already existing Symbol with the given class name.\n */\n int setMajorVersionAndClassName(final int majorVersion, final String className) {\n this.majorVersion = majorVersion;\n this.className = className;\n return addConstantClass(className).index;\n }\n\n /**\n * Returns the number of items in this symbol table's constant_pool array (plus 1).\n *\n * @return the number of items in this symbol table's constant_pool array (plus 1).\n */\n int getConstantPoolCount() {\n return constantPoolCount;\n }\n\n /**\n * Returns the length in bytes of this symbol table's constant_pool array.\n *\n * @return the length in bytes of this symbol table's constant_pool array.\n */\n int getConstantPoolLength() {\n return constantPool.length;\n }\n\n /**\n * Puts this symbol table's constant_pool array in the given ByteVector, preceded by the\n * constant_pool_count value.\n *\n * @param output where the JVMS ClassFile's constant_pool array must be put.\n */\n void putConstantPool(final ByteVector output) {\n output.putShort(constantPoolCount).putByteArray(constantPool.data, 0, constantPool.length);\n }\n\n /**\n * Returns the size in bytes of this symbol table's BootstrapMethods attribute. Also adds the\n * attribute name in the constant pool.\n *\n * @return the size in bytes of this symbol table's BootstrapMethods attribute.\n */\n int computeBootstrapMethodsSize() {\n if (bootstrapMethods != null) {\n addConstantUtf8(Constants.BOOTSTRAP_METHODS);\n return 8 + bootstrapMethods.length;\n } else {\n return 0;\n }\n }\n\n /**\n * Puts this symbol table's BootstrapMethods attribute in the given ByteVector. This includes the\n * 6 attribute header bytes and the num_bootstrap_methods value.\n *\n * @param output where the JVMS BootstrapMethods attribute must be put.\n */\n void putBootstrapMethods(final ByteVector output) {\n if (bootstrapMethods != null) {\n output.putShort(addConstantUtf8(Constants.BOOTSTRAP_METHODS)).putInt(bootstrapMethods.length + 2).putShort(bootstrapMethodCount).putByteArray(bootstrapMethods.data, 0, bootstrapMethods.length);\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Generic symbol table entries management.\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the list of entries which can potentially have the given hash code.\n *\n * @param hashCode a {@link Entry#hashCode} value.\n * @return the list of entries which can potentially have the given hash code. The list is stored\n * via the {@link Entry#next} field.\n */\n private Entry get(final int hashCode) {\n return entries[hashCode % entries.length];\n }\n\n /**\n * Puts the given entry in the {@link #entries} hash set. This method does not check\n * whether {@link #entries} already contains a similar entry or not. {@link #entries} is resized\n * if necessary to avoid hash collisions (multiple entries needing to be stored at the same {@link\n * #entries} array index) as much as possible, with reasonable memory usage.\n *\n * @param entry an Entry (which must not already be contained in {@link #entries}).\n * @return the given entry\n */\n private Entry put(final Entry entry) {\n if (entryCount > (entries.length * 3) / 4) {\n int currentCapacity = entries.length;\n int newCapacity = currentCapacity * 2 + 1;\n Entry[] newEntries = new Entry[newCapacity];\n for (int i = currentCapacity - 1; i >= 0; --i) {\n Entry currentEntry = entries[i];\n while (currentEntry != null) {\n int newCurrentEntryIndex = currentEntry.hashCode % newCapacity;\n Entry nextEntry = currentEntry.next;\n currentEntry.next = newEntries[newCurrentEntryIndex];\n newEntries[newCurrentEntryIndex] = currentEntry;\n currentEntry = nextEntry;\n }\n }\n entries = newEntries;\n }\n entryCount++;\n int index = entry.hashCode % entries.length;\n entry.next = entries[index];\n return entries[index] = entry;\n }\n\n /**\n * Adds the given entry in the {@link #entries} hash set. This method does not check\n * whether {@link #entries} already contains a similar entry or not, and does not resize\n * {@link #entries} if necessary.\n *\n * @param entry an Entry (which must not already be contained in {@link #entries}).\n */\n private void add(final Entry entry) {\n entryCount++;\n int index = entry.hashCode % entries.length;\n entry.next = entries[index];\n entries[index] = entry;\n }\n // -----------------------------------------------------------------------------------------------\n // Constant pool entries management.\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Adds a number or string constant to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value the value of the constant to be added to the constant pool. This parameter must be\n * an {@link Integer}, {@link Byte}, {@link Character}, {@link Short}, {@link Boolean}, {@link\n * Float}, {@link Long}, {@link Double}, {@link String}, {@link Type} or {@link Handle}.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstant(final Object value) {\n if (value instanceof Integer) {\n return addConstantInteger(((Integer) value).intValue());\n } else if (value instanceof Byte) {\n return addConstantInteger(((Byte) value).intValue());\n } else if (value instanceof Character) {\n return addConstantInteger(((Character) value).charValue());\n } else if (value instanceof Short) {\n return addConstantInteger(((Short) value).intValue());\n } else if (value instanceof Boolean) {\n return addConstantInteger(((Boolean) value).booleanValue() ? 1 : 0);\n } else if (value instanceof Float) {\n return addConstantFloat(((Float) value).floatValue());\n } else if (value instanceof Long) {\n return addConstantLong(((Long) value).longValue());\n } else if (value instanceof Double) {\n return addConstantDouble(((Double) value).doubleValue());\n } else if (value instanceof String) {\n return addConstantString((String) value);\n } else if (value instanceof Type) {\n Type type = (Type) value;\n int typeSort = type.getSort();\n if (typeSort == Type.OBJECT) {\n return addConstantClass(type.getInternalName());\n } else if (typeSort == Type.METHOD) {\n return addConstantMethodType(type.getDescriptor());\n } else { // type is a primitive or array type.\n return addConstantClass(type.getDescriptor());\n }\n } else if (value instanceof Handle) {\n Handle handle = (Handle) value;\n return addConstantMethodHandle(handle.getTag(), handle.getOwner(), handle.getName(), handle.getDesc(), handle.isInterface());\n } else if (value instanceof ConstantDynamic) {\n ConstantDynamic constantDynamic = (ConstantDynamic) value;\n return addConstantDynamic(constantDynamic.getName(), constantDynamic.getDescriptor(), constantDynamic.getBootstrapMethod(), constantDynamic.getBootstrapMethodArgumentsUnsafe());\n } else {\n throw new IllegalArgumentException(\"value \" + value);\n }\n }\n\n /**\n * Adds a CONSTANT_Class_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value the internal name of a class.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantClass(final String value) {\n return addConstantUtf8Reference(Symbol.CONSTANT_CLASS_TAG, value);\n }\n\n /**\n * Adds a CONSTANT_Fieldref_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param owner the internal name of a class.\n * @param name a field name.\n * @param descriptor a field descriptor.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantFieldref(final String owner, final String name, final String descriptor) {\n return addConstantMemberReference(Symbol.CONSTANT_FIELDREF_TAG, owner, name, descriptor);\n }\n\n /**\n * Adds a CONSTANT_Methodref_info or CONSTANT_InterfaceMethodref_info to the constant pool of this\n * symbol table. Does nothing if the constant pool already contains a similar item.\n *\n * @param owner the internal name of a class.\n * @param name a method name.\n * @param descriptor a method descriptor.\n * @param isInterface whether owner is an interface or not.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantMethodref(final String owner, final String name, final String descriptor, final boolean isInterface) {\n int tag = isInterface ? Symbol.CONSTANT_INTERFACE_METHODREF_TAG : Symbol.CONSTANT_METHODREF_TAG;\n return addConstantMemberReference(tag, owner, name, descriptor);\n }\n\n /**\n * Adds a CONSTANT_Fieldref_info, CONSTANT_Methodref_info or CONSTANT_InterfaceMethodref_info to\n * the constant pool of this symbol table. Does nothing if the constant pool already contains a\n * similar item.\n *\n * @param tag one of {@link Symbol#CONSTANT_FIELDREF_TAG}, {@link Symbol#CONSTANT_METHODREF_TAG}\n * or {@link Symbol#CONSTANT_INTERFACE_METHODREF_TAG}.\n * @param owner the internal name of a class.\n * @param name a field or method name.\n * @param descriptor a field or method descriptor.\n * @return a new or already existing Symbol with the given value.\n */\n private Entry addConstantMemberReference(final int tag, final String owner, final String name, final String descriptor) {\n int hashCode = hash(tag, owner, name, descriptor);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.owner.equals(owner) && entry.name.equals(name) && entry.value.equals(descriptor)) {\n return entry;\n }\n entry = entry.next;\n }\n constantPool.put122(tag, addConstantClass(owner).index, addConstantNameAndType(name, descriptor));\n return put(new Entry(constantPoolCount++, tag, owner, name, descriptor, 0, hashCode));\n }\n\n /**\n * Adds a new CONSTANT_Fieldref_info, CONSTANT_Methodref_info or CONSTANT_InterfaceMethodref_info\n * to the constant pool of this symbol table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param tag one of {@link Symbol#CONSTANT_FIELDREF_TAG}, {@link Symbol#CONSTANT_METHODREF_TAG}\n * or {@link Symbol#CONSTANT_INTERFACE_METHODREF_TAG}.\n * @param owner the internal name of a class.\n * @param name a field or method name.\n * @param descriptor a field or method descriptor.\n */\n private void addConstantMemberReference(final int index, final int tag, final String owner, final String name, final String descriptor) {\n add(new Entry(index, tag, owner, name, descriptor, 0, hash(tag, owner, name, descriptor)));\n }\n\n /**\n * Adds a CONSTANT_String_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value a string.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantString(final String value) {\n return addConstantUtf8Reference(Symbol.CONSTANT_STRING_TAG, value);\n }\n\n /**\n * Adds a CONSTANT_Integer_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value an int.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantInteger(final int value) {\n return addConstantIntegerOrFloat(Symbol.CONSTANT_INTEGER_TAG, value);\n }\n\n /**\n * Adds a CONSTANT_Float_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value a float.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantFloat(final float value) {\n return addConstantIntegerOrFloat(Symbol.CONSTANT_FLOAT_TAG, Float.floatToRawIntBits(value));\n }\n\n /**\n * Adds a CONSTANT_Integer_info or CONSTANT_Float_info to the constant pool of this symbol table.\n * Does nothing if the constant pool already contains a similar item.\n *\n * @param tag one of {@link Symbol#CONSTANT_INTEGER_TAG} or {@link Symbol#CONSTANT_FLOAT_TAG}.\n * @param value an int or float.\n * @return a constant pool constant with the given tag and primitive values.\n */\n private Symbol addConstantIntegerOrFloat(final int tag, final int value) {\n int hashCode = hash(tag, value);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.data == value) {\n return entry;\n }\n entry = entry.next;\n }\n constantPool.putByte(tag).putInt(value);\n return put(new Entry(constantPoolCount++, tag, value, hashCode));\n }\n\n /**\n * Adds a new CONSTANT_Integer_info or CONSTANT_Float_info to the constant pool of this symbol\n * table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param tag one of {@link Symbol#CONSTANT_INTEGER_TAG} or {@link Symbol#CONSTANT_FLOAT_TAG}.\n * @param value an int or float.\n */\n private void addConstantIntegerOrFloat(final int index, final int tag, final int value) {\n add(new Entry(index, tag, value, hash(tag, value)));\n }\n\n /**\n * Adds a CONSTANT_Long_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value a long.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantLong(final long value) {\n return addConstantLongOrDouble(Symbol.CONSTANT_LONG_TAG, value);\n }\n\n /**\n * Adds a CONSTANT_Double_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value a double.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantDouble(final double value) {\n return addConstantLongOrDouble(Symbol.CONSTANT_DOUBLE_TAG, Double.doubleToRawLongBits(value));\n }\n\n /**\n * Adds a CONSTANT_Long_info or CONSTANT_Double_info to the constant pool of this symbol table.\n * Does nothing if the constant pool already contains a similar item.\n *\n * @param tag one of {@link Symbol#CONSTANT_LONG_TAG} or {@link Symbol#CONSTANT_DOUBLE_TAG}.\n * @param value a long or double.\n * @return a constant pool constant with the given tag and primitive values.\n */\n private Symbol addConstantLongOrDouble(final int tag, final long value) {\n int hashCode = hash(tag, value);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.data == value) {\n return entry;\n }\n entry = entry.next;\n }\n int index = constantPoolCount;\n constantPool.putByte(tag).putLong(value);\n constantPoolCount += 2;\n return put(new Entry(index, tag, value, hashCode));\n }\n\n /**\n * Adds a new CONSTANT_Long_info or CONSTANT_Double_info to the constant pool of this symbol\n * table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param tag one of {@link Symbol#CONSTANT_LONG_TAG} or {@link Symbol#CONSTANT_DOUBLE_TAG}.\n * @param value a long or double.\n */\n private void addConstantLongOrDouble(final int index, final int tag, final long value) {\n add(new Entry(index, tag, value, hash(tag, value)));\n }\n\n /**\n * Adds a CONSTANT_NameAndType_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param name a field or method name.\n * @param descriptor a field or method descriptor.\n * @return a new or already existing Symbol with the given value.\n */\n int addConstantNameAndType(final String name, final String descriptor) {\n final int tag = Symbol.CONSTANT_NAME_AND_TYPE_TAG;\n int hashCode = hash(tag, name, descriptor);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.name.equals(name) && entry.value.equals(descriptor)) {\n return entry.index;\n }\n entry = entry.next;\n }\n constantPool.put122(tag, addConstantUtf8(name), addConstantUtf8(descriptor));\n return put(new Entry(constantPoolCount++, tag, name, descriptor, hashCode)).index;\n }\n\n /**\n * Adds a new CONSTANT_NameAndType_info to the constant pool of this symbol table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param name a field or method name.\n * @param descriptor a field or method descriptor.\n */\n private void addConstantNameAndType(final int index, final String name, final String descriptor) {\n final int tag = Symbol.CONSTANT_NAME_AND_TYPE_TAG;\n add(new Entry(index, tag, name, descriptor, hash(tag, name, descriptor)));\n }\n\n /**\n * Adds a CONSTANT_Utf8_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param value a string.\n * @return a new or already existing Symbol with the given value.\n */\n int addConstantUtf8(final String value) {\n int hashCode = hash(Symbol.CONSTANT_UTF8_TAG, value);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == Symbol.CONSTANT_UTF8_TAG && entry.hashCode == hashCode && entry.value.equals(value)) {\n return entry.index;\n }\n entry = entry.next;\n }\n constantPool.putByte(Symbol.CONSTANT_UTF8_TAG).putUTF8(value);\n return put(new Entry(constantPoolCount++, Symbol.CONSTANT_UTF8_TAG, value, hashCode)).index;\n }\n\n /**\n * Adds a new CONSTANT_String_info to the constant pool of this symbol table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param value a string.\n */\n private void addConstantUtf8(final int index, final String value) {\n add(new Entry(index, Symbol.CONSTANT_UTF8_TAG, value, hash(Symbol.CONSTANT_UTF8_TAG, value)));\n }\n\n /**\n * Adds a CONSTANT_MethodHandle_info to the constant pool of this symbol table. Does nothing if\n * the constant pool already contains a similar item.\n *\n * @param referenceKind one of {@link Opcodes#H_GETFIELD}, {@link Opcodes#H_GETSTATIC}, {@link\n * Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL}, {@link\n * Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, {@link\n * Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}.\n * @param owner the internal name of a class of interface.\n * @param name a field or method name.\n * @param descriptor a field or method descriptor.\n * @param isInterface whether owner is an interface or not.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantMethodHandle(final int referenceKind, final String owner, final String name, final String descriptor, final boolean isInterface) {\n final int tag = Symbol.CONSTANT_METHOD_HANDLE_TAG;\n // Note that we don't need to include isInterface in the hash computation, because it is\n // redundant with owner (we can't have the same owner with different isInterface values).\n int hashCode = hash(tag, owner, name, descriptor, referenceKind);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.data == referenceKind && entry.owner.equals(owner) && entry.name.equals(name) && entry.value.equals(descriptor)) {\n return entry;\n }\n entry = entry.next;\n }\n if (referenceKind <= Opcodes.H_PUTSTATIC) {\n constantPool.put112(tag, referenceKind, addConstantFieldref(owner, name, descriptor).index);\n } else {\n constantPool.put112(tag, referenceKind, addConstantMethodref(owner, name, descriptor, isInterface).index);\n }\n return put(new Entry(constantPoolCount++, tag, owner, name, descriptor, referenceKind, hashCode));\n }\n\n /**\n * Adds a new CONSTANT_MethodHandle_info to the constant pool of this symbol table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param referenceKind one of {@link Opcodes#H_GETFIELD}, {@link Opcodes#H_GETSTATIC}, {@link\n * Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL}, {@link\n * Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, {@link\n * Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}.\n * @param owner the internal name of a class of interface.\n * @param name a field or method name.\n * @param descriptor a field or method descriptor.\n */\n private void addConstantMethodHandle(final int index, final int referenceKind, final String owner, final String name, final String descriptor) {\n final int tag = Symbol.CONSTANT_METHOD_HANDLE_TAG;\n int hashCode = hash(tag, owner, name, descriptor, referenceKind);\n add(new Entry(index, tag, owner, name, descriptor, referenceKind, hashCode));\n }\n\n /**\n * Adds a CONSTANT_MethodType_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param methodDescriptor a method descriptor.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantMethodType(final String methodDescriptor) {\n return addConstantUtf8Reference(Symbol.CONSTANT_METHOD_TYPE_TAG, methodDescriptor);\n }\n\n /**\n * Adds a CONSTANT_Dynamic_info to the constant pool of this symbol table. Also adds the related\n * bootstrap method to the BootstrapMethods of this symbol table. Does nothing if the constant\n * pool already contains a similar item.\n *\n * @param name a method name.\n * @param descriptor a field descriptor.\n * @param bootstrapMethodHandle a bootstrap method handle.\n * @param bootstrapMethodArguments the bootstrap method arguments.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantDynamic(final String name, final String descriptor, final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) {\n Symbol bootstrapMethod = addBootstrapMethod(bootstrapMethodHandle, bootstrapMethodArguments);\n return addConstantDynamicOrInvokeDynamicReference(Symbol.CONSTANT_DYNAMIC_TAG, name, descriptor, bootstrapMethod.index);\n }\n\n /**\n * Adds a CONSTANT_InvokeDynamic_info to the constant pool of this symbol table. Also adds the\n * related bootstrap method to the BootstrapMethods of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param name a method name.\n * @param descriptor a method descriptor.\n * @param bootstrapMethodHandle a bootstrap method handle.\n * @param bootstrapMethodArguments the bootstrap method arguments.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantInvokeDynamic(final String name, final String descriptor, final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) {\n Symbol bootstrapMethod = addBootstrapMethod(bootstrapMethodHandle, bootstrapMethodArguments);\n return addConstantDynamicOrInvokeDynamicReference(Symbol.CONSTANT_INVOKE_DYNAMIC_TAG, name, descriptor, bootstrapMethod.index);\n }\n\n /**\n * Adds a CONSTANT_Dynamic or a CONSTANT_InvokeDynamic_info to the constant pool of this symbol\n * table. Does nothing if the constant pool already contains a similar item.\n *\n * @param tag one of {@link Symbol#CONSTANT_DYNAMIC_TAG} or {@link\n * Symbol#CONSTANT_INVOKE_DYNAMIC_TAG}.\n * @param name a method name.\n * @param descriptor a field descriptor for CONSTANT_DYNAMIC_TAG) or a method descriptor for\n * CONSTANT_INVOKE_DYNAMIC_TAG.\n * @param bootstrapMethodIndex the index of a bootstrap method in the BootstrapMethods attribute.\n * @return a new or already existing Symbol with the given value.\n */\n private Symbol addConstantDynamicOrInvokeDynamicReference(final int tag, final String name, final String descriptor, final int bootstrapMethodIndex) {\n int hashCode = hash(tag, name, descriptor, bootstrapMethodIndex);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.data == bootstrapMethodIndex && entry.name.equals(name) && entry.value.equals(descriptor)) {\n return entry;\n }\n entry = entry.next;\n }\n constantPool.put122(tag, bootstrapMethodIndex, addConstantNameAndType(name, descriptor));\n return put(new Entry(constantPoolCount++, tag, null, name, descriptor, bootstrapMethodIndex, hashCode));\n }\n\n /**\n * Adds a new CONSTANT_Dynamic_info or CONSTANT_InvokeDynamic_info to the constant pool of this\n * symbol table.\n *\n * @param tag one of {@link Symbol#CONSTANT_DYNAMIC_TAG} or {@link\n * Symbol#CONSTANT_INVOKE_DYNAMIC_TAG}.\n * @param index the constant pool index of the new Symbol.\n * @param name a method name.\n * @param descriptor a field descriptor for CONSTANT_DYNAMIC_TAG or a method descriptor for\n * CONSTANT_INVOKE_DYNAMIC_TAG.\n * @param bootstrapMethodIndex the index of a bootstrap method in the BootstrapMethods attribute.\n */\n private void addConstantDynamicOrInvokeDynamicReference(final int tag, final int index, final String name, final String descriptor, final int bootstrapMethodIndex) {\n int hashCode = hash(tag, name, descriptor, bootstrapMethodIndex);\n add(new Entry(index, tag, null, name, descriptor, bootstrapMethodIndex, hashCode));\n }\n\n /**\n * Adds a CONSTANT_Module_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param moduleName a fully qualified name (using dots) of a module.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantModule(final String moduleName) {\n return addConstantUtf8Reference(Symbol.CONSTANT_MODULE_TAG, moduleName);\n }\n\n /**\n * Adds a CONSTANT_Package_info to the constant pool of this symbol table. Does nothing if the\n * constant pool already contains a similar item.\n *\n * @param packageName the internal name of a package.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addConstantPackage(final String packageName) {\n return addConstantUtf8Reference(Symbol.CONSTANT_PACKAGE_TAG, packageName);\n }\n\n /**\n * Adds a CONSTANT_Class_info, CONSTANT_String_info, CONSTANT_MethodType_info,\n * CONSTANT_Module_info or CONSTANT_Package_info to the constant pool of this symbol table. Does\n * nothing if the constant pool already contains a similar item.\n *\n * @param tag one of {@link Symbol#CONSTANT_CLASS_TAG}, {@link Symbol#CONSTANT_STRING_TAG}, {@link\n * Symbol#CONSTANT_METHOD_TYPE_TAG}, {@link Symbol#CONSTANT_MODULE_TAG} or {@link\n * Symbol#CONSTANT_PACKAGE_TAG}.\n * @param value an internal class name, an arbitrary string, a method descriptor, a module or a\n * package name, depending on tag.\n * @return a new or already existing Symbol with the given value.\n */\n private Symbol addConstantUtf8Reference(final int tag, final String value) {\n int hashCode = hash(tag, value);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == tag && entry.hashCode == hashCode && entry.value.equals(value)) {\n return entry;\n }\n entry = entry.next;\n }\n constantPool.put12(tag, addConstantUtf8(value));\n return put(new Entry(constantPoolCount++, tag, value, hashCode));\n }\n\n /**\n * Adds a new CONSTANT_Class_info, CONSTANT_String_info, CONSTANT_MethodType_info,\n * CONSTANT_Module_info or CONSTANT_Package_info to the constant pool of this symbol table.\n *\n * @param index the constant pool index of the new Symbol.\n * @param tag one of {@link Symbol#CONSTANT_CLASS_TAG}, {@link Symbol#CONSTANT_STRING_TAG}, {@link\n * Symbol#CONSTANT_METHOD_TYPE_TAG}, {@link Symbol#CONSTANT_MODULE_TAG} or {@link\n * Symbol#CONSTANT_PACKAGE_TAG}.\n * @param value an internal class name, an arbitrary string, a method descriptor, a module or a\n * package name, depending on tag.\n */\n private void addConstantUtf8Reference(final int index, final int tag, final String value) {\n add(new Entry(index, tag, value, hash(tag, value)));\n }\n // -----------------------------------------------------------------------------------------------\n // Bootstrap method entries management.\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Adds a bootstrap method to the BootstrapMethods attribute of this symbol table. Does nothing if\n * the BootstrapMethods already contains a similar bootstrap method.\n *\n * @param bootstrapMethodHandle a bootstrap method handle.\n * @param bootstrapMethodArguments the bootstrap method arguments.\n * @return a new or already existing Symbol with the given value.\n */\n Symbol addBootstrapMethod(final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) {\n ByteVector bootstrapMethodsAttribute = bootstrapMethods;\n if (bootstrapMethodsAttribute == null) {\n bootstrapMethodsAttribute = bootstrapMethods = new ByteVector();\n }\n // The bootstrap method arguments can be Constant_Dynamic values, which reference other\n // bootstrap methods. We must therefore add the bootstrap method arguments to the constant pool\n // and BootstrapMethods attribute first, so that the BootstrapMethods attribute is not modified\n // while adding the given bootstrap method to it, in the rest of this method.\n for (Object bootstrapMethodArgument : bootstrapMethodArguments) {\n addConstant(bootstrapMethodArgument);\n }\n // Write the bootstrap method in the BootstrapMethods table. This is necessary to be able to\n // compare it with existing ones, and will be reverted below if there is already a similar\n // bootstrap method.\n int bootstrapMethodOffset = bootstrapMethodsAttribute.length;\n bootstrapMethodsAttribute.putShort(addConstantMethodHandle(bootstrapMethodHandle.getTag(), bootstrapMethodHandle.getOwner(), bootstrapMethodHandle.getName(), bootstrapMethodHandle.getDesc(), bootstrapMethodHandle.isInterface()).index);\n int numBootstrapArguments = bootstrapMethodArguments.length;\n bootstrapMethodsAttribute.putShort(numBootstrapArguments);\n for (Object bootstrapMethodArgument : bootstrapMethodArguments) {\n bootstrapMethodsAttribute.putShort(addConstant(bootstrapMethodArgument).index);\n }\n // Compute the length and the hash code of the bootstrap method.\n int bootstrapMethodlength = bootstrapMethodsAttribute.length - bootstrapMethodOffset;\n int hashCode = bootstrapMethodHandle.hashCode();\n for (Object bootstrapMethodArgument : bootstrapMethodArguments) {\n hashCode ^= bootstrapMethodArgument.hashCode();\n }\n hashCode &= 0x7FFFFFFF;\n // Add the bootstrap method to the symbol table or revert the above changes.\n return addBootstrapMethod(bootstrapMethodOffset, bootstrapMethodlength, hashCode);\n }\n\n /**\n * Adds a bootstrap method to the BootstrapMethods attribute of this symbol table. Does nothing if\n * the BootstrapMethods already contains a similar bootstrap method (more precisely, reverts the\n * content of {@link #bootstrapMethods} to remove the last, duplicate bootstrap method).\n *\n * @param offset the offset of the last bootstrap method in {@link #bootstrapMethods}, in bytes.\n * @param length the length of this bootstrap method in {@link #bootstrapMethods}, in bytes.\n * @param hashCode the hash code of this bootstrap method.\n * @return a new or already existing Symbol with the given value.\n */\n private Symbol addBootstrapMethod(final int offset, final int length, final int hashCode) {\n final byte[] bootstrapMethodsData = bootstrapMethods.data;\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == Symbol.BOOTSTRAP_METHOD_TAG && entry.hashCode == hashCode) {\n int otherOffset = (int) entry.data;\n boolean isSameBootstrapMethod = true;\n for (int i = 0; i < length; ++i) {\n if (bootstrapMethodsData[offset + i] != bootstrapMethodsData[otherOffset + i]) {\n isSameBootstrapMethod = false;\n break;\n }\n }\n if (isSameBootstrapMethod) {\n bootstrapMethods.length = offset; // Revert to old position.\n return entry;\n }\n }\n entry = entry.next;\n }\n return put(new Entry(bootstrapMethodCount++, Symbol.BOOTSTRAP_METHOD_TAG, offset, hashCode));\n }\n // -----------------------------------------------------------------------------------------------\n // Type table entries management.\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the type table element whose index is given.\n *\n * @param typeIndex a type table index.\n * @return the type table element whose index is given.\n */\n Symbol getType(final int typeIndex) {\n return typeTable[typeIndex];\n }\n\n /**\n * Adds a type in the type table of this symbol table. Does nothing if the type table already\n * contains a similar type.\n *\n * @param value an internal class name.\n * @return the index of a new or already existing type Symbol with the given value.\n */\n int addType(final String value) {\n int hashCode = hash(Symbol.TYPE_TAG, value);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == Symbol.TYPE_TAG && entry.hashCode == hashCode && entry.value.equals(value)) {\n return entry.index;\n }\n entry = entry.next;\n }\n return addTypeInternal(new Entry(typeCount, Symbol.TYPE_TAG, value, hashCode));\n }\n\n /**\n * Adds an {@link Frame#ITEM_UNINITIALIZED} type in the type table of this symbol table. Does\n * nothing if the type table already contains a similar type.\n *\n * @param value an internal class name.\n * @param bytecodeOffset the bytecode offset of the NEW instruction that created this {@link\n * Frame#ITEM_UNINITIALIZED} type value.\n * @return the index of a new or already existing type Symbol with the given value.\n */\n int addUninitializedType(final String value, final int bytecodeOffset) {\n int hashCode = hash(Symbol.UNINITIALIZED_TYPE_TAG, value, bytecodeOffset);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == Symbol.UNINITIALIZED_TYPE_TAG && entry.hashCode == hashCode && entry.data == bytecodeOffset && entry.value.equals(value)) {\n return entry.index;\n }\n entry = entry.next;\n }\n return addTypeInternal(new Entry(typeCount, Symbol.UNINITIALIZED_TYPE_TAG, value, bytecodeOffset, hashCode));\n }\n\n /**\n * Adds a merged type in the type table of this symbol table. Does nothing if the type table\n * already contains a similar type.\n *\n * @param typeTableIndex1 a {@link Symbol#TYPE_TAG} type, specified by its index in the type\n * table.\n * @param typeTableIndex2 another {@link Symbol#TYPE_TAG} type, specified by its index in the type\n * table.\n * @return the index of a new or already existing {@link Symbol#TYPE_TAG} type Symbol,\n * corresponding to the common super class of the given types.\n */\n int addMergedType(final int typeTableIndex1, final int typeTableIndex2) {\n long data = typeTableIndex1 < typeTableIndex2 ? typeTableIndex1 | (((long) typeTableIndex2) << 32) : typeTableIndex2 | (((long) typeTableIndex1) << 32);\n int hashCode = hash(Symbol.MERGED_TYPE_TAG, typeTableIndex1 + typeTableIndex2);\n Entry entry = get(hashCode);\n while (entry != null) {\n if (entry.tag == Symbol.MERGED_TYPE_TAG && entry.hashCode == hashCode && entry.data == data) {\n return entry.info;\n }\n entry = entry.next;\n }\n String type1 = typeTable[typeTableIndex1].value;\n String type2 = typeTable[typeTableIndex2].value;\n int commonSuperTypeIndex = addType(classWriter.getCommonSuperClass(type1, type2));\n put(new Entry(typeCount, Symbol.MERGED_TYPE_TAG, data, hashCode)).info = commonSuperTypeIndex;\n return commonSuperTypeIndex;\n }\n\n /**\n * Adds the given type Symbol to {@link #typeTable}.\n *\n * @param entry a {@link Symbol#TYPE_TAG} or {@link Symbol#UNINITIALIZED_TYPE_TAG} type symbol.\n * The index of this Symbol must be equal to the current value of {@link #typeCount}.\n * @return the index in {@link #typeTable} where the given type was added, which is also equal to\n * entry's index by hypothesis.\n */\n private int addTypeInternal(final Entry entry) {\n if (typeTable == null) {\n typeTable = new Entry[16];\n }\n if (typeCount == typeTable.length) {\n Entry[] newTypeTable = new Entry[2 * typeTable.length];\n System.arraycopy(typeTable, 0, newTypeTable, 0, typeTable.length);\n typeTable = newTypeTable;\n }\n typeTable[typeCount++] = entry;\n return put(entry).index;\n }\n // -----------------------------------------------------------------------------------------------\n // Static helper methods to compute hash codes.\n // -----------------------------------------------------------------------------------------------\n\n private static int hash(final int tag, final int value) {\n return 0x7FFFFFFF & (tag + value);\n }\n\n private static int hash(final int tag, final long value) {\n return 0x7FFFFFFF & (tag + (int) value + (int) (value >>> 32));\n }\n\n private static int hash(final int tag, final String value) {\n return 0x7FFFFFFF & (tag + value.hashCode());\n }\n\n private static int hash(final int tag, final String value1, final int value2) {\n return 0x7FFFFFFF & (tag + value1.hashCode() + value2);\n }\n\n private static int hash(final int tag, final String value1, final String value2) {\n return 0x7FFFFFFF & (tag + value1.hashCode() * value2.hashCode());\n }\n\n private static int hash(final int tag, final String value1, final String value2, final int value3) {\n return 0x7FFFFFFF & (tag + value1.hashCode() * value2.hashCode() * (value3 + 1));\n }\n\n private static int hash(final int tag, final String value1, final String value2, final String value3) {\n return 0x7FFFFFFF & (tag + value1.hashCode() * value2.hashCode() * value3.hashCode());\n }\n\n private static int hash(final int tag, final String value1, final String value2, final String value3, final int value4) {\n return 0x7FFFFFFF & (tag + value1.hashCode() * value2.hashCode() * value3.hashCode() * value4);\n }\n\n /**\n * An entry of a SymbolTable. This concrete and private subclass of {@link Symbol} adds two fields\n * which are only used inside SymbolTable, to implement hash sets of symbols (in order to avoid\n * duplicate symbols). See {@link #entries}.\n *\n * @author Eric Bruneton\n */\n private static class Entry extends Symbol {\n /** The hash code of this entry. */\n final int hashCode;\n /**\n * Another entry (and so on recursively) having the same hash code (modulo the size of {@link\n * #entries}) as this one.\n */\n Entry next;\n\n Entry(final int index, final int tag, final String owner, final String name, final String value, final long data, final int hashCode) {\n super(index, tag, owner, name, value, data);\n this.hashCode = hashCode;\n }\n\n Entry(final int index, final int tag, final String value, final int hashCode) {\n super(index, tag, /* owner = */ null, /* name = */ null, value, /* data = */ 0);\n this.hashCode = hashCode;\n }\n\n Entry(final int index, final int tag, final String value, final long data, final int hashCode) {\n super(index, tag, /* owner = */ null, /* name = */ null, value, data);\n this.hashCode = hashCode;\n }\n\n Entry(final int index, final int tag, final String name, final String value, final int hashCode) {\n super(index, tag, /* owner = */ null, name, value, /* data = */ 0);\n this.hashCode = hashCode;\n }\n\n Entry(final int index, final int tag, final long data, final int hashCode) {\n super(index, tag, /* owner = */ null, /* name = */ null, /* value = */ null, data);\n this.hashCode = hashCode;\n }\n }\n}\n", "file_name": "SymbolTable.java", "human_label": "Add constant information generated by its name and type to the constant pool and return the index of the constant.", "level": "project_runnable", "lineno": "649", "name": "addConstantNameAndType", "oracle_context": "{ \"apis\" : \"[hash, get, equals, put122, addConstantUtf8, put, Entry]\", \"classes\" : \"[Entry, Symbol]\", \"vars\" : \"[CONSTANT_NAME_AND_TYPE_TAG, value, index, next, constantPool, constantPoolCount]\" }", "package": "net.hasor.utils.asm", "project": "hasor-master" }, { "_id": "636767461a6d9265ec017d17", "all_context": "{ \"class_level\" : \"import org.antlr.v4.runtime.*;\\nimport org.antlr.v4.runtime.misc.*;\\nimport org.apache.commons.text.*;\\nimport org.apache.commons.text.translate.*;\\nimport org.jgrapht.alg.util.Pair;\\nimport org.jgrapht.nio.*;\\nimport java.io.*;\\nimport java.util.*;\\nimport java.util.Map.Entry;\\nString DEFAULT_GRAPH_ID_KEY;\\nCharSequenceTranslator unescapeId;\\nboolean notifyVertexAttributesOutOfOrder;\\nboolean notifyEdgeAttributesOutOfOrder;\\nSet vertices;\\nDeque subgraphScopes;\\nDeque stack;\\nLinkedList children;\\nList ids;\\nMap attrs;\\nList vertices;\\nSubgraphScope subgraph;\\nMap graphAttrs;\\nMap nodeAttrs;\\nMap edgeAttrs;\\nDOTEventDrivenImporter();\\nDOTEventDrivenImporter(boolean notifyVertexAttributesOutOfOrder,boolean notifyEdgeAttributesOutOfOrder);\\nimportInput(Reader in);\\nsyntaxError(Recognizer recognizer,Object offendingSymbol,int line,int charPositionInLine,String msg,RecognitionException e);\\nNotifyDOTListener();\\nenterGraph(GraphContext ctx);\\nexitGraph(GraphContext ctx);\\nenterGraphHeader(GraphHeaderContext ctx);\\nexitGraphHeader(GraphHeaderContext ctx);\\nenterGraphIdentifier(GraphIdentifierContext ctx);\\nexitGraphIdentifier(GraphIdentifierContext ctx);\\nenterAttributeStatement(AttributeStatementContext ctx);\\nexitAttributeStatement(AttributeStatementContext ctx);\\nenterAttributesList(AttributesListContext ctx);\\nexitAttributesList(AttributesListContext ctx);\\nenterAList(AListContext ctx);\\nexitAList(AListContext ctx);\\nenterEdgeStatement(EdgeStatementContext ctx);\\nexitEdgeStatement(EdgeStatementContext ctx);\\nenterIdentifierPairStatement(IdentifierPairStatementContext ctx);\\nexitIdentifierPairStatement(IdentifierPairStatementContext ctx);\\nenterNodeStatement(NodeStatementContext ctx);\\nexitNodeStatement(NodeStatementContext ctx);\\nenterNodeStatementNoAttributes(NodeStatementNoAttributesContext ctx);\\nexitNodeStatementNoAttributes(NodeStatementNoAttributesContext ctx);\\nenterNodeIdentifier(NodeIdentifierContext ctx);\\nexitNodeIdentifier(NodeIdentifierContext ctx);\\nenterSubgraphStatement(SubgraphStatementContext ctx);\\nexitSubgraphStatement(SubgraphStatementContext ctx);\\nenterIdentifierPair(IdentifierPairContext ctx);\\nexitIdentifierPair(IdentifierPairContext ctx);\\nenterIdentifier(IdentifierContext ctx);\\nexitIdentifier(IdentifierContext ctx);\\nState();\\ngetId();\\naddId(String id);\\nput(String key,Attribute value);\\nputAll(Map attrs);\\naddVertex(String v);\\ngetVertices();\\nSubgraphScope();\\naddVertices(List v);\\nunescapeHtmlString(String input);\\n\", \"repo_level\" : \"public interface Pair {public A getFirst();\\npublic B getSecond();\\npublic void setFirst(A f);\\npublic void setSecond(B s);\\npublic boolean hasElement(E e);\\npublic String toString();\\npublic boolean equals(Object o);\\npublic int hashCode();\\nstatic Pair of(A a,B b);\\n }\\n\" }", "class_name": "DOTEventDrivenImporter", "code": "private String unescapeId(String input){\n final char quote='\"';\n if (input.charAt(0) != quote || input.charAt(input.length() - 1) != quote) {\n return input;\n }\n String noQuotes=input.subSequence(1,input.length() - 1).toString();\n String unescaped=unescapeId.translate(noQuotes);\n return unescaped;\n}\n", "docstring": "/** \n * Unescape a string DOT identifier.\n * @param input the input\n * @return the unescaped output\n */\n", "end_lineno": "794", "file_content": "/*\n * (C) Copyright 2016-2021, by Dimitrios Michail and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.nio.dot;\n\nimport org.antlr.v4.runtime.*;\nimport org.antlr.v4.runtime.misc.*;\nimport org.apache.commons.text.*;\nimport org.apache.commons.text.translate.*;\nimport org.jgrapht.alg.util.Pair;\nimport org.jgrapht.nio.*;\n\nimport java.io.*;\nimport java.util.*;\nimport java.util.Map.Entry;\n\n/**\n * Import a graph from a DOT file.\n * \n *

      \n * For a description of the format see \n * http://en.wikipedia.org/wiki/DOT_language and\n * \n * http://www.graphviz.org/doc/info/lang.html\n * \n *

      \n * The importer notifies interested parties using consumers.\n *\n * @author Dimitrios Michail\n */\npublic class DOTEventDrivenImporter\n extends\n BaseEventDrivenImporter>\n implements\n EventDrivenImporter>\n{\n /**\n * Default key used for the graph ID.\n */\n public static final String DEFAULT_GRAPH_ID_KEY = \"ID\";\n\n // identifier unescape rule\n private final CharSequenceTranslator unescapeId;\n\n private boolean notifyVertexAttributesOutOfOrder;\n private boolean notifyEdgeAttributesOutOfOrder;\n\n /**\n * Constructs a new importer.\n */\n public DOTEventDrivenImporter()\n {\n this(true, true);\n }\n\n /**\n * Constructs a new importer.\n * \n * @param notifyVertexAttributesOutOfOrder whether to notify for vertex attributes out-of-order\n * even if they appear together in the input\n * @param notifyEdgeAttributesOutOfOrder whether to notify for edge attributes out-of-order even\n * if they appear together in the input\n */\n public DOTEventDrivenImporter(\n boolean notifyVertexAttributesOutOfOrder, boolean notifyEdgeAttributesOutOfOrder)\n {\n super();\n Map lookupMap = new HashMap<>();\n lookupMap.put(\"\\\\\\\\\", \"\\\\\");\n lookupMap.put(\"\\\\\\\"\", \"\\\"\");\n lookupMap.put(\"\\\\'\", \"'\");\n lookupMap.put(\"\\\\\", \"\");\n unescapeId = new AggregateTranslator(new LookupTranslator(lookupMap));\n\n this.notifyVertexAttributesOutOfOrder = notifyVertexAttributesOutOfOrder;\n this.notifyEdgeAttributesOutOfOrder = notifyEdgeAttributesOutOfOrder;\n }\n\n @Override\n public void importInput(Reader in)\n throws ImportException\n {\n try {\n /**\n * Create lexer with unbuffered input stream and use a token factory which copies\n * characters from the input stream into the text of the tokens.\n */\n DOTLexer lexer = new DOTLexer(new UnbufferedCharStream(in));\n lexer.setTokenFactory(new CommonTokenFactory(true));\n lexer.removeErrorListeners();\n ThrowingErrorListener errorListener = new ThrowingErrorListener();\n lexer.addErrorListener(errorListener);\n\n /**\n * Create parser with unbuffered token stream.\n */\n DOTParser parser = new DOTParser(new UnbufferedTokenStream<>(lexer));\n parser.removeErrorListeners();\n parser.addErrorListener(errorListener);\n\n /**\n * Disable parse tree building and attach listener.\n */\n parser.setBuildParseTree(false);\n parser.addParseListener(new NotifyDOTListener());\n\n /**\n * Parse\n */\n notifyImportEvent(ImportEvent.START);\n parser.graph();\n notifyImportEvent(ImportEvent.END);\n } catch (ParseCancellationException | IllegalArgumentException e) {\n throw new ImportException(\"Failed to import DOT graph: \" + e.getMessage(), e);\n }\n }\n\n /*\n * Common error listener for both lexer and parser which throws an exception.\n */\n private class ThrowingErrorListener\n extends\n BaseErrorListener\n {\n @Override\n public void syntaxError(\n Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine,\n String msg, RecognitionException e)\n throws ParseCancellationException\n {\n throw new ParseCancellationException(\n \"line \" + line + \":\" + charPositionInLine + \" \" + msg);\n }\n }\n\n /*\n * Listen on parser events and construct the graph. The listener is strongly dependent on the\n * grammar.\n */\n private class NotifyDOTListener\n extends\n DOTBaseListener\n {\n private Set vertices;\n\n // stacks to maintain scope and state\n private Deque subgraphScopes;\n private Deque stack;\n\n public NotifyDOTListener()\n {\n this.vertices = new HashSet<>();\n this.stack = new ArrayDeque<>();\n this.subgraphScopes = new ArrayDeque<>();\n }\n\n @Override\n public void enterGraph(DOTParser.GraphContext ctx)\n {\n stack.push(new State());\n subgraphScopes.push(new SubgraphScope());\n }\n\n @Override\n public void exitGraph(DOTParser.GraphContext ctx)\n {\n if (stack.isEmpty() || subgraphScopes.isEmpty()) {\n return;\n }\n subgraphScopes.pop();\n stack.pop();\n }\n\n @Override\n public void enterGraphHeader(DOTParser.GraphHeaderContext ctx)\n {\n // nothing\n }\n\n @Override\n public void exitGraphHeader(DOTParser.GraphHeaderContext ctx)\n {\n // nothing\n }\n\n @Override\n public void enterGraphIdentifier(DOTParser.GraphIdentifierContext ctx)\n {\n // add partial state\n stack.push(new State());\n }\n\n @Override\n public void exitGraphIdentifier(DOTParser.GraphIdentifierContext ctx)\n {\n if (stack.isEmpty()) {\n return;\n }\n\n // read graph id\n State s = stack.pop();\n State idPartial = s.children.peekFirst();\n\n if (idPartial != null) {\n notifyGraphAttribute(\n DEFAULT_GRAPH_ID_KEY, DefaultAttribute.createAttribute(idPartial.getId()));\n }\n\n // add as child of parent\n if (!stack.isEmpty()) {\n stack.element().children.addLast(s);\n }\n }\n\n @Override\n public void enterAttributeStatement(DOTParser.AttributeStatementContext ctx)\n {\n // add partial state\n stack.push(new State());\n }\n\n @Override\n public void exitAttributeStatement(DOTParser.AttributeStatementContext ctx)\n {\n if (stack.isEmpty() || subgraphScopes.isEmpty()) {\n return;\n }\n\n // read attributes\n State s = stack.pop();\n State child = s.children.peekFirst();\n if (child != null && child.attrs != null) {\n Map attrs = child.attrs;\n\n // update current scope\n SubgraphScope scope = subgraphScopes.element();\n if (ctx.NODE() != null) {\n scope.nodeAttrs.putAll(attrs);\n } else if (ctx.EDGE() != null) {\n scope.edgeAttrs.putAll(attrs);\n } else if (ctx.GRAPH() != null) {\n scope.graphAttrs.putAll(attrs);\n }\n }\n }\n\n @Override\n public void enterAttributesList(DOTParser.AttributesListContext ctx)\n {\n // add partial state\n stack.push(new State());\n }\n\n @Override\n public void exitAttributesList(DOTParser.AttributesListContext ctx)\n {\n if (stack.isEmpty()) {\n return;\n }\n\n // union children attributes\n State s = stack.pop();\n for (State child : s.children) {\n if (child.attrs != null) {\n s.putAll(child.attrs);\n }\n }\n\n // add as child of parent\n s.children.clear();\n if (!stack.isEmpty()) {\n stack.element().children.addLast(s);\n }\n }\n\n @Override\n public void enterAList(DOTParser.AListContext ctx)\n {\n // add partial state\n stack.push(new State());\n }\n\n @Override\n public void exitAList(DOTParser.AListContext ctx)\n {\n if (stack.isEmpty()) {\n return;\n }\n\n // collect attributes in map\n State s = stack.pop();\n Iterator it = s.children.iterator();\n while (it.hasNext()) {\n State child = it.next();\n if (child.ids != null && child.ids.size() == 1) {\n s.put(child.ids.get(0), null);\n } else if (child.ids != null && child.ids.size() >= 2) {\n s.put(child.ids.get(0), DefaultAttribute.createAttribute(child.ids.get(1)));\n }\n it.remove();\n }\n\n // add as child of parent\n s.children.clear();\n if (!stack.isEmpty()) {\n stack.element().children.addLast(s);\n }\n }\n\n @Override\n public void enterEdgeStatement(DOTParser.EdgeStatementContext ctx)\n {\n // add partial state\n stack.push(new State());\n }\n\n @Override\n public void exitEdgeStatement(DOTParser.EdgeStatementContext ctx)\n {\n if (stack.isEmpty() || subgraphScopes.isEmpty()) {\n return;\n }\n\n State s = stack.pop();\n\n // find attributes (last child)\n Map attrs = null;\n State last = s.children.peekLast();\n if (last != null && last.attrs != null) {\n attrs = last.attrs;\n }\n\n Iterator it = s.children.iterator();\n State cur, prev = null;\n while (it.hasNext()) {\n cur = it.next();\n if (cur.attrs != null) {\n // last node with attributes\n break;\n } else if (prev != null) {\n for (String sourceVertex : prev.getVertices()) {\n for (String targetVertex : cur.getVertices()) {\n // find default attributes\n Map edgeAttrs =\n new HashMap<>(subgraphScopes.element().edgeAttrs);\n // add extra attributes\n if (attrs != null) {\n edgeAttrs.putAll(attrs);\n }\n\n Pair pe = Pair.of(sourceVertex, targetVertex);\n\n if (notifyEdgeAttributesOutOfOrder) {\n // notify individually\n notifyEdge(pe);\n for (Entry entry : edgeAttrs.entrySet()) {\n notifyEdgeAttribute(pe, entry.getKey(), entry.getValue());\n }\n } else {\n // notify with all attributes\n notifyEdgeWithAttributes(pe, edgeAttrs);\n }\n }\n }\n }\n\n prev = cur;\n }\n }\n\n @Override\n public void enterIdentifierPairStatement(DOTParser.IdentifierPairStatementContext ctx)\n {\n // add partial state\n stack.push(new State());\n }\n\n @Override\n public void exitIdentifierPairStatement(DOTParser.IdentifierPairStatementContext ctx)\n {\n if (stack.isEmpty() || subgraphScopes.isEmpty()) {\n return;\n }\n\n // read key value pair\n State s = stack.pop();\n State idPairChild = s.children.peekFirst();\n if (idPairChild == null || idPairChild.ids == null) {\n return;\n }\n String key = idPairChild.ids.get(0);\n String value = idPairChild.ids.get(1);\n\n // update attributes in current scope\n SubgraphScope scope = subgraphScopes.element();\n scope.graphAttrs.put(key, DefaultAttribute.createAttribute(value));\n if (subgraphScopes.size() == 1) {\n notifyGraphAttribute(key, DefaultAttribute.createAttribute(value));\n }\n }\n\n @Override\n public void enterNodeStatement(DOTParser.NodeStatementContext ctx)\n {\n // add partial state\n stack.push(new State());\n }\n\n @Override\n public void exitNodeStatement(DOTParser.NodeStatementContext ctx)\n {\n if (stack.isEmpty() || subgraphScopes.isEmpty()) {\n return;\n }\n\n // read node id\n State s = stack.pop();\n Iterator it = s.children.iterator();\n if (!it.hasNext()) {\n return;\n }\n State nodeIdPartialState = it.next();\n String nodeId = nodeIdPartialState.getId();\n\n // read attributes\n Map attrs = null;\n if (it.hasNext()) {\n attrs = it.next().attrs;\n }\n if (attrs == null) {\n attrs = Collections.emptyMap();\n }\n\n // create or update vertex\n if (!vertices.contains(nodeId)) {\n SubgraphScope scope = subgraphScopes.element();\n // find default attributes\n Map defaultAttrs = new HashMap<>(scope.nodeAttrs);\n // append extra attributes\n defaultAttrs.putAll(attrs);\n\n if (notifyVertexAttributesOutOfOrder) {\n notifyVertex(nodeId);\n for (Entry entry : defaultAttrs.entrySet()) {\n notifyVertexAttribute(nodeId, entry.getKey(), entry.getValue());\n }\n } else {\n notifyVertexWithAttributes(nodeId, defaultAttrs);\n }\n\n vertices.add(nodeId);\n scope.addVertex(nodeId);\n } else {\n for (String key : attrs.keySet()) {\n notifyVertexAttribute(nodeId, key, attrs.get(key));\n }\n }\n s.addVertex(nodeId);\n\n // add as child of parent\n s.children.clear();\n if (!stack.isEmpty()) {\n stack.element().children.addLast(s);\n }\n }\n\n @Override\n public void enterNodeStatementNoAttributes(DOTParser.NodeStatementNoAttributesContext ctx)\n {\n // add partial state\n stack.push(new State());\n }\n\n @Override\n public void exitNodeStatementNoAttributes(DOTParser.NodeStatementNoAttributesContext ctx)\n {\n if (stack.isEmpty() || subgraphScopes.isEmpty()) {\n return;\n }\n\n // read node id\n State s = stack.pop();\n Iterator it = s.children.iterator();\n if (!it.hasNext()) {\n return;\n }\n State nodeIdPartial = it.next();\n String nodeId = nodeIdPartial.getId();\n\n // create or update vertex\n if (!vertices.contains(nodeId)) {\n SubgraphScope scope = subgraphScopes.element();\n // find default attributes\n Map defaultAttrs = new HashMap<>(scope.nodeAttrs);\n\n if (notifyVertexAttributesOutOfOrder) {\n notifyVertex(nodeId);\n for (Entry entry : defaultAttrs.entrySet()) {\n notifyVertexAttribute(nodeId, entry.getKey(), entry.getValue());\n }\n } else {\n notifyVertexWithAttributes(nodeId, defaultAttrs);\n }\n\n vertices.add(nodeId);\n scope.addVertex(nodeId);\n }\n s.addVertex(nodeId);\n\n // add as child of parent\n s.children.clear();\n if (!stack.isEmpty()) {\n stack.element().children.addLast(s);\n }\n }\n\n @Override\n public void enterNodeIdentifier(DOTParser.NodeIdentifierContext ctx)\n {\n // add partial state\n stack.push(new State());\n }\n\n @Override\n public void exitNodeIdentifier(DOTParser.NodeIdentifierContext ctx)\n {\n if (stack.isEmpty()) {\n return;\n }\n\n // collect only first child (ignore ports)\n State s = stack.pop();\n if (!s.children.isEmpty()) {\n s.addId(s.children.getFirst().getId());\n\n // add as child of parent\n s.children.clear();\n if (!stack.isEmpty()) {\n stack.element().children.addLast(s);\n }\n }\n }\n\n @Override\n public void enterSubgraphStatement(DOTParser.SubgraphStatementContext ctx)\n {\n // Create new scope with inherited attributes\n Map defaultGraphAttrs = subgraphScopes.element().graphAttrs;\n Map defaultNodeAttrs = subgraphScopes.element().nodeAttrs;\n Map defaultEdgeAttrs = subgraphScopes.element().edgeAttrs;\n SubgraphScope newState = new SubgraphScope();\n newState.graphAttrs.putAll(defaultGraphAttrs);\n newState.nodeAttrs.putAll(defaultNodeAttrs);\n newState.edgeAttrs.putAll(defaultEdgeAttrs);\n subgraphScopes.push(newState);\n\n // Add partial state\n State s = new State();\n s.subgraph = newState;\n stack.push(s);\n }\n\n @Override\n public void exitSubgraphStatement(DOTParser.SubgraphStatementContext ctx)\n {\n if (stack.isEmpty() || subgraphScopes.isEmpty()) {\n return;\n }\n\n // remove last scope\n SubgraphScope scope = subgraphScopes.pop();\n State s = stack.pop();\n\n // if not on root graph, append nodes to subgraph one level up\n if (scope.vertices != null && subgraphScopes.size() > 1) {\n subgraphScopes.element().addVertices(scope.vertices);\n }\n\n // add as child of parent\n s.children.clear();\n if (!stack.isEmpty()) {\n stack.element().children.addLast(s);\n }\n }\n\n @Override\n public void enterIdentifierPair(DOTParser.IdentifierPairContext ctx)\n {\n // add partial state\n stack.push(new State());\n }\n\n @Override\n public void exitIdentifierPair(DOTParser.IdentifierPairContext ctx)\n {\n if (stack.isEmpty()) {\n return;\n }\n\n // collect our two children as one pair\n State s = stack.pop();\n Iterator it = s.children.iterator();\n if (it.hasNext()) {\n s.addId(it.next().getId());\n }\n if (it.hasNext()) {\n s.addId(it.next().getId());\n }\n\n if (s.ids != null) {\n // add as child of parent\n s.children.clear();\n if (!stack.isEmpty()) {\n stack.element().children.addLast(s);\n }\n }\n }\n\n @Override\n public void enterIdentifier(DOTParser.IdentifierContext ctx)\n {\n // add partial state\n stack.push(new State());\n }\n\n @Override\n public void exitIdentifier(DOTParser.IdentifierContext ctx)\n {\n if (stack.isEmpty()) {\n return;\n }\n\n // collect actual identifier\n State s = stack.pop();\n String id = null;\n if (ctx.Id() != null) {\n id = ctx.Id().toString();\n } else if (ctx.String() != null) {\n id = unescapeId(ctx.String().toString());\n } else if (ctx.HtmlString() != null) {\n id = unescapeHtmlString(ctx.HtmlString().toString());\n } else if (ctx.Numeral() != null) {\n id = ctx.Numeral().toString();\n }\n\n // record id\n if (id != null) {\n s.addId(id);\n\n // add as child of parent\n if (!stack.isEmpty()) {\n stack.element().children.addLast(s);\n }\n }\n }\n }\n\n /*\n * Partial parsed state depending on node type.\n */\n private class State\n {\n LinkedList children;\n List ids;\n Map attrs;\n List vertices;\n SubgraphScope subgraph;\n\n public State()\n {\n this.children = new LinkedList<>();\n this.ids = null;\n this.attrs = null;\n this.vertices = null;\n this.subgraph = null;\n }\n\n public String getId()\n {\n if (ids == null || ids.isEmpty()) {\n return \"\";\n } else {\n return ids.get(0);\n }\n }\n\n public void addId(String id)\n {\n if (this.ids == null) {\n this.ids = new ArrayList<>();\n }\n this.ids.add(id);\n }\n\n public void put(String key, Attribute value)\n {\n if (this.attrs == null) {\n this.attrs = new HashMap<>();\n }\n this.attrs.put(key, value);\n }\n\n public void putAll(Map attrs)\n {\n if (this.attrs == null) {\n this.attrs = new HashMap<>();\n }\n this.attrs.putAll(attrs);\n }\n\n public void addVertex(String v)\n {\n if (this.vertices == null) {\n this.vertices = new ArrayList<>();\n }\n this.vertices.add(v);\n }\n\n public List getVertices()\n {\n if (vertices != null) {\n return vertices;\n } else if (subgraph != null && subgraph.vertices != null) {\n return subgraph.vertices;\n }\n return Collections.emptyList();\n }\n }\n\n /*\n * Records default attributes per subgraph\n */\n private class SubgraphScope\n {\n Map graphAttrs;\n Map nodeAttrs;\n Map edgeAttrs;\n List vertices;\n\n public SubgraphScope()\n {\n this.graphAttrs = new HashMap<>();\n this.nodeAttrs = new HashMap<>();\n this.edgeAttrs = new HashMap<>();\n this.vertices = null;\n }\n\n public void addVertex(String v)\n {\n if (this.vertices == null) {\n this.vertices = new ArrayList<>();\n }\n this.vertices.add(v);\n }\n\n public void addVertices(List v)\n {\n if (this.vertices == null) {\n this.vertices = new ArrayList<>();\n }\n this.vertices.addAll(v);\n }\n }\n\n /**\n * Unescape a string DOT identifier.\n *\n * @param input the input\n * @return the unescaped output\n */\n private String unescapeId(String input)\n {\n final char quote = '\"';\n if (input.charAt(0) != quote || input.charAt(input.length() - 1) != quote) {\n return input;\n }\n String noQuotes = input.subSequence(1, input.length() - 1).toString();\n String unescaped = unescapeId.translate(noQuotes);\n return unescaped;\n }\n\n /**\n * Unescape an HTML string DOT identifier.\n *\n * @param input the input\n * @return the unescaped output\n */\n private static String unescapeHtmlString(String input)\n {\n if (input.charAt(0) != '<' || input.charAt(input.length() - 1) != '>') {\n return input;\n }\n String noQuotes = input.subSequence(1, input.length() - 1).toString();\n String unescaped = StringEscapeUtils.unescapeXml(noQuotes);\n return unescaped;\n }\n\n}\n", "file_name": "DOTEventDrivenImporter.java", "human_label": "Unescape a dot identifier string.", "level": "class_runnable", "lineno": "779", "name": "unescapeId", "oracle_context": "{ \"apis\" : \"[charAt, length, toString, subSequence, translate]\", \"classes\" : \"[String]\", \"vars\" : \"[]\" }", "package": "org.jgrapht.nio.dot", "project": "jgrapht-master" }, { "_id": "6367676c1a6d9265ec018204", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static String[] concatenateStringArrays(String[] array1,String[] array2){\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr=new String[array1.length + array2.length];\n System.arraycopy(array1,0,newArr,0,array1.length);\n System.arraycopy(array2,0,newArr,array1.length,array2.length);\n return newArr;\n}\n", "docstring": "/** \n * Concatenate the given String arrays into one, with overlapping array elements included twice.

      The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n", "end_lineno": "755", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *

      \n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
      \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
      \n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
      \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

      The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

      This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

      The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

      The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

      Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

      Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

      The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

      The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

      A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

      A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Concatenate two string arrays into one.", "level": "slib_runnable", "lineno": "736", "name": "concatenateStringArrays", "oracle_context": "{ \"apis\" : \"[isEmpty, arraycopy]\", \"classes\" : \"[String[]]\", \"vars\" : \"[length]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636767641a6d9265ec018190", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.alg.util.*;\\nimport org.jgrapht.generate.*;\\nimport org.jgrapht.graph.*;\\nimport org.jgrapht.util.*;\\nimport java.util.*;\\nint n;\\nint m;\\nGraph graph;\\nMap vertices;\\nList indices;\\nBoolean weaklyChordal;\\nGraphPath certificate;\\nWeakChordalityInspector(Graph graph);\\nisWeaklyChordal();\\ngetCertificate();\\nlazyComputeWeakChordality();\\ncomputeGlobalSeparatorList();\\nreformatSeparatorList(List separators,E edge);\\ngetLabeling(E edge);\\nsortSeparatorsList(List separators);\\nunequalSeparators(List sep1,List sep2);\\ncomputeCoConnectedComponents(Graph graph,List separator);\\nputToNextBucket(Integer vertex,Integer vertexLabel,List bucketsByLabel,List labels);\\nreload(List bucketsByLabel,List labels,int minLabel);\\ncheckLabels(List coConnectedComponents,List separator);\\nfindHole(V sourceInSeparator,V source,V target,V targetInSeparator);\\nfindAntiHole(V source,V targetInSeparator);\\nfindHole(Graph graph,V sourceInSeparator,V source,V target,V targetInSeparator);\\nfindCycle(Set visited,Graph graph,V tarInSep,V tar,V sour,V sourInSep);\\nminimizeCycle(Graph graph,List cycle,V tar,V tarInSep,V sour,V sourInSep);\\nfindSeparators(Graph graph,E edge);\\ngetSeparator(Graph graph,V startVertex,Map dfsMap);\\nneighborhoodSetOf(Graph g,E edge);\\ninitMappings();\\n\", \"repo_level\" : \"\" }", "class_name": "WeakChordalityInspector", "code": "private void reload(List> bucketsByLabel,List labels,int minLabel){\n if (minLabel != 0 && minLabel < bucketsByLabel.size()) {\n Set bucket=bucketsByLabel.get(minLabel);\n for ( Integer vertex : bucket) {\n labels.set(vertex,0);\n bucketsByLabel.get(0).add(vertex);\n }\n bucket.clear();\n }\n}\n", "docstring": "/** \n * Moves all vertices from the bucket with label {@code minLabel} to the bucket with label 0.Clears the bucket with label {@code minLabel}. Updates the labeling accordingly.\n * @param bucketsByLabel the buckets vertices are stored in\n * @param labels the labels of the vertices\n * @param minLabel the minimum value of the non-empty bucket\n */\n", "end_lineno": "471", "file_content": "/*\n * (C) Copyright 2018-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.cycle;\n\nimport org.jgrapht.*;\nimport org.jgrapht.alg.util.*;\nimport org.jgrapht.generate.*;\nimport org.jgrapht.graph.*;\nimport org.jgrapht.util.*;\n\nimport java.util.*;\n\n/**\n * Tests whether a graph is weakly\n * chordal. Weakly chordal graphs are also known as weakly triangulated graphs. Triangulated in\n * the context of chordality has a different meaning than triangulated in the context of planarity,\n * where it refers to a maximal planar graph, see:\n * \n * http://mathworld.wolfram.com/TriangulatedGraph.html\n *

      \n * The following definitions of are equivalent:\n *

        \n *
      1. A graph is weakly chordal (weakly triangulated) if neither it nor its complement contains a\n * chordless cycles with five or more\n * vertices.
      2. \n *
      3. A 2-pair in a graph is a pair of non-adjacent vertices $x$, $y$ such that every chordless\n * path has exactly two edges. A graph is weakly chordal if every connected\n * induced subgraph $H$ that is not a\n * complete graph, contains a 2-pair.
      4. \n *
      \n * Chordal and weakly chordal graphs are\n * perfect.
      \n * For more details, refer to: Hayward, R.B. Weakly triangulated graphs, Journal of Combinatorial\n * Theory, Series B, vol 39, Issue 3, pp 200-208, 1985.\n *

      \n * The implementation in this class is based on: Lars Severin Skeide (2002)\n * Recognizing weakly chordal graphs.\n * Candidate Scientist Thesis in Informatics. Department of Informatics, University of Bergen,\n * Norway. The terminology used in this implementation is consistent with the one used in this\n * thesis.\n *

      \n * Both the runtime complexity and space complexity of the algorithm implemented in this class is\n * $\\mathcal{O}(|E|^2)$.
      \n * The inspected {@code graph} is specified at the construction time and cannot be modified. When\n * the graph is modified externally, the behavior of the {@code WeakChordalityInspector} is\n * undefined.\n *

      \n * In the case the inspected graph in not weakly chordal, this inspector provides a certificate in\n * the form of some hole or\n * anti-hole. The running time of\n * finding a hole is $\\mathcal{O}(|V| + |E|)$ and of finding an anti-hole - $\\mathcal{O}(|E|^2)$ in\n * the worst case.\n *\n * @param the graph vertex type\n * @param the graph edge type\n * @author Timofey Chudakov\n */\npublic class WeakChordalityInspector\n{\n /**\n * Vertex number\n */\n private final int n;\n /**\n * Edge number\n */\n private final int m;\n /**\n * The inspected graph\n */\n private Graph graph;\n /**\n * Bijective mapping of vertices onto $\\left[0,n-1\\right]$\n */\n private Map vertices;\n /**\n * Inverse of the bijective mapping of vertices onto $\\left[0,n-1\\right]$\n */\n private List indices;\n /**\n * Contains true if the graph is weakly chordal, otherwise false. Is null before the first call\n * to the {@link WeakChordalityInspector#isWeaklyChordal()}.\n */\n private Boolean weaklyChordal = null;\n /**\n * Contains a hole or an anti-hole of the graph, if it isn't weakly chordal\n */\n private GraphPath certificate;\n\n /**\n * Creates a weak chordality inspector for the {@code graph}\n *\n * @param graph the inspected {@code graph}\n */\n public WeakChordalityInspector(Graph graph)\n {\n this.graph = Objects.requireNonNull(graph);\n if (graph.getType().isDirected()) {\n this.graph = new AsUndirectedGraph<>(graph);\n }\n n = graph.vertexSet().size();\n m = graph.edgeSet().size();\n initMappings();\n }\n\n /**\n * Initializes the mappings of the vertices\n */\n private void initMappings()\n {\n VertexToIntegerMapping mapping = new VertexToIntegerMapping<>(graph.vertexSet());\n vertices = mapping.getVertexMap();\n indices = mapping.getIndexList();\n }\n\n /**\n * Check whether the inspected {@code graph} is weakly chordal. Note: this value is computed\n * lazily.\n *\n * @return true, if the inspected {@code graph} is weakly chordal, otherwise false.\n */\n public boolean isWeaklyChordal()\n {\n return lazyComputeWeakChordality();\n }\n\n /**\n * Computes and returns the certificate in the form of a hole or anti-hole in the inspected\n * {@code graph}. Returns null if the inspected graph is weakly chordal. Note: certificate is\n * computed lazily.\n *\n * @return a hole or\n * anti-hole in the\n * inspected {@code graph}, null if the {@code graph} is weakly chordal\n */\n public GraphPath getCertificate()\n {\n lazyComputeWeakChordality();\n return certificate;\n }\n\n /**\n * Lazily tests the weak chordality of the {@code graph} and returns the computed value.\n *\n * @return true, if the inspected {@code graph} is weakly chordal, otherwise false.\n */\n private boolean lazyComputeWeakChordality()\n {\n if (weaklyChordal == null) {\n List>, E>> globalSeparatorList =\n computeGlobalSeparatorList();\n\n if (globalSeparatorList.size() > 0) {\n Pair pair;\n sortSeparatorsList(globalSeparatorList);\n\n // Iterating over separators. Computing coconnected components only for distinct\n // separators\n int separatorsNum = 1;\n List> original = globalSeparatorList.get(0).getFirst();\n List> coConnectedComponents =\n computeCoConnectedComponents(graph, original);\n\n for (Pair>, E> separator : globalSeparatorList) {\n if (unequalSeparators(original, separator.getFirst())) {\n original = separator.getFirst();\n ++separatorsNum;\n if (n + m < separatorsNum) {\n return weaklyChordal = false;\n } else {\n coConnectedComponents = computeCoConnectedComponents(graph, original);\n }\n }\n if ((pair = checkLabels(coConnectedComponents, separator.getFirst())) != null) {\n // Found a pair of vertices which has labels 1 and 2. This means the graph\n // isn't weakly chordal. Start detecting a hole\n E holeFormer = separator.getSecond();\n V source = graph.getEdgeSource(holeFormer);\n V target = graph.getEdgeTarget(holeFormer);\n\n V sourceInSeparator = indices.get(pair.getFirst());\n V targetInSeparator = indices.get(pair.getSecond());\n\n if (!graph.containsEdge(source, sourceInSeparator)) {\n V t = sourceInSeparator;\n sourceInSeparator = targetInSeparator;\n targetInSeparator = t;\n }\n if (graph.containsEdge(sourceInSeparator, targetInSeparator)) {\n findAntiHole(source, targetInSeparator);\n } else {\n findHole(sourceInSeparator, source, target, targetInSeparator);\n }\n return weaklyChordal = false;\n }\n }\n\n return weaklyChordal = true;\n } else {\n\n return weaklyChordal = true;\n }\n }\n return weaklyChordal;\n }\n\n /**\n * Computes the global separator list of the {@code graph}. More precisely, for every edge $e$\n * in the $G = (V, E)$ computes list of minimal separators $S_e$ in the neighborhood of $e$ and\n * then concatenates these lists. Note: the result may contain duplicates\n *\n * @return the list of minimal separators of every edge $e$ in the inspected graph\n */\n private List>, E>> computeGlobalSeparatorList()\n {\n List>, E>> globalSeparatorList = new ArrayList<>();\n for (E edge : graph.edgeSet()) {\n V source = graph.getEdgeSource(edge);\n V target = graph.getEdgeTarget(edge);\n if (source != target) {\n List> edgeSeparators = findSeparators(graph, edge);\n globalSeparatorList.addAll(reformatSeparatorList(edgeSeparators, edge));\n }\n }\n return globalSeparatorList;\n }\n\n /**\n * Reformats the list o {@code separators} so that is can be conveniently used by this\n * inspector. More precisely, in every separator from the list of minimal separators in the\n * neighborhood of the {@code edge} substitutes all vertices for their indices in the numeration\n * defined by {@code vertices}. Pairs every separator with the {@code edge}.\n *\n * @param separators the list of minimal separators in the neighborhood of the {@code edge}\n * @param edge the edge, which neighborhood contains minimal separators from {@code separators}\n * @return the reformatted list of minimal separators\n */\n private List>, E>> reformatSeparatorList(\n List> separators, E edge)\n {\n List labeling = getLabeling(edge);\n List>, E>> reformattedSeparators = new ArrayList<>();\n List>>> vInSeparator = new ArrayList<>(n);\n for (int i = 0; i < n; i++) {\n vInSeparator.add(new ArrayList<>());\n }\n\n for (Set computedSeparator : separators) {\n List> reformattedSeparator =\n new ArrayList<>(computedSeparator.size());\n reformattedSeparators.add(new Pair<>(reformattedSeparator, edge));\n for (V vertex : computedSeparator) {\n int vertexIndex = vertices.get(vertex);\n vInSeparator.get(vertexIndex).add(reformattedSeparator);\n }\n }\n\n for (int vertex = 0; vertex < n; vertex++) {\n List>> listOfSeparators = vInSeparator.get(vertex);\n for (List> separator : listOfSeparators) {\n separator.add(new Pair<>(vertex, labeling.get(vertex)));\n }\n }\n\n return reformattedSeparators;\n\n }\n\n /**\n * Computes the labeling of the neighborhood of {@code edge} on the vertices {@code source} and\n * {@code target}. Vertex from the neighborhood is labeled with \"1\" if it sees only\n * {@code source}, \"2\" is it sees only {@code target}, and \"3\" if it sees both vertices.\n *\n * @param edge the edge, whose neighborhood is to be labeled\n * @return the computed labeling with the respect to the rule described above\n */\n private List getLabeling(E edge)\n {\n V source = graph.getEdgeSource(edge);\n V target = graph.getEdgeTarget(edge);\n List labeling = new ArrayList<>(Collections.nCopies(n, null));\n for (E sourceEdge : graph.edgesOf(source)) {\n labeling.set(vertices.get(Graphs.getOppositeVertex(graph, sourceEdge, source)), 1);\n }\n for (E targetEdge : graph.edgesOf(target)) {\n Integer oppositeIndex =\n vertices.get(Graphs.getOppositeVertex(graph, targetEdge, target));\n if (labeling.get(oppositeIndex) != null) {\n labeling.set(oppositeIndex, 3);\n } else {\n labeling.set(oppositeIndex, 2);\n }\n }\n return labeling;\n }\n\n /**\n * Sorts the {@code separators} using bucket sort\n *\n * @param separators the list of separators to be sorted\n */\n private void sortSeparatorsList(List>, E>> separators)\n {\n Queue>, E>> mainQueue = new ArrayDeque<>();\n int maxSeparatorLength = 0;\n for (Pair>, E> separator : separators) {\n if (separator.getFirst().size() > maxSeparatorLength) {\n maxSeparatorLength = separator.getFirst().size();\n }\n mainQueue.add(separator);\n }\n separators.clear();\n List>, E>>> queues = new ArrayList<>(n);\n for (int i = 0; i < n; i++) {\n queues.add(new LinkedList<>());\n }\n for (int i = 0; i < maxSeparatorLength; i++) {\n while (!mainQueue.isEmpty()) {\n Pair>, E> separator = mainQueue.remove();\n if (i >= separator.getFirst().size()) {\n separators.add(separator);\n } else {\n queues\n .get(\n separator\n .getFirst().get(separator.getFirst().size() - i - 1).getFirst())\n .add(separator);\n }\n }\n for (Queue>, E>> queue : queues) {\n mainQueue.addAll(queue);\n queue.clear();\n }\n }\n separators.addAll(mainQueue);\n }\n\n /**\n * Compares two separators for inequality. Labeling of the vertices in the separators isn't\n * considered\n *\n * @param sep1 first separator\n * @param sep2 second separator\n * @return true, if the separators are unequal, false otherwise\n */\n private boolean unequalSeparators(\n List> sep1, List> sep2)\n {\n if (sep1.size() == sep2.size()) {\n for (int i = 0; i < sep1.size(); i++) {\n if (!sep2.get(i).getFirst().equals(sep1.get(i).getFirst())) {\n return true;\n }\n }\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Computes the connected components of the complement of the graph induces by the vertices of\n * the {@code separator}. They are also called \"coconnected components\". The running time is\n * $\\mathcal{O}(|V| + |E|)$.\n *\n * @param separator the separators, whose coconnected components are computed\n * @return the coconected of the {@code separator}\n */\n private List> computeCoConnectedComponents(\n Graph graph, List> separator)\n {\n List> coConnectedComponents = new ArrayList<>();\n\n // Initializing buckets, labels and set of unvisited vertices. Every vertex in separator is\n // put\n // to bucket with label 0\n List> bucketsByLabel = new ArrayList<>(separator.size());\n for (int i = 0; i < separator.size(); i++) {\n bucketsByLabel.add(new HashSet<>());\n }\n List labels = new ArrayList<>(Collections.nCopies(n, -1));\n Set unvisited = CollectionUtil.newHashSetWithExpectedSize(separator.size());\n separator.forEach(pair -> {\n unvisited.add(pair.getFirst());\n labels.set(pair.getFirst(), 0);\n });\n bucketsByLabel.set(0, unvisited);\n int minLabel = 0;\n\n while (unvisited.size() > 0) {\n List coConnectedComponent = new ArrayList<>();\n do {\n // When minLabel = coConnectedComponent.size(), we've visited all vertices in some\n // coconnected component in the separator. If there exist unvisited vertices, we\n // start again\n while (!bucketsByLabel.get(minLabel).isEmpty()) {\n Integer vertex = bucketsByLabel.get(minLabel).iterator().next();\n bucketsByLabel.get(minLabel).remove(vertex);\n coConnectedComponent.add(vertex);\n labels.set(vertex, -1);\n\n for (E edge : graph.edgesOf(indices.get(vertex))) {\n Integer opposite = vertices\n .get(Graphs.getOppositeVertex(graph, edge, indices.get(vertex)));\n Integer oppositeLabel = labels.get(opposite);\n if (oppositeLabel != -1) {\n putToNextBucket(opposite, oppositeLabel, bucketsByLabel, labels);\n }\n }\n }\n ++minLabel;\n } while (minLabel != coConnectedComponent.size());\n reload(bucketsByLabel, labels, minLabel);\n\n coConnectedComponents.add(coConnectedComponent);\n minLabel = 0;\n }\n return coConnectedComponents;\n }\n\n /**\n * Moves the {@code vertex} to the next bucket.\n *\n * @param vertex the vertex to be moved\n * @param vertexLabel the label of the {@code vertex}\n * @param bucketsByLabel the buckets, in which vertices are stored\n * @param labels the labels of the vertices\n */\n private void putToNextBucket(\n Integer vertex, Integer vertexLabel, List> bucketsByLabel,\n List labels)\n {\n bucketsByLabel.get(vertexLabel).remove(vertex);\n bucketsByLabel.get(vertexLabel + 1).add(vertex);\n labels.set(vertex, vertexLabel + 1);\n }\n\n /**\n * Moves all vertices from the bucket with label {@code minLabel} to the bucket with label 0.\n * Clears the bucket with label {@code minLabel}. Updates the labeling accordingly.\n *\n * @param bucketsByLabel the buckets vertices are stored in\n * @param labels the labels of the vertices\n * @param minLabel the minimum value of the non-empty bucket\n */\n private void reload(List> bucketsByLabel, List labels, int minLabel)\n {\n if (minLabel != 0 && minLabel < bucketsByLabel.size()) {\n Set bucket = bucketsByLabel.get(minLabel);\n for (Integer vertex : bucket) {\n labels.set(vertex, 0);\n bucketsByLabel.get(0).add(vertex);\n }\n bucket.clear();\n }\n }\n\n /**\n * For a given coconnected component of the {@code separator} checks whether every vertex in it\n * is seen by al least one vertex of the edge that is separated by the {@code separator}\n *\n * @param coConnectedComponents the set of the coconected components of the {@code separator}\n * @param separator minimal separator of some edge in the {@code graph}\n * @return true if the condition described above holds, false otherwise\n */\n private Pair checkLabels(\n List> coConnectedComponents, List> separator)\n {\n List vertexLabels = new ArrayList<>(Collections.nCopies(n, null));\n for (Pair vertexAndLabel : separator) {\n vertexLabels.set(vertexAndLabel.getFirst(), vertexAndLabel.getSecond());\n }\n for (List coConnectedComponent : coConnectedComponents) {\n int label = 0;\n Integer labelVertex = null;\n for (Integer vertex : coConnectedComponent) {\n if (vertexLabels.get(vertex) != 3) {\n if (label != 0) {\n if (label != vertexLabels.get(vertex)) {\n return new Pair<>(labelVertex, vertex);\n }\n } else {\n label = vertexLabels.get(vertex);\n labelVertex = vertex;\n }\n }\n }\n }\n return null;\n }\n\n /**\n * Finds a hole in the inspected {@code graph}. Vertices {@code sourceInSeparator},\n * {@code source}, {@code target} and {@code targetInSeparator} belong to the computes hole.\n * They are used to correctly find a hole in the inspected graph.\n *\n * @param sourceInSeparator vertex on the hole\n * @param source vertex on the hole\n * @param target vertex on the hole\n * @param targetInSeparator vertex on the hole\n */\n private void findHole(V sourceInSeparator, V source, V target, V targetInSeparator)\n {\n this.certificate = findHole(graph, sourceInSeparator, source, target, targetInSeparator);\n }\n\n /**\n * Finds an anti-hole in the inspected {@code graph}. Vertices {@code source} and\n * {@code targetInSeparator} specify an edge, which belongs to the anti-hole in the complement\n * of the {@code graph}. Then the hole in the complement of the graph is computed in the graph's\n * complement in the same way a hole is computed in the {@code graph}.\n *\n * @param source endpoint of the edge that belongs to the anti-hole\n * @param targetInSeparator endpoint of the edge that belongs to the anti-hole\n */\n private void findAntiHole(V source, V targetInSeparator)\n {\n // Generating the complement of the inspected graph\n ComplementGraphGenerator generator = new ComplementGraphGenerator<>(graph, false);\n Graph complement = Pseudograph. createBuilder(graph.getEdgeSupplier()).build();\n generator.generateGraph(complement);\n\n E cycleFormer = complement.getEdge(source, targetInSeparator);\n V cycleSource = graph.getEdgeSource(cycleFormer);\n V cycleTarget = graph.getEdgeTarget(cycleFormer);\n\n // For edge cycleFormer we need to find the separator, which contains vertices with labels 1\n // and 2\n // After that the procedure of detecting a hole in the complement of the graph is identical\n // to finding a hole in the graph itself\n List> separators = findSeparators(complement, cycleFormer);\n List>, E>> reformatted =\n reformatSeparatorList(separators, cycleFormer);\n\n sortSeparatorsList(reformatted);\n\n List> original = reformatted.get(0).getFirst();\n List> coConnectedComponents =\n computeCoConnectedComponents(complement, original);\n\n Pair pair;\n for (Pair>, E> separator : reformatted) {\n if (unequalSeparators(separator.getFirst(), original)) {\n original = separator.getFirst();\n coConnectedComponents =\n computeCoConnectedComponents(complement, separator.getFirst());\n }\n if ((pair = checkLabels(coConnectedComponents, separator.getFirst())) != null) {\n // Found a pair of vertices with labels 1 and 2\n V cycleSourceInSeparator = indices.get(pair.getFirst());\n V cycleTargetInSeparator = indices.get(pair.getSecond());\n if (!complement.containsEdge(cycleSourceInSeparator, cycleSource)) {\n V t = cycleSourceInSeparator;\n cycleSourceInSeparator = cycleTargetInSeparator;\n cycleTargetInSeparator = t;\n }\n this.certificate = findHole(\n complement, cycleSourceInSeparator, cycleSource, cycleTarget,\n cycleTargetInSeparator);\n return;\n }\n }\n }\n\n /**\n * Finds a hole in the specified {@code graph}. Vertices {@code sourceInSeparator},\n * {@code source}, {@code target} and {@code targetInSeparator} belong to the computes hole.\n * They are used to correctly find a hole in the specified {@code graph}.\n *\n * @param sourceInSeparator vertex on the hole\n * @param source vertex on the hole\n * @param target vertex on the hole\n * @param targetInSeparator vertex on the hole\n * @return the computed hole on the {@code graph}\n */\n private GraphPath findHole(\n Graph graph, V sourceInSeparator, V source, V target, V targetInSeparator)\n {\n Set visited = CollectionUtil.newHashSetWithExpectedSize(graph.vertexSet().size());\n visited.add(target);\n visited.add(source);\n\n // Obtaining some cycle, which can be minimized to a hole\n List cycle =\n findCycle(visited, graph, targetInSeparator, target, source, sourceInSeparator);\n cycle = minimizeCycle(graph, cycle, target, targetInSeparator, source, sourceInSeparator);\n\n return new GraphWalk<>(graph, cycle, 0);\n }\n\n /**\n * Starts the iterative depth-first traversal from {@code sourInSep} vertex. Tries to build a\n * cycle with the vertices, which aren't adjacent to the {@code tar} and {@code sour}. This\n * condition is used in order to ensure that the cycle contains a hole, to which it is later\n * minimized.\n *\n * @param visited defines which vertices have been visited already\n * @param graph the graph the search is performed on\n * @param tarInSep the end point of the cycle\n * @param tar the vertex, which can't be adjacent to the vertices in the cycle\n * @param sour the vertex, which can't be adjacent to the vertices in the cycle\n * @param sourInSep the vertex the search is started from\n * @return the computed cycle, which contains a hole\n */\n private List findCycle(\n Set visited, Graph graph, V tarInSep, V tar, V sour, V sourInSep)\n {\n List cycle = new ArrayList<>(Arrays.asList(tarInSep, tar, sour));\n Deque stack = new ArrayDeque<>();\n stack.add(sourInSep);\n\n while (!stack.isEmpty()) {\n V currentVertex = stack.removeLast();\n if (visited.add(currentVertex)) {\n\n // trying to advance cycle from current vertex\n // removing all vertices from the head of the cycle, which aren't adjacent to the\n // current vertex\n while (!graph.containsEdge(cycle.get(cycle.size() - 1), currentVertex)) {\n cycle.remove(cycle.size() - 1);\n }\n cycle.add(currentVertex);\n if (tarInSep.equals(currentVertex)) {\n // the cycle is complete\n break;\n } else {\n for (V neighbor : Graphs.neighborListOf(graph, currentVertex)) {\n // add a vertex to the stack if it hasn't been visited yet and it isn't\n // adjacent to the\n // source vertex and (it isn't adjacent to the target vertex or it is\n // targetInSeparator (the end of the cycle))\n if (!visited.contains(neighbor) && !graph.containsEdge(sour, neighbor)\n && (!graph.containsEdge(tar, neighbor) || neighbor.equals(tarInSep)))\n {\n stack.add(neighbor);\n }\n }\n }\n }\n }\n return cycle;\n }\n\n /**\n * Minimizes the {@code cycle} so that it contains a hole in the {@code graph}. Vertices\n * {@code tar}, {@code tarInSep}, {@code sour} and {@code sourInSep} belong to the final result.\n *\n * @param graph the graph, which contains vertices from {@code cycle}\n * @param cycle the cycle to minimize\n * @param tar vertex, which should belong to the final result\n * @param tarInSep vertex, which should belong to the final result\n * @param sour vertex, which should belong to the final result\n * @param sourInSep vertex, which should belong to the final result\n * @return a list of vertices, which defines a hole in the {@code graph}\n */\n private List minimizeCycle(\n Graph graph, List cycle, V tar, V tarInSep, V sour, V sourInSep)\n {\n List minimizedCycle = new ArrayList<>(Arrays.asList(tarInSep, tar, sour));\n Set forwardVertices = new HashSet<>(cycle);\n forwardVertices.remove(tar);\n forwardVertices.remove(sour);\n forwardVertices.remove(sourInSep);\n\n for (int i = 3; i < cycle.size() - 1;) {\n V current = cycle.get(i);\n minimizedCycle.add(current);\n forwardVertices.remove(current);\n\n // Computing a set of vertices, which are adjacent to current and have greater index\n // in the cycle than current\n Set currentForward = new HashSet<>();\n for (V neighbor : Graphs.neighborListOf(graph, current)) {\n if (forwardVertices.contains(neighbor)) {\n currentForward.add(neighbor);\n }\n }\n\n // Jump to the forward vertex with the greatest index. Therefore we ensure, that\n // the resulting cycle doesn't contain chords\n for (V forwardVertex : currentForward) {\n if (forwardVertices.contains(forwardVertex)) {\n do {\n forwardVertices.remove(cycle.get(i));\n i++;\n } while (i < cycle.size() && !cycle.get(i).equals(forwardVertex));\n }\n }\n }\n minimizedCycle.add(tarInSep);\n return minimizedCycle;\n }\n\n /**\n * Computes and returns all minimal separators in the neighborhood of the {@code edge} in the\n * {@code graph}. The result may contain duplicate separators.\n *\n * @param graph the graph to search minimal separators in\n * @param edge the edge, whose neighborhood is being explored\n * @return the list of all minimal separators in the neighborhood of the {@code edge}. The\n * resulted list may contain duplicates.\n */\n private List> findSeparators(Graph graph, E edge)\n {\n List> separators = new ArrayList<>();\n V source = graph.getEdgeSource(edge);\n V target = graph.getEdgeTarget(edge);\n Set neighborhood = neighborhoodSetOf(graph, edge);\n Map dfsMap = CollectionUtil.newHashMapWithExpectedSize(graph.vertexSet().size());\n\n // 0 - unvisited (white), 1 - neighbor of the edge (red), 2 - visited (black)\n for (V vertex : graph.vertexSet()) {\n if (neighborhood.contains(vertex)) {\n dfsMap.put(vertex, (byte) 1);\n } else {\n dfsMap.put(vertex, (byte) 0);\n }\n }\n dfsMap.put(source, (byte) 2);\n dfsMap.put(target, (byte) 2);\n\n for (V vertex : graph.vertexSet()) {\n if (dfsMap.get(vertex) == 0) {\n // possible to find one more separator\n Set separator = getSeparator(graph, vertex, dfsMap);\n if (!separator.isEmpty()) {\n separators.add(separator);\n }\n }\n }\n\n return separators;\n }\n\n /**\n * Performs iterative depth-first search starting from the {@code startVertex} in the\n * {@code graph}. Adds every encountered red vertex to the resulting separator. Doesn't process\n * red vertices. Marks all white vertices with black color.\n *\n * @param graph the graph dfs is performed on\n * @param startVertex the vertex to start depth-first traversal from\n * @param dfsMap the depth-first vertex labeling\n * @return the computed separator, which consists of all encountered red vertices\n */\n private Set getSeparator(Graph graph, V startVertex, Map dfsMap)\n {\n Deque stack = new ArrayDeque<>();\n Set separator = new HashSet<>();\n stack.add(startVertex);\n\n while (!stack.isEmpty()) {\n V currentVertex = stack.removeLast();\n if (dfsMap.get(currentVertex) == 0) {\n dfsMap.put(currentVertex, (byte) 2);\n for (E edge : graph.edgesOf(currentVertex)) {\n V opposite = Graphs.getOppositeVertex(graph, edge, currentVertex);\n if (dfsMap.get(opposite) == 0) {\n stack.add(opposite);\n } else if (dfsMap.get(opposite) == 1) {\n separator.add(opposite); // found red vertex, which belongs to the separator\n }\n }\n }\n }\n\n return separator;\n }\n\n /**\n * Returns a set of vertices that are neighbors of the source of the specified edge or of the\n * target of specified edge. The endpoints of the specified edge aren't included in the result.\n *\n * @param g the graph to look for neighbors in\n * @param edge the edge to get the neighbors of\n * @return a set of vertices that are neighbors of at least one endpoint of the specified edge.\n * The endpoints of the specified edge aren't included in the result\n */\n private Set neighborhoodSetOf(Graph g, E edge)\n {\n Set neighborhood = new HashSet<>();\n\n V source = g.getEdgeSource(edge);\n V target = g.getEdgeTarget(edge);\n\n for (E e : g.edgesOf(source)) {\n neighborhood.add(Graphs.getOppositeVertex(g, e, source));\n }\n for (E e : g.edgesOf(target)) {\n neighborhood.add(Graphs.getOppositeVertex(g, e, target));\n }\n neighborhood.remove(source);\n neighborhood.remove(target);\n\n return neighborhood;\n }\n}\n", "file_name": "WeakChordalityInspector.java", "human_label": "Move all vertices from the minimum label bucket to the bucket with label 0 and clear the minimum label bucket.", "level": "self_contained", "lineno": "453", "name": "reload", "oracle_context": "{ \"apis\" : \"[size, get, set, add, clear]\", \"classes\" : \"[Set]\", \"vars\" : \"[]\" }", "package": "org.jgrapht.alg.cycle", "project": "jgrapht-master" }, { "_id": "6367676a1a6d9265ec0181d4", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static String[] addStringToArray(String[] array,String str){\n if (Objects.isEmpty(array)) {\n return new String[]{str};\n }\n String[] newArr=new String[array.length + 1];\n System.arraycopy(array,0,newArr,0,array.length);\n newArr[array.length]=str;\n return newArr;\n}\n", "docstring": "/** \n * Append the given String to the given String array, returning a new array consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n", "end_lineno": "734", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *

      \n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
      \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
      \n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
      \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

      The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

      This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

      The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

      The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

      Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

      Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

      The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

      The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

      A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

      A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Append a string to a string array.", "level": "slib_runnable", "lineno": "719", "name": "addStringToArray", "oracle_context": "{ \"apis\" : \"[isEmpty, arraycopy]\", \"classes\" : \"[String[]]\", \"vars\" : \"[length]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "6367676b1a6d9265ec0181dd", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static int countOccurrencesOf(String str,String sub){\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count=0;\n int pos=0;\n int idx;\n while ((idx=str.indexOf(sub,pos)) != -1) {\n ++count;\n pos=idx + sub.length();\n }\n return count;\n}\n", "docstring": "/** \n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n", "end_lineno": "370", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *

      \n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
      \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
      \n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
      \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

      The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

      This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

      The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

      The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

      Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

      Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

      The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

      The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

      A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

      A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Return the frequencies that the substring appears in the string.", "level": "self_contained", "lineno": "352", "name": "countOccurrencesOf", "oracle_context": "{ \"apis\" : \"[length, indexOf]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636766811a6d9265ec017499", "all_context": "{ \"class_level\" : \"import org.atmosphere.annotation.Processor;\\nimport org.atmosphere.cache.BroadcasterCacheInspector;\\nimport org.atmosphere.cache.DefaultBroadcasterCache;\\nimport org.atmosphere.cache.UUIDBroadcasterCache;\\nimport org.atmosphere.config.ApplicationConfiguration;\\nimport org.atmosphere.config.AtmosphereHandlerConfig;\\nimport org.atmosphere.config.AtmosphereHandlerProperty;\\nimport org.atmosphere.config.FrameworkConfiguration;\\nimport org.atmosphere.container.BlockingIOCometSupport;\\nimport org.atmosphere.container.Tomcat7BIOSupportWithWebSocket;\\nimport org.atmosphere.container.WebLogicServlet30WithWebSocket;\\nimport org.atmosphere.handler.AbstractReflectorAtmosphereHandler;\\nimport org.atmosphere.handler.ReflectorServletProcessor;\\nimport org.atmosphere.inject.InjectableObjectFactory;\\nimport org.atmosphere.interceptor.AndroidAtmosphereInterceptor;\\nimport org.atmosphere.interceptor.CacheHeadersInterceptor;\\nimport org.atmosphere.interceptor.CorsInterceptor;\\nimport org.atmosphere.interceptor.HeartbeatInterceptor;\\nimport org.atmosphere.interceptor.IdleResourceInterceptor;\\nimport org.atmosphere.interceptor.InvokationOrder;\\nimport org.atmosphere.interceptor.JSONPAtmosphereInterceptor;\\nimport org.atmosphere.interceptor.JavaScriptProtocol;\\nimport org.atmosphere.interceptor.OnDisconnectInterceptor;\\nimport org.atmosphere.interceptor.PaddingAtmosphereInterceptor;\\nimport org.atmosphere.interceptor.SSEAtmosphereInterceptor;\\nimport org.atmosphere.interceptor.WebSocketMessageSuspendInterceptor;\\nimport org.atmosphere.util.AtmosphereConfigReader;\\nimport org.atmosphere.util.DefaultEndpointMapper;\\nimport org.atmosphere.util.DefaultUUIDProvider;\\nimport org.atmosphere.util.EndpointMapper;\\nimport org.atmosphere.util.ExecutorsFactory;\\nimport org.atmosphere.util.IOUtils;\\nimport org.atmosphere.util.IntrospectionUtils;\\nimport org.atmosphere.util.ServletContextFactory;\\nimport org.atmosphere.util.UUIDProvider;\\nimport org.atmosphere.util.Utils;\\nimport org.atmosphere.util.Version;\\nimport org.atmosphere.util.VoidServletConfig;\\nimport org.atmosphere.util.analytics.FocusPoint;\\nimport org.atmosphere.util.analytics.JGoogleAnalyticsTracker;\\nimport org.atmosphere.util.analytics.ModuleDetection;\\nimport org.atmosphere.websocket.DefaultWebSocketFactory;\\nimport org.atmosphere.websocket.DefaultWebSocketProcessor;\\nimport org.atmosphere.websocket.WebSocket;\\nimport org.atmosphere.websocket.WebSocketFactory;\\nimport org.atmosphere.websocket.WebSocketHandler;\\nimport org.atmosphere.websocket.WebSocketProcessor;\\nimport org.atmosphere.websocket.WebSocketProtocol;\\nimport org.atmosphere.websocket.protocol.SimpleHttpProtocol;\\nimport org.slf4j.Logger;\\nimport org.slf4j.LoggerFactory;\\nimport javax.servlet.Servlet;\\nimport javax.servlet.ServletConfig;\\nimport javax.servlet.ServletContext;\\nimport javax.servlet.ServletException;\\nimport java.io.BufferedReader;\\nimport java.io.File;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport java.io.InputStreamReader;\\nimport java.io.UnsupportedEncodingException;\\nimport java.net.HttpURLConnection;\\nimport java.net.MalformedURLException;\\nimport java.net.URI;\\nimport java.net.URL;\\nimport java.net.URLClassLoader;\\nimport java.net.URLDecoder;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collections;\\nimport java.util.Comparator;\\nimport java.util.Enumeration;\\nimport java.util.HashMap;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nimport java.util.Objects;\\nimport java.util.concurrent.ConcurrentHashMap;\\nimport java.util.concurrent.ConcurrentLinkedQueue;\\nimport java.util.concurrent.ExecutorService;\\nimport java.util.concurrent.ThreadPoolExecutor;\\nimport java.util.concurrent.atomic.AtomicBoolean;\\nimport static org.atmosphere.cpr.ApplicationConfig.ALLOW_QUERYSTRING_AS_REQUEST;\\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER;\\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER_MAPPING;\\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER_PATH;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CACHE;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CLASS;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_FACTORY;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_LIFECYCLE_POLICY;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_SHAREABLE_LISTENERS;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_WAIT_TIME;\\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCAST_FILTER_CLASSES;\\nimport static org.atmosphere.cpr.ApplicationConfig.CONTENT_TYPE_FIRST_RESPONSE;\\nimport static org.atmosphere.cpr.ApplicationConfig.DISABLE_ONSTATE_EVENT;\\nimport static org.atmosphere.cpr.ApplicationConfig.META_SERVICE_PATH;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_ALLOW_SESSION_TIMEOUT_REMOVAL;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_ATMOSPHERE_XML;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_BLOCKING_COMETSUPPORT;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_COMET_SUPPORT;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_NATIVE_COMETSUPPORT;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SERVLET_MAPPING;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SESSION_SUPPORT;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_THROW_EXCEPTION_ON_CLONED_REQUEST;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_USE_STREAM;\\nimport static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID;\\nimport static org.atmosphere.cpr.ApplicationConfig.USE_SERVLET_CONTEXT_PARAMETERS;\\nimport static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROCESSOR;\\nimport static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROTOCOL;\\nimport static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_SUPPORT;\\nimport static org.atmosphere.cpr.Broadcaster.ROOT_MASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.ATMOSPHERE_CONFIG;\\nimport static org.atmosphere.cpr.FrameworkConfig.CDI_INJECTOR;\\nimport static org.atmosphere.cpr.FrameworkConfig.GUICE_INJECTOR;\\nimport static org.atmosphere.cpr.FrameworkConfig.HAZELCAST_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.INJECT_LIBARY;\\nimport static org.atmosphere.cpr.FrameworkConfig.JERSEY_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.JERSEY_CONTAINER;\\nimport static org.atmosphere.cpr.FrameworkConfig.JGROUPS_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.JMS_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.KAFKA_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.RABBITMQ_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.REDIS_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.RMI_BROADCASTER;\\nimport static org.atmosphere.cpr.FrameworkConfig.SPRING_INJECTOR;\\nimport static org.atmosphere.cpr.FrameworkConfig.THROW_EXCEPTION_ON_CLONED_REQUEST;\\nimport static org.atmosphere.cpr.FrameworkConfig.XMPP_BROADCASTER;\\nimport static org.atmosphere.cpr.HeaderConfig.ATMOSPHERE_POST_BODY;\\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_TRACKING_ID;\\nimport static org.atmosphere.util.IOUtils.realPath;\\nimport static org.atmosphere.websocket.WebSocket.WEBSOCKET_SUSPEND;\\nString DEFAULT_ATMOSPHERE_CONFIG_PATH;\\nString DEFAULT_LIB_PATH;\\nString DEFAULT_HANDLER_PATH;\\nString META_SERVICE;\\nString MAPPING_REGEX;\\nString ASYNC_IO;\\nLogger logger;\\nList broadcasterFilters;\\nList asyncSupportListeners;\\nList atmosphereResourceListeners;\\nArrayList possibleComponentsCandidate;\\nHashMap initParams;\\nAtmosphereConfig config;\\nAtomicBoolean isCometSupportConfigured;\\nboolean isFilter;\\nMap atmosphereHandlers;\\nConcurrentLinkedQueue broadcasterTypes;\\nConcurrentLinkedQueue objectFactoryType;\\nConcurrentLinkedQueue inspectors;\\nString mappingRegex;\\nboolean useNativeImplementation;\\nboolean useBlockingImplementation;\\nboolean useStreamForFlushingComments;\\nboolean useServlet30;\\nAsyncSupport asyncSupport;\\nString broadcasterClassName;\\nboolean isCometSupportSpecified;\\nboolean isBroadcasterSpecified;\\nboolean isSessionSupportSpecified;\\nboolean isThrowExceptionOnClonedRequestSpecified;\\nBroadcasterFactory broadcasterFactory;\\nString broadcasterFactoryClassName;\\nString broadcasterCacheClassName;\\nboolean webSocketEnabled;\\nString broadcasterLifeCyclePolicy;\\nString webSocketProtocolClassName;\\nWebSocketProtocol webSocketProtocol;\\nString handlersPath;\\nServletConfig servletConfig;\\nboolean autoDetectHandlers;\\nboolean hasNewWebSocketProtocol;\\nString atmosphereDotXmlPath;\\nString metaServicePath;\\nLinkedList interceptors;\\nboolean scanDone;\\nString annotationProcessorClassName;\\nList broadcasterListeners;\\nString webSocketProcessorClassName;\\nboolean webSocketProtocolInitialized;\\nEndpointMapper endpointMapper;\\nString libPath;\\nboolean isInit;\\nboolean sharedThreadPools;\\nList packages;\\nLinkedList annotationPackages;\\nboolean allowAllClassesScan;\\nboolean annotationFound;\\nboolean executeFirstSet;\\nAtmosphereObjectFactory objectFactory;\\nAtomicBoolean isDestroyed;\\nboolean externalizeDestroy;\\nAnnotationProcessor annotationProcessor;\\nList excludedInterceptors;\\nLinkedList broadcasterCacheListeners;\\nList filterManipulators;\\nAtmosphereResourceFactory arFactory;\\nMetaBroadcaster metaBroadcaster;\\nAtmosphereResourceSessionFactory sessionFactory;\\nString defaultSerializerClassName;\\nClass defaultSerializerClass;\\nList frameworkListeners;\\nUUIDProvider uuidProvider;\\nThread shutdownHook;\\nList> DEFAULT_ATMOSPHERE_INTERCEPTORS;\\nWebSocketFactory webSocketFactory;\\nIllegalStateException initializationError;\\nAtmosphereHandler REFLECTOR_ATMOSPHEREHANDLER;\\nAtmosphereHandler atmosphereHandler;\\nBroadcaster broadcaster;\\nString mapping;\\nboolean create;\\nboolean needRequestScopedInjection;\\nboolean wilcardMapping;\\nMetaServiceProcedure procedure;\\nAtomicBoolean done;\\nonRequest(AtmosphereResource resource);\\ndestroy();\\nsetAndConfigureAtmosphereResourceFactory(AtmosphereResourceFactory arFactory);\\nAtmosphereHandlerWrapper(BroadcasterFactory broadcasterFactory,AtmosphereHandler atmosphereHandler,String mapping,AtmosphereConfig config);\\nhookInjection(AtmosphereConfig config);\\nAtmosphereHandlerWrapper(AtmosphereHandler atmosphereHandler,Broadcaster broadcaster,AtmosphereConfig config);\\ntoString();\\nneedRequestScopedInjection();\\nwildcardMapping();\\napply(AtmosphereFramework fwk,Class clazz);\\napply(AtmosphereFramework fwk,Class c);\\nconfigure(AtmosphereConfig config);\\nnewClassInstance(Class classType,Class defaultType);\\nallowInjectionOf(Object o);\\nAtmosphereFramework();\\nAtmosphereFramework(ServletConfig sc);\\nAtmosphereFramework(boolean isFilter,boolean autoDetectHandlers);\\nnewAtmosphereConfig();\\npopulateBroadcasterType();\\npopulateObjectFactoryType();\\naddAtmosphereHandler(String mapping,AtmosphereHandler h,List l);\\naddAtmosphereHandler(String mapping,AtmosphereHandler h,Broadcaster broadcaster,List l);\\naddAtmosphereHandler(String mapping,AtmosphereHandler h,String broadcasterId,List l);\\ncreateWrapperAndConfigureHandler(AtmosphereHandler h,String mapping,List l);\\naddAtmosphereHandler(String mapping,AtmosphereHandler h);\\naddMapping(String path,AtmosphereHandlerWrapper w);\\nnormalizePath(String path);\\naddAtmosphereHandler(String mapping,AtmosphereHandler h,String broadcasterId);\\ninitServletProcessor(AtmosphereHandler h);\\naddAtmosphereHandler(String mapping,AtmosphereHandler h,Broadcaster broadcaster);\\nremoveAtmosphereHandler(String mapping);\\nremoveAllAtmosphereHandler();\\nremoveAllInitParams();\\naddInitParameter(String name,String value);\\nreadSystemProperties();\\npatchContainer();\\ninit();\\ninit(ServletConfig sc);\\npreventOOM();\\ninit(ServletConfig sc,boolean wrap);\\nservletConfig(ServletConfig sc,boolean wrap);\\ngetServletName();\\ngetServletContext();\\ngetInitParameter(String name);\\ngetInitParameterNames();\\nreconfigureInitParams(boolean reconfigureInitParams);\\ninfo();\\nuniverse();\\nconfigureAnnotationPackages();\\nanalytics();\\nconfigureAtmosphereInterceptor(ServletConfig sc);\\nnewAInterceptor(Class a);\\ncompare(AtmosphereInterceptor i1,AtmosphereInterceptor i2);\\nconfigureWebDotXmlAtmosphereHandler(ServletConfig sc);\\nconfigureScanningPackage(ServletConfig sc,String value);\\ndefaultPackagesToScan();\\nconfigureBroadcasterFactory();\\nconfigureBroadcaster();\\ninstallAnnotationProcessor(ServletConfig sc);\\ndoInitParamsForWebSocket(ServletConfig sc);\\ndoInitParams(ServletConfig sc);\\ndoInitParams(ServletConfig sc,boolean reconfigure);\\nloadConfiguration(ServletConfig sc);\\ndetectSupportedFramework(ServletConfig sc);\\nconfigureDetectedFramework(ReflectorServletProcessor rsp,boolean isJersey);\\nlookupDefaultBroadcasterType(String defaultB);\\nautodetectBroadcaster();\\nlookupDefaultObjectFactoryType();\\nsessionSupport(boolean sessionSupport);\\ninitAtmosphereHandler(ServletConfig sc);\\ninitAtmosphereHandler();\\ncheckWebSocketSupportState();\\nonRequest(AtmosphereResource r);\\ninitWebSocket();\\ninitEndpointMapper();\\ncloseAtmosphereResource();\\ndestroyInterceptors();\\nresetStates();\\nloadMetaService();\\nloadAtmosphereDotXml(InputStream stream,ClassLoader c);\\nsetAsyncSupport(AsyncSupport asyncSupport);\\nsetCometSupport(AsyncSupport asyncSupport);\\ngetAsyncSupport();\\ngetCometSupport();\\ncreateAsyncSupportResolver();\\nautoDetectContainer();\\nautoDetectAtmosphereHandlers(ServletContext servletContext,ClassLoader classloader);\\nloadAtmosphereHandlersFromPath(ClassLoader classloader,String realPath);\\nautoDetectWebSocketHandler(ServletContext servletContext,ClassLoader classloader);\\nloadWebSocketFromPath(ClassLoader classloader,String realPath);\\ngetFiles(File f);\\nconfigureRequestResponse(AtmosphereRequest req,AtmosphereResponse res);\\ndoCometSupport(AtmosphereRequest req,AtmosphereResponse res);\\ngetDefaultBroadcasterClassName();\\nsetDefaultBroadcasterClassName(String bccn);\\nisUseStreamForFlushingComments();\\nisUseServlet30();\\nsetUseStreamForFlushingComments(boolean useStreamForFlushingComments);\\ngetBroadcasterFactory();\\nsetBroadcasterFactory(BroadcasterFactory broadcasterFactory);\\ngetBroadcasterCacheClassName();\\nsetBroadcasterCacheClassName(String broadcasterCacheClassName);\\naddBroadcasterType(String broadcasterTypeString);\\nbroadcasterTypes();\\ngetWebSocketProtocolClassName();\\nsetWebSocketProtocolClassName(String webSocketProtocolClassName);\\ngetAtmosphereHandlers();\\nconfigureQueryStringAsRequest(AtmosphereRequest request);\\ngetWebSocketProtocol();\\nisUseNativeImplementation();\\nsetUseNativeImplementation(boolean useNativeImplementation);\\nisUseBlockingImplementation();\\nsetUseBlockingImplementation(boolean useBlockingImplementation);\\ngetAtmosphereDotXmlPath();\\nsetAtmosphereDotXmlPath(String atmosphereDotXmlPath);\\ngetHandlersPath();\\nsetHandlersPath(String handlersPath);\\ngetLibPath();\\nsetLibPath(String libPath);\\ngetWebSocketProcessorClassName();\\nsetWebsocketProcessorClassName(String webSocketProcessorClassName);\\ninterceptor(AtmosphereInterceptor c);\\naddDefaultOrAppInterceptors();\\naddInterceptorToAllWrappers(AtmosphereInterceptor c);\\naddInterceptorToWrapper(AtmosphereHandlerWrapper wrapper,AtmosphereInterceptor c);\\naddInterceptorToWrapper(AtmosphereHandlerWrapper wrapper,List interceptors);\\ncheckDuplicate(AtmosphereInterceptor c);\\ncheckDuplicate(List interceptorList,Class c);\\ninterceptors();\\nannotationProcessorClassName(String annotationProcessorClassName);\\nasyncSupportListener(AsyncSupportListener asyncSupportListener);\\nasyncSupportListeners();\\naddBroadcasterListener(BroadcasterListener b);\\naddBroadcasterCacheListener(BroadcasterCacheListener b);\\nbroadcasterCacheListeners();\\naddBroadcasterCacheInjector(BroadcasterCacheInspector b);\\ninspectors();\\ngetAtmosphereConfig();\\ngetServletConfig();\\nbroadcasterFilters();\\nbroadcasterFilters(BroadcastFilter f);\\nisShareExecutorServices();\\nshareExecutorServices(boolean sharedThreadPools);\\nautoConfigureService(ServletContext sc);\\nendPointMapper();\\nendPointMapper(EndpointMapper endpointMapper);\\naddAnnotationPackage(Class clazz);\\nnotify(TYPE type,AtmosphereRequest request,AtmosphereResponse response);\\nnotifyDestroyed(String uuid);\\nnotifySuspended(String uuid);\\naddWebSocketHandler(WebSocketHandler handler);\\naddWebSocketHandler(String path,WebSocketHandler handler);\\naddWebSocketHandler(String path,WebSocketHandler handler,AtmosphereHandler h);\\naddWebSocketHandler(String path,WebSocketHandler handler,AtmosphereHandler h,List l);\\nannotationScanned(boolean b);\\ninitialized();\\npackages();\\ncustomAnnotationPackages();\\naddCustomAnnotationPackage(Class p);\\nobjectFactory(AtmosphereObjectFactory objectFactory);\\nexternalizeDestroy(boolean externalizeDestroy);\\nannotationProcessor();\\nisBroadcasterSpecified();\\nconfigureObjectFactory();\\nexcludeInterceptor(String interceptor);\\nfilterManipulator(FilterManipulator m);\\nfilterManipulators();\\nisAServletFilter();\\nobjectFactoryType();\\nmappingRegex();\\nmappingRegex(String mappingRegex);\\nsetUseServlet30(boolean useServlet30);\\nwebSocketEnabled();\\nwebSocketEnabled(boolean webSocketEnabled);\\nbroadcasterLifeCyclePolicy();\\nbroadcasterLifeCyclePolicy(String broadcasterLifeCyclePolicy);\\nbroadcasterListeners();\\nsharedThreadPools();\\nsharedThreadPools(boolean sharedThreadPools);\\nallowAllClassesScan();\\nallowAllClassesScan(boolean allowAllClassesScan);\\nobjectFactory();\\nexternalizeDestroy();\\nexcludedInterceptors();\\ndefaultInterceptors();\\natmosphereFactory();\\nconfigureAtmosphereResourceFactory();\\nconfigureWebSocketFactory();\\nmetaBroadcaster();\\nconfigureMetaBroadcaster();\\ngetDefaultSerializerClassName();\\ngetDefaultSerializerClass();\\nsetDefaultSerializerClassName(String defaultSerializerClassName);\\ninitDefaultSerializer();\\nsessionFactory();\\nisDestroyed();\\nframeworkListener(AtmosphereFrameworkListener l);\\nframeworkListeners();\\nonPreInit();\\nonPostInit();\\nonPreDestroy();\\nonPostDestroy();\\natmosphereResourceListeners();\\natmosphereResourceListener(AtmosphereResourceListener atmosphereResourceListener);\\nuuidProvider(UUIDProvider uuidProvider);\\nuuidProvider();\\nwebSocketFactory();\\nwebSocketFactory(WebSocketFactory webSocketFactory);\\ninitializationError(IllegalStateException initializationError);\\nMetaServiceAction(MetaServiceProcedure p);\\n\", \"repo_level\" : \"public interface Processor { void handle(AtmosphereFramework framework,Class annotatedClass);\\n }\\npublic interface BroadcasterCacheInspector { boolean inspect(BroadcastMessage message);\\n }\\npublic interface DefaultBroadcasterCache {public void start();\\npublic void stop();\\npublic void cleanup();\\npublic CacheMessage addToCache(String broadcasterId,String uuid,BroadcastMessage message);\\npublic List retrieveFromCache(String id,String uuid);\\npublic BroadcasterCache clearCache(String broadcasterId,String uuid,CacheMessage cache);\\npublic BroadcasterCache excludeFromCache(String broadcasterId,AtmosphereResource r);\\npublic BroadcasterCache cacheCandidate(String broadcasterId,String uuid);\\npublic BroadcasterCache inspector(BroadcasterCacheInspector interceptor);\\npublic BroadcasterCache addBroadcasterCacheListener(BroadcasterCacheListener l);\\npublic BroadcasterCache removeBroadcasterCacheListener(BroadcasterCacheListener l);\\npublic void configure(AtmosphereConfig config);\\n }\\npublic interface UUIDBroadcasterCache {public void configure(AtmosphereConfig config);\\npublic void start();\\npublic void stop();\\npublic void cleanup();\\npublic CacheMessage addToCache(String broadcasterId,String uuid,BroadcastMessage message);\\npublic List retrieveFromCache(String broadcasterId,String uuid);\\npublic BroadcasterCache clearCache(String broadcasterId,String uuid,CacheMessage message);\\npublic BroadcasterCache inspector(BroadcasterCacheInspector b);\\npublic BroadcasterCache addBroadcasterCacheListener(BroadcasterCacheListener l);\\npublic BroadcasterCache removeBroadcasterCacheListener(BroadcasterCacheListener l);\\nprotected String uuid(AtmosphereResource r);\\npublic Map> messages();\\npublic Map activeClients();\\nprotected boolean inspect(BroadcastMessage m);\\npublic void setInvalidateCacheInterval(long invalidateCacheInterval);\\npublic void setClientIdleTime(long clientIdleTime);\\nprotected void invalidateExpiredEntries();\\npublic BroadcasterCache excludeFromCache(String broadcasterId,AtmosphereResource r);\\npublic BroadcasterCache cacheCandidate(String broadcasterId,String uuid);\\npublic String toString();\\npublic List listeners();\\npublic List inspectors();\\n }\\npublic interface ApplicationConfiguration {public String getParamName();\\npublic void setParamName(String paramName);\\npublic String getParamValue();\\npublic void setParamValue(String paramValue);\\n }\\npublic interface AtmosphereHandlerConfig {public String getSupportSession();\\npublic void setSupportSession(String supportSession);\\npublic String getContextRoot();\\npublic void setContextRoot(String contextRoot);\\npublic String getClassName();\\npublic void setClassName(String className);\\npublic String getBroadcaster();\\npublic void setBroadcaster(String broadcaster);\\npublic List getProperties();\\npublic void setProperties(List properties);\\npublic List getApplicationConfig();\\npublic void setApplicationConfig(List applicationConfig);\\npublic List getFrameworkConfig();\\npublic void setFrameworkConfig(List frameworkConfig);\\npublic String getBroadcasterCache();\\npublic void setBroadcasterCache(String broadcasterCache);\\npublic List getBroadcastFilterClasses();\\npublic void setAtmosphereInterceptorClasses(List interceptors);\\npublic List getAtmosphereInterceptorClasses();\\npublic void setBroadcastFilterClasses(List broadcastFilterClasses);\\npublic String getCometSupport();\\npublic void setCometSupport(String cometSupport);\\n }\\npublic interface AtmosphereHandlerProperty {public String getName();\\npublic void setName(String name);\\npublic String getValue();\\npublic void setValue(String value);\\n }\\npublic interface FrameworkConfiguration {public String getParamName();\\npublic void setParamName(String paramName);\\npublic String getParamValue();\\npublic void setParamValue(String paramValue);\\n }\\npublic interface BlockingIOCometSupport {public Action service(AtmosphereRequest req,AtmosphereResponse res);\\nprotected void suspend(Action action,AtmosphereRequest req,AtmosphereResponse res);\\npublic void onResume(AtmosphereResourceEvent event);\\npublic Action cancelled(AtmosphereRequest req,AtmosphereResponse res);\\npublic void action(AtmosphereResourceImpl r);\\npublic AsyncSupport complete(AtmosphereResourceImpl r);\\n }\\npublic interface Tomcat7BIOSupportWithWebSocket {public Action service(AtmosphereRequest req,AtmosphereResponse res);\\npublic Action doService(AtmosphereRequest req,AtmosphereResponse res);\\npublic boolean supportWebSocket();\\n }\\npublic interface WebLogicServlet30WithWebSocket {public boolean supportWebSocket();\\npublic String getContainerName();\\n }\\npublic interface AbstractReflectorAtmosphereHandler {public void onStateChange(AtmosphereResourceEvent event);\\nprotected void write(AtmosphereResourceEvent event,ServletOutputStream o,byte[] data);\\nprotected boolean useTwoStepWrite(AtmosphereResourceEvent event);\\nfinal void postStateChange(AtmosphereResourceEvent event);\\npublic void destroy();\\npublic void init(AtmosphereConfig config);\\npublic void onRequest(AtmosphereResource resource);\\n }\\npublic interface ReflectorServletProcessor { void loadWebApplication(ServletConfig sc);\\npublic void onRequest(AtmosphereResource r);\\npublic void init(AtmosphereConfig config);\\npublic void addFilter(Filter filter);\\npublic void destroy();\\npublic String getServletClass();\\npublic void setServletClass(String servletClass);\\npublic String getServletClassName();\\npublic void setServletClassName(String servletClass);\\npublic void setFilterClassName(String filterClass);\\npublic void addFilterClassName(String filterClass,String filterName);\\npublic Servlet getServlet();\\npublic void setServlet(Servlet servlet);\\npublic void destroy();\\npublic String getInitParameter(String name);\\npublic Enumeration getInitParameterNames();\\npublic ServletConfig getServletConfig();\\npublic ServletContext getServletContext();\\npublic String getServletInfo();\\npublic void init(ServletConfig sc);\\npublic void init();\\npublic void log(String msg);\\npublic void log(String message,Throwable t);\\npublic void service(ServletRequest req,ServletResponse res);\\npublic String getServletName();\\npublic String toString();\\n }\\npublic interface InjectableObjectFactory {public void configure(AtmosphereConfig config);\\npublic void started(AtmosphereFramework framework);\\nprotected void retryInjection(AtmosphereFramework framework);\\npublic U newClassInstance(Class classType,Class defaultType);\\npublic T inject(T instance);\\npublic void applyMethods(U instance,Class defaultType);\\npublic void injectInjectable(U instance,Class defaultType,AtmosphereFramework framework);\\npublic void injectFields(Set fields,U instance,AtmosphereFramework framework,LinkedList injectable);\\npublic AtmosphereObjectFactory allowInjectionOf(Injectable injectable);\\npublic AtmosphereObjectFactory allowInjectionOf(Injectable injectable,boolean first);\\npublic String toString();\\npublic U getInjectable(Class u);\\npublic void requestScoped(Object instance,Class defaultType,AtmosphereResource r);\\npublic void requestScoped(Object instance,Class defaultType);\\npublic boolean needRequestScoped(Class defaultType);\\npublic InjectableObjectFactory listener(InjectionListener i);\\nprotected void injectionFailed();\\nprotected void nullFieldInjectionFor(Field field,U instance,Class clazz);\\nprotected void fieldInjectionException(Field field,U instance,Class clazz,Exception ex);\\nprotected void methodInjectionException(Method m,U instance,Class clazz,Exception ex);\\nprotected void preFieldInjection(Field field,U instance,Class clazz);\\nprotected void postFieldInjection(Field field,U instance,Class clazz);\\nprotected void preMethodInjection(Method method,U instance,Class clazz);\\nprotected void postMethodInjection(Method method,U instance,Class clazz);\\n }\\npublic interface AndroidAtmosphereInterceptor {public Action inspect(AtmosphereResource r);\\npublic void prePayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic void postPayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic String toString();\\n }\\npublic interface CacheHeadersInterceptor {public void configure(AtmosphereConfig config);\\npublic Action inspect(AtmosphereResource r);\\npublic boolean injectCacheHeaders();\\npublic boolean writeHeaders();\\npublic CacheHeadersInterceptor injectCacheHeaders(boolean injectCacheHeaders);\\npublic CacheHeadersInterceptor writeHeaders(boolean writeHeaders);\\npublic String toString();\\n }\\npublic interface CorsInterceptor {public void configure(AtmosphereConfig config);\\npublic Action inspect(AtmosphereResource r);\\npublic boolean enableAccessControl();\\npublic CorsInterceptor enableAccessControl(boolean enableAccessControl);\\npublic PRIORITY priority();\\npublic String toString();\\n }\\npublic interface HeartbeatInterceptor {public HeartbeatInterceptor paddingText(byte[] paddingBytes);\\npublic byte[] getPaddingBytes();\\npublic HeartbeatInterceptor heartbeatFrequencyInSeconds(int heartbeatFrequencyInSeconds);\\npublic int heartbeatFrequencyInSeconds();\\npublic int clientHeartbeatFrequencyInSeconds();\\npublic HeartbeatInterceptor clientHeartbeatFrequencyInSeconds(int clientHeartbeatFrequencyInSeconds);\\npublic boolean resumeOnHeartbeat();\\npublic HeartbeatInterceptor resumeOnHeartbeat(boolean resumeOnHeartbeat);\\npublic void configure(AtmosphereConfig config);\\npublic Action inspect(AtmosphereResource r);\\npublic void onHeartbeat(AtmosphereResourceEvent event);\\npublic void onSuspend(AtmosphereResourceEvent event);\\npublic void onResume(AtmosphereResourceEvent event);\\npublic void onDisconnect(AtmosphereResourceEvent event);\\npublic void onClose(AtmosphereResourceEvent event);\\npublic byte[] transformPayload(AtmosphereResponse response,byte[] responseDraft,byte[] data);\\npublic void postPayload(AtmosphereResponse response,byte[] data,int offset,int length);\\nprotected int extractHeartbeatInterval(AtmosphereResourceImpl resource);\\n void cancelF(AtmosphereRequest request);\\npublic HeartbeatInterceptor clock(int interval,AtmosphereResource r,AtmosphereRequest request,AtmosphereResponse response);\\npublic String toString();\\npublic void destroy();\\n }\\npublic interface IdleResourceInterceptor {public void configure(AtmosphereConfig config);\\nprotected void idleResources();\\npublic long maxInactiveTime();\\npublic IdleResourceInterceptor maxInactiveTime(long maxInactiveTime);\\npublic Action inspect(AtmosphereResource r);\\npublic PRIORITY priority();\\npublic void destroy();\\n }\\npublic interface InvokationOrder { PRIORITY priority();\\n }\\npublic interface JSONPAtmosphereInterceptor {public void configure(AtmosphereConfig config);\\npublic Action inspect(AtmosphereResource r);\\n String callbackName();\\npublic void prePayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic byte[] transformPayload(AtmosphereResponse response,byte[] responseDraft,byte[] data);\\npublic void postPayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic String toString();\\n }\\npublic interface JavaScriptProtocol {public void configure(AtmosphereConfig config);\\npublic Action inspect(AtmosphereResource ar);\\npublic void onSuspend(AtmosphereResourceEvent event);\\npublic String wsDelimiter();\\npublic JavaScriptProtocol wsDelimiter(String wsDelimiter);\\npublic boolean enforceAtmosphereVersion();\\npublic JavaScriptProtocol enforceAtmosphereVersion(boolean enforceAtmosphereVersion);\\npublic String toString();\\n }\\npublic interface OnDisconnectInterceptor {public void configure(AtmosphereConfig config);\\npublic Action inspect(AtmosphereResource r);\\npublic String toString();\\n }\\npublic interface PaddingAtmosphereInterceptor {static String confPadding(int size);\\npublic Action inspect(AtmosphereResource r);\\npublic void prePayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic void postPayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic String toString();\\npublic void onPreSuspend(AtmosphereResourceEvent event);\\n }\\npublic interface SSEAtmosphereInterceptor {public void configure(AtmosphereConfig config);\\npublic void onPreSuspend(AtmosphereResourceEvent event);\\npublic Action inspect(AtmosphereResource r);\\npublic void prePayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic byte[] transformPayload(AtmosphereResponse response,byte[] responseDraft,byte[] data);\\npublic void postPayload(AtmosphereResponse response,byte[] data,int offset,int length);\\npublic String toString();\\n }\\npublic interface WebSocketMessageSuspendInterceptor {public Action inspect(AtmosphereResource r);\\n }\\npublic interface AtmosphereConfigReader {public AtmosphereConfig parse(AtmosphereConfig config,String filename);\\npublic AtmosphereConfig parse(AtmosphereConfig config,InputStream stream);\\nstatic AtmosphereConfigReader getInstance();\\n }\\npublic interface DefaultEndpointMapper {protected U match(String path,Map handlers);\\npublic String computePath(AtmosphereRequest req);\\npublic void configure(AtmosphereConfig config);\\npublic U map(AtmosphereRequest req,Map handlers);\\npublic U map(String path,Map handlers);\\n }\\npublic interface DefaultUUIDProvider {public String generateUuid();\\n }\\npublic interface EndpointMapper { U map(AtmosphereRequest req,Map handlers);\\n U map(String path,Map handlers);\\n }\\npublic interface ExecutorsFactory {public Thread newThread(Runnable runnable);\\nstatic ExecutorService getMessageDispatcher(AtmosphereConfig config,String name);\\nstatic ExecutorService getAsyncOperationExecutor(AtmosphereConfig config,String name);\\nstatic ScheduledExecutorService getScheduler(AtmosphereConfig config);\\npublic Thread newThread(Runnable runnable);\\nstatic void reset(AtmosphereConfig config);\\n }\\npublic interface IOUtils {static void deliver(Object o,DeliverTo deliverConfig,DELIVER_TO defaultDeliver,AtmosphereResource r);\\nstatic Object readEntirely(AtmosphereResource r);\\nstatic boolean isBodyBinary(AtmosphereRequest request);\\nstatic boolean isBodyEmpty(Object o);\\nstatic StringBuilder readEntirelyAsString(AtmosphereResource r);\\nstatic byte[] readEntirelyAsByte(AtmosphereResource r);\\nstatic byte[] forceReadEntirelyAsByte(AtmosphereResource r);\\nstatic String guestServletPath(AtmosphereConfig config);\\nstatic String guestRawServletPath(AtmosphereConfig config);\\nstatic String getCleanedServletPath(String fullServletPath);\\nstatic Class loadClass(Class thisClass,String className);\\nstatic boolean isAtmosphere(String className);\\nstatic Map readServiceFile(String path);\\nstatic void close(Closeable closeableArray);\\nstatic String realPath(ServletContext servletContext,String targetPath);\\n }\\npublic interface IntrospectionUtils {static void execute(Object proxy,String method);\\nstatic void setAttribute(Object proxy,String name,Object value);\\nstatic Object getAttribute(Object proxy,String name);\\nstatic boolean setProperty(Object o,String name,String value);\\nstatic boolean addProperty(Object o,String name,String value);\\npublic boolean invokeProperty(Object object,String setter,String name,String value);\\nstatic Object getProperty(Object object,String name);\\nstatic void setProperty(Object object,String name);\\nstatic String replaceProperties(String value,Hashtable staticProp,PropertySource dynamicProp);\\nstatic String capitalize(String name);\\nstatic String unCapitalize(String name);\\nstatic void addToClassPath(Vector cpV,String dir);\\nstatic void addToolsJar(Vector v);\\nstatic String[] getFilesByExt(String ld,String ext);\\npublic boolean accept(File d,String name);\\nstatic URL getURL(String base,String file);\\nstatic void addJarsFromClassPath(Vector jars,String cp);\\nstatic URL[] getClassPath(Vector v);\\nstatic URL[] getClassPath(String dir,String cpath,String cpathProp,boolean addTools);\\nstatic boolean processArgs(Object proxy,String args);\\nstatic boolean processArgs(Object proxy,String args,String args0,String args1,Hashtable aliases);\\nstatic void clear();\\nstatic String[] findVoidSetters(Class c);\\nstatic String[] findBooleanSetters(Class c);\\nstatic Method[] findMethods(Class c);\\nstatic Method findMethod(Class c,String name,Class params);\\nstatic boolean hasHook(Object obj,String methodN);\\nstatic void callMain(Class c,String args);\\nstatic Object callMethod1(Object target,String methodN,Object param1,String typeParam1,ClassLoader cl);\\nstatic Object callMethod0(Object target,String methodN);\\nstatic Object callMethodN(Object target,String methodN,Object params,Class typeParams);\\nstatic Object convert(String object,Class paramType);\\npublic String getProperty(String key);\\npublic void setAttribute(String key,Object o);\\nstatic void debug(String s);\\n }\\npublic interface ServletContextFactory {public void init(ServletContext servletContext);\\npublic ServletContext getServletContext();\\nstatic ServletContextFactory getDefault();\\n }\\npublic interface UUIDProvider { String generateUuid();\\n }\\npublic interface Utils {static boolean webSocketEnabled(HttpServletRequest request);\\nstatic boolean rawWebSocket(HttpServletRequest request);\\nstatic boolean firefoxWebSocketEnabled(HttpServletRequest request);\\nstatic boolean twoConnectionsTransport(TRANSPORT t);\\nstatic boolean webSocketQueryStringPresentOrNull(HttpServletRequest request);\\nstatic boolean resumableTransport(TRANSPORT t);\\nstatic boolean pollableTransport(TRANSPORT t);\\nstatic boolean pushMessage(TRANSPORT t);\\nstatic boolean atmosphereProtocol(AtmosphereRequest r);\\nstatic boolean webSocketMessage(AtmosphereResource r);\\nstatic boolean properProtocol(HttpServletRequest request);\\nstatic AtmosphereResource websocketResource(AtmosphereResource r);\\nstatic boolean closeMessage(HttpServletRequest request);\\nstatic Object invoke(Object proxiedInstance,Method m,Object o);\\nstatic void inject(AtmosphereResource r);\\nstatic void inject(Object object,Class clazz,AtmosphereResource r);\\nstatic void inject(Object object,Class clazz,AtmosphereConfig config);\\nstatic Set getInheritedPrivateFields(Class type);\\nstatic Set getInheritedPrivateMethod(Class type);\\nstatic boolean requestScopedInjection(AtmosphereConfig config,AtmosphereHandler h);\\nstatic boolean requestScopedInjection(AtmosphereConfig config,Object o);\\nstatic void destroyMeteor(AtmosphereRequest req);\\nstatic String pathInfo(AtmosphereRequest request);\\nstatic boolean isRunningTest();\\nstatic boolean isUnderJDK11AndUp();\\n }\\npublic interface Version {static void main(String[] args);\\nstatic String getRawVersion();\\nstatic String getDotedVersion();\\nstatic int getMajorVersion();\\nstatic int getMinorVersion();\\nstatic int getMicroVersion();\\nstatic boolean equalVersion(int major,int minor);\\n }\\npublic interface VoidServletConfig {public String getServletName();\\npublic ServletContext getServletContext();\\npublic String getInitParameter(String name);\\npublic Enumeration getInitParameterNames();\\n }\\npublic interface FocusPoint {public String getName();\\npublic void setParentTrackPoint(FocusPoint parentFocusPoint);\\npublic FocusPoint getParentFocusPoint();\\npublic String getContentURI();\\npublic String getContentTitle();\\n }\\npublic interface JGoogleAnalyticsTracker {public void setUrlBuildingStrategy(URLBuildingStrategy urlBuildingStrategy);\\npublic void trackSynchronously(FocusPoint focusPoint);\\n }\\npublic interface ModuleDetection {static String detect();\\nstatic boolean check(String clazz);\\n }\\npublic interface DefaultWebSocketFactory {public WebSocket find(String uuid);\\n }\\npublic interface DefaultWebSocketProcessor {public WebSocketProcessor configure(AtmosphereConfig config);\\npublic Action service(AtmosphereRequest req,AtmosphereResponse res);\\npublic boolean handshake(HttpServletRequest request);\\npublic WebSocketProcessor registerWebSocketHandler(String path,WebSocketHandlerProxy webSockethandler);\\nfinal void open(WebSocket webSocket,AtmosphereRequest request,AtmosphereResponse response);\\nprotected WebSocketHandler postProcessMapping(WebSocket webSocket,AtmosphereRequest request,WebSocketHandlerProxy w);\\npublic void invokeWebSocketProtocol(WebSocket webSocket,String webSocketMessage);\\npublic void invokeWebSocketProtocol(WebSocket webSocket,byte[] data,int offset,int length);\\npublic void invokeWebSocketProtocol(WebSocket webSocket,InputStream stream);\\npublic void invokeWebSocketProtocol(WebSocket webSocket,Reader reader);\\nfinal void dispatch(WebSocket webSocket,AtmosphereRequest request,AtmosphereResponse r);\\npublic void close(WebSocket webSocket,int closeCode);\\npublic void executeClose(WebSocket webSocket,int closeCode);\\npublic void destroy();\\npublic void notifyListener(WebSocket webSocket,WebSocketEventListener.WebSocketEvent event);\\nstatic Map configureHeader(AtmosphereRequest request);\\nprotected void dispatchStream(WebSocket webSocket,InputStream is);\\nprotected void dispatchReader(WebSocket webSocket,Reader r);\\nprotected void optimizeMapping();\\npublic boolean wildcardMapping();\\npublic DefaultWebSocketProcessor wildcardMapping(boolean wildcardMapping);\\npublic Map handlers();\\npublic boolean executeAsync();\\npublic boolean destroyable();\\npublic int byteBufferMaxSize();\\npublic DefaultWebSocketProcessor byteBufferMaxSize(int byteBufferMaxSize);\\npublic int charBufferMaxSize();\\npublic DefaultWebSocketProcessor charBufferMaxSize(int charBufferMaxSize);\\npublic long closingTime();\\npublic EndpointMapper mapper();\\npublic boolean invokeInterceptors();\\npublic void onPong(WebSocket webSocket,byte[] payload,int offset,int length);\\npublic void onPing(WebSocket webSocket,byte[] payload,int offset,int length);\\n }\\npublic interface WebSocket {public AtmosphereConfig config();\\nprotected WebSocket webSocketHandler(WebSocketHandler webSocketHandler);\\npublic WebSocket binaryWrite(boolean binaryWrite);\\npublic WebSocketHandler webSocketHandler();\\npublic WebSocket resource(AtmosphereResource r);\\nsynchronized void shiftAttributes();\\npublic Map attributes();\\npublic AtmosphereResource resource();\\npublic long lastWriteTimeStampInMilliseconds();\\nprotected byte[] transform(byte[] b,int offset,int length);\\nprotected byte[] transform(AtmosphereResponse response,byte[] b,int offset,int length);\\npublic WebSocket write(AtmosphereResponse r,String data);\\npublic WebSocket write(AtmosphereResponse r,byte[] data);\\npublic WebSocket write(AtmosphereResponse r,byte[] b,int offset,int length);\\npublic WebSocket broadcast(Object o);\\npublic WebSocket writeError(AtmosphereResponse r,int errorCode,String message);\\npublic WebSocket redirect(AtmosphereResponse r,String location);\\npublic void close(AtmosphereResponse r);\\npublic WebSocket flush(AtmosphereResponse r);\\npublic boolean isOpen();\\npublic WebSocket write(String s);\\npublic WebSocket write(byte[] b,int offset,int length);\\npublic WebSocket write(byte[] b);\\npublic void close();\\npublic void close(int statusCode,String reasonText);\\npublic String uuid();\\nstatic void notSupported(AtmosphereRequest request,AtmosphereResponse response);\\npublic WebSocket sendPing(byte[] payload);\\npublic WebSocket sendPong(byte[] payload);\\npublic WebSocket attachment(Object attachment);\\npublic Object attachment();\\n }\\npublic interface WebSocketFactory { WebSocket find(String uuid);\\n }\\npublic interface WebSocketHandler { void onByteMessage(WebSocket webSocket,byte[] data,int offset,int length);\\n void onTextMessage(WebSocket webSocket,String data);\\n void onOpen(WebSocket webSocket);\\n void onClose(WebSocket webSocket);\\n void onError(WebSocket webSocket,WebSocketException t);\\n }\\npublic interface WebSocketProcessor { WebSocketProcessor configure(AtmosphereConfig config);\\n boolean handshake(HttpServletRequest request);\\n WebSocketProcessor registerWebSocketHandler(String path,WebSocketHandlerProxy webSockethandler);\\n void open(WebSocket webSocket,AtmosphereRequest request,AtmosphereResponse response);\\n void invokeWebSocketProtocol(WebSocket webSocket,String webSocketMessage);\\n void invokeWebSocketProtocol(WebSocket webSocket,byte[] data,int offset,int length);\\n void invokeWebSocketProtocol(WebSocket webSocket,InputStream stream);\\n void invokeWebSocketProtocol(WebSocket webSocket,Reader reader);\\n void close(WebSocket webSocket,int closeCode);\\n void notifyListener(WebSocket webSocket,WebSocketEvent webSocketEvent);\\n void destroy();\\npublic AtmosphereResponse response();\\npublic String path();\\npublic WebSocketHandlerProxy path(String path);\\npublic WebSocketHandler proxied();\\npublic void onByteMessage(WebSocket webSocket,byte[] data,int offset,int length);\\npublic void onTextMessage(WebSocket webSocket,String data);\\npublic void onOpen(WebSocket webSocket);\\npublic void onClose(WebSocket webSocket);\\npublic void onError(WebSocket webSocket,WebSocketException t);\\n }\\npublic interface WebSocketProtocol { List onMessage(WebSocket webSocket,String data);\\n List onMessage(WebSocket webSocket,byte[] data,int offset,int length);\\n void onOpen(WebSocket webSocket);\\n void onClose(WebSocket webSocket);\\n void onError(WebSocket webSocket,WebSocketException t);\\n }\\npublic interface SimpleHttpProtocol {public void configure(AtmosphereConfig config);\\npublic List onMessage(WebSocket webSocket,String message);\\npublic List onMessage(WebSocket webSocket,byte[] d,int offset,int length);\\npublic void onOpen(WebSocket webSocket);\\npublic void onClose(WebSocket webSocket);\\npublic void onError(WebSocket webSocket,WebSocketException t);\\n }\\n\" }", "class_name": "AtmosphereFramework", "code": "private boolean checkDuplicate(final List interceptorList,Class c){\n for ( final AtmosphereInterceptor i : interceptorList) {\n if (i.getClass().equals(c)) {\n return true;\n }\n }\n return false;\n}\n", "docstring": "/** \n *

      Checks in the specified list if there is at least one instance of the given {@link AtmosphereInterceptor interceptor} implementation class.

      \n * @param interceptorList the interceptors\n * @param c the interceptor class\n * @return {@code false} if an instance of the class already exists in the list, {@code true} otherwise\n */\n", "end_lineno": "2683", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\npackage org.atmosphere.cpr;\n\nimport org.atmosphere.annotation.Processor;\nimport org.atmosphere.cache.BroadcasterCacheInspector;\nimport org.atmosphere.cache.DefaultBroadcasterCache;\nimport org.atmosphere.cache.UUIDBroadcasterCache;\nimport org.atmosphere.config.ApplicationConfiguration;\nimport org.atmosphere.config.AtmosphereHandlerConfig;\nimport org.atmosphere.config.AtmosphereHandlerProperty;\nimport org.atmosphere.config.FrameworkConfiguration;\nimport org.atmosphere.container.BlockingIOCometSupport;\nimport org.atmosphere.container.Tomcat7BIOSupportWithWebSocket;\nimport org.atmosphere.container.WebLogicServlet30WithWebSocket;\nimport org.atmosphere.handler.AbstractReflectorAtmosphereHandler;\nimport org.atmosphere.handler.ReflectorServletProcessor;\nimport org.atmosphere.inject.InjectableObjectFactory;\nimport org.atmosphere.interceptor.AndroidAtmosphereInterceptor;\nimport org.atmosphere.interceptor.CacheHeadersInterceptor;\nimport org.atmosphere.interceptor.CorsInterceptor;\nimport org.atmosphere.interceptor.HeartbeatInterceptor;\nimport org.atmosphere.interceptor.IdleResourceInterceptor;\nimport org.atmosphere.interceptor.InvokationOrder;\nimport org.atmosphere.interceptor.JSONPAtmosphereInterceptor;\nimport org.atmosphere.interceptor.JavaScriptProtocol;\nimport org.atmosphere.interceptor.OnDisconnectInterceptor;\nimport org.atmosphere.interceptor.PaddingAtmosphereInterceptor;\nimport org.atmosphere.interceptor.SSEAtmosphereInterceptor;\nimport org.atmosphere.interceptor.WebSocketMessageSuspendInterceptor;\nimport org.atmosphere.util.AtmosphereConfigReader;\nimport org.atmosphere.util.DefaultEndpointMapper;\nimport org.atmosphere.util.DefaultUUIDProvider;\nimport org.atmosphere.util.EndpointMapper;\nimport org.atmosphere.util.ExecutorsFactory;\nimport org.atmosphere.util.IOUtils;\nimport org.atmosphere.util.IntrospectionUtils;\nimport org.atmosphere.util.ServletContextFactory;\nimport org.atmosphere.util.UUIDProvider;\nimport org.atmosphere.util.Utils;\nimport org.atmosphere.util.Version;\nimport org.atmosphere.util.VoidServletConfig;\nimport org.atmosphere.util.analytics.FocusPoint;\nimport org.atmosphere.util.analytics.JGoogleAnalyticsTracker;\nimport org.atmosphere.util.analytics.ModuleDetection;\nimport org.atmosphere.websocket.DefaultWebSocketFactory;\nimport org.atmosphere.websocket.DefaultWebSocketProcessor;\nimport org.atmosphere.websocket.WebSocket;\nimport org.atmosphere.websocket.WebSocketFactory;\nimport org.atmosphere.websocket.WebSocketHandler;\nimport org.atmosphere.websocket.WebSocketProcessor;\nimport org.atmosphere.websocket.WebSocketProtocol;\nimport org.atmosphere.websocket.protocol.SimpleHttpProtocol;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.servlet.Servlet;\nimport javax.servlet.ServletConfig;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.UnsupportedEncodingException;\nimport java.net.HttpURLConnection;\nimport java.net.MalformedURLException;\nimport java.net.URI;\nimport java.net.URL;\nimport java.net.URLClassLoader;\nimport java.net.URLDecoder;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Objects;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\nimport static org.atmosphere.cpr.ApplicationConfig.ALLOW_QUERYSTRING_AS_REQUEST;\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER;\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER_MAPPING;\nimport static org.atmosphere.cpr.ApplicationConfig.ATMOSPHERE_HANDLER_PATH;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CACHE;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_CLASS;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_FACTORY;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_LIFECYCLE_POLICY;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_SHAREABLE_LISTENERS;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCASTER_WAIT_TIME;\nimport static org.atmosphere.cpr.ApplicationConfig.BROADCAST_FILTER_CLASSES;\nimport static org.atmosphere.cpr.ApplicationConfig.CONTENT_TYPE_FIRST_RESPONSE;\nimport static org.atmosphere.cpr.ApplicationConfig.DISABLE_ONSTATE_EVENT;\nimport static org.atmosphere.cpr.ApplicationConfig.META_SERVICE_PATH;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_ALLOW_SESSION_TIMEOUT_REMOVAL;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_ATMOSPHERE_XML;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_BLOCKING_COMETSUPPORT;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_COMET_SUPPORT;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_NATIVE_COMETSUPPORT;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SERVLET_MAPPING;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SESSION_SUPPORT;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_THROW_EXCEPTION_ON_CLONED_REQUEST;\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_USE_STREAM;\nimport static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID;\nimport static org.atmosphere.cpr.ApplicationConfig.USE_SERVLET_CONTEXT_PARAMETERS;\nimport static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROCESSOR;\nimport static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_PROTOCOL;\nimport static org.atmosphere.cpr.ApplicationConfig.WEBSOCKET_SUPPORT;\nimport static org.atmosphere.cpr.Broadcaster.ROOT_MASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.ATMOSPHERE_CONFIG;\nimport static org.atmosphere.cpr.FrameworkConfig.CDI_INJECTOR;\nimport static org.atmosphere.cpr.FrameworkConfig.GUICE_INJECTOR;\nimport static org.atmosphere.cpr.FrameworkConfig.HAZELCAST_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.INJECT_LIBARY;\nimport static org.atmosphere.cpr.FrameworkConfig.JERSEY_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.JERSEY_CONTAINER;\nimport static org.atmosphere.cpr.FrameworkConfig.JGROUPS_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.JMS_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.KAFKA_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.RABBITMQ_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.REDIS_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.RMI_BROADCASTER;\nimport static org.atmosphere.cpr.FrameworkConfig.SPRING_INJECTOR;\nimport static org.atmosphere.cpr.FrameworkConfig.THROW_EXCEPTION_ON_CLONED_REQUEST;\nimport static org.atmosphere.cpr.FrameworkConfig.XMPP_BROADCASTER;\nimport static org.atmosphere.cpr.HeaderConfig.ATMOSPHERE_POST_BODY;\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_TRACKING_ID;\nimport static org.atmosphere.util.IOUtils.realPath;\nimport static org.atmosphere.websocket.WebSocket.WEBSOCKET_SUSPEND;\n\n/**\n * The {@link AtmosphereFramework} is the entry point for the framework. This class can be used to from Servlet/filter\n * to dispatch {@link AtmosphereRequest} and {@link AtmosphereResponse}. The framework can also be configured using\n * the setXXX method. The life cycle of this class is\n *
      \n * AtmosphereFramework f = new AtmosphereFramework();\n * f.init();\n * f.doCometSupport(AtmosphereRequest, AtmosphereResource);\n * f.destroy();\n * 
      \n *\n * @author Jeanfrancois Arcand\n */\npublic class AtmosphereFramework {\n\n public static final String DEFAULT_ATMOSPHERE_CONFIG_PATH = \"/META-INF/atmosphere.xml\";\n public static final String DEFAULT_LIB_PATH = \"/WEB-INF/lib/\";\n public static final String DEFAULT_HANDLER_PATH = \"/WEB-INF/classes/\";\n public static final String META_SERVICE = \"META-INF/services/\";\n public static final String MAPPING_REGEX = \"[a-zA-Z0-9-&.*_~=@;\\\\?]+\";\n public static final String ASYNC_IO = \"io.async\";\n\n protected static final Logger logger = LoggerFactory.getLogger(AtmosphereFramework.class);\n\n protected final List broadcasterFilters = new ArrayList<>();\n protected final List asyncSupportListeners = new ArrayList<>();\n protected final List atmosphereResourceListeners = new ArrayList<>();\n protected final ArrayList possibleComponentsCandidate = new ArrayList<>();\n protected final HashMap initParams = new HashMap<>();\n protected final AtmosphereConfig config;\n protected final AtomicBoolean isCometSupportConfigured = new AtomicBoolean(false);\n protected final boolean isFilter;\n protected final Map atmosphereHandlers = new ConcurrentHashMap<>();\n protected final ConcurrentLinkedQueue broadcasterTypes = new ConcurrentLinkedQueue<>();\n protected final ConcurrentLinkedQueue objectFactoryType = new ConcurrentLinkedQueue<>();\n protected final ConcurrentLinkedQueue inspectors = new ConcurrentLinkedQueue<>();\n\n protected String mappingRegex = MAPPING_REGEX;\n protected boolean useNativeImplementation;\n protected boolean useBlockingImplementation;\n protected boolean useStreamForFlushingComments = true;\n protected boolean useServlet30 = true;\n protected AsyncSupport asyncSupport;\n protected String broadcasterClassName = DefaultBroadcaster.class.getName();\n protected boolean isCometSupportSpecified;\n protected boolean isBroadcasterSpecified;\n protected boolean isSessionSupportSpecified;\n protected boolean isThrowExceptionOnClonedRequestSpecified;\n protected BroadcasterFactory broadcasterFactory;\n protected String broadcasterFactoryClassName;\n protected String broadcasterCacheClassName;\n protected boolean webSocketEnabled = true;\n protected String broadcasterLifeCyclePolicy = \"NEVER\";\n protected String webSocketProtocolClassName = SimpleHttpProtocol.class.getName();\n protected WebSocketProtocol webSocketProtocol;\n protected String handlersPath = DEFAULT_HANDLER_PATH;\n protected ServletConfig servletConfig;\n protected boolean autoDetectHandlers = true;\n private boolean hasNewWebSocketProtocol;\n protected String atmosphereDotXmlPath = DEFAULT_ATMOSPHERE_CONFIG_PATH;\n protected String metaServicePath = META_SERVICE;\n protected final LinkedList interceptors = new LinkedList<>();\n protected boolean scanDone;\n protected String annotationProcessorClassName = \"org.atmosphere.cpr.DefaultAnnotationProcessor\";\n protected final List broadcasterListeners = Collections.synchronizedList(new ArrayList<>());\n protected String webSocketProcessorClassName = DefaultWebSocketProcessor.class.getName();\n protected boolean webSocketProtocolInitialized;\n protected EndpointMapper endpointMapper = new DefaultEndpointMapper<>();\n protected String libPath = DEFAULT_LIB_PATH;\n protected boolean isInit;\n protected boolean sharedThreadPools = true;\n protected final List packages = new ArrayList<>();\n protected final LinkedList annotationPackages = new LinkedList<>();\n protected boolean allowAllClassesScan = true;\n protected boolean annotationFound;\n protected boolean executeFirstSet;\n protected AtmosphereObjectFactory objectFactory = new DefaultAtmosphereObjectFactory();\n protected final AtomicBoolean isDestroyed = new AtomicBoolean();\n protected boolean externalizeDestroy;\n protected AnnotationProcessor annotationProcessor;\n protected final List excludedInterceptors = new ArrayList<>();\n protected final LinkedList broadcasterCacheListeners = new LinkedList<>();\n protected final List filterManipulators = new ArrayList<>();\n protected AtmosphereResourceFactory arFactory;\n protected MetaBroadcaster metaBroadcaster;\n protected AtmosphereResourceSessionFactory sessionFactory;\n protected String defaultSerializerClassName;\n protected Class defaultSerializerClass;\n protected final List frameworkListeners = new LinkedList<>();\n private UUIDProvider uuidProvider = new DefaultUUIDProvider();\n protected Thread shutdownHook;\n public static final List> DEFAULT_ATMOSPHERE_INTERCEPTORS = new LinkedList>() {\n {\n // Add CORS support\n add(CorsInterceptor.class);\n // Default Interceptor\n add(CacheHeadersInterceptor.class);\n // WebKit & IE Padding\n add(PaddingAtmosphereInterceptor.class);\n // Android 2.3.x streaming support\n add(AndroidAtmosphereInterceptor.class);\n // Heartbeat\n add(HeartbeatInterceptor.class);\n // Add SSE support\n add(SSEAtmosphereInterceptor.class);\n // ADD JSONP support\n add(JSONPAtmosphereInterceptor.class);\n // ADD Tracking ID Handshake\n add(JavaScriptProtocol.class);\n // WebSocket and suspend\n add(WebSocketMessageSuspendInterceptor.class);\n // OnDisconnect\n add(OnDisconnectInterceptor.class);\n // Idle connection\n add(IdleResourceInterceptor.class);\n }\n };\n private WebSocketFactory webSocketFactory;\n private IllegalStateException initializationError;\n\n /**\n * An implementation of {@link AbstractReflectorAtmosphereHandler}.\n */\n public final static AtmosphereHandler REFLECTOR_ATMOSPHEREHANDLER = new AbstractReflectorAtmosphereHandler() {\n @Override\n public void onRequest(AtmosphereResource resource) {\n logger.trace(\"VoidHandler {}\", resource.uuid());\n }\n\n @Override\n public void destroy() {\n logger.trace(\"VoidHandler\");\n }\n };\n\n public void setAndConfigureAtmosphereResourceFactory(AtmosphereResourceFactory arFactory) {\n this.arFactory = arFactory;\n this.arFactory.configure(config);\n }\n\n public static final class AtmosphereHandlerWrapper {\n\n public final AtmosphereHandler atmosphereHandler;\n public Broadcaster broadcaster;\n public String mapping;\n public final LinkedList interceptors = new LinkedList<>();\n public boolean create;\n private boolean needRequestScopedInjection;\n private final boolean wilcardMapping;\n\n public AtmosphereHandlerWrapper(BroadcasterFactory broadcasterFactory, final AtmosphereHandler atmosphereHandler, String mapping,\n final AtmosphereConfig config) {\n this.atmosphereHandler = atmosphereHandler;\n\n try {\n if (broadcasterFactory != null) {\n this.broadcaster = broadcasterFactory.lookup(mapping, true);\n } else {\n this.mapping = mapping;\n }\n } catch (Exception t) {\n throw new RuntimeException(t);\n }\n wilcardMapping = mapping.contains(\"{\") && mapping.contains(\"}\");\n hookInjection(config);\n }\n\n void hookInjection(final AtmosphereConfig config) {\n config.startupHook(framework -> needRequestScopedInjection = Utils.requestScopedInjection(config, atmosphereHandler));\n }\n\n public AtmosphereHandlerWrapper(final AtmosphereHandler atmosphereHandler, Broadcaster broadcaster,\n final AtmosphereConfig config) {\n this.atmosphereHandler = atmosphereHandler;\n this.broadcaster = broadcaster;\n hookInjection(config);\n wilcardMapping = false;\n }\n\n @Override\n public String toString() {\n\n StringBuilder b = new StringBuilder();\n for (int i = 0; i < interceptors.size(); i++) {\n b.append(\"\\n\\t\").append(i).append(\": \").append(interceptors.get(i).getClass().getName());\n }\n\n return \"\\n atmosphereHandler\"\n + \"\\n\\t\" + atmosphereHandler\n + \"\\n interceptors\" +\n b.toString()\n + \"\\n broadcaster\"\n + \"\\t\" + broadcaster;\n }\n\n public boolean needRequestScopedInjection() {\n return needRequestScopedInjection;\n }\n\n public boolean wildcardMapping() {\n return wilcardMapping;\n }\n }\n\n /**\n *

      \n * This enumeration represents all possible actions to specify in a meta service file.\n *

      \n *\n * @author Guillaume DROUET\n * @version 1.0\n * @since 2.2.0\n */\n public enum MetaServiceAction {\n\n /**\n * Install service.\n */\n INSTALL(new InstallMetaServiceProcedure()),\n\n /**\n * Exclude service.\n */\n EXCLUDE(new ExcludeMetaServiceProcedure());\n\n /**\n * The procedure to apply.\n */\n private MetaServiceProcedure procedure;\n\n /**\n *

      \n * Builds a new instance.\n *

      \n *\n * @param p the enum procedure\n */\n MetaServiceAction(final MetaServiceProcedure p) {\n procedure = p;\n }\n\n /**\n *

      \n * Applies this action to given class.\n *

      \n *\n * @param fwk the framework\n * @param clazz the class\n * @throws Exception if procedure fails\n */\n public void apply(final AtmosphereFramework fwk, final Class clazz) throws Exception {\n procedure.apply(fwk, clazz);\n\n }\n\n /**\n *

      \n * This interface defined a method with a signature like a procedure to process an action.\n *

      \n *\n * @author Guillaume DROUET\n * @version 1.0\n * @since 2.2.0\n */\n private interface MetaServiceProcedure {\n\n /**\n *

      \n * Processes an action.\n *

      \n *\n * @param fwk the framework\n * @param clazz the class to use during processing\n * @throws Exception if procedure fails\n */\n void apply(final AtmosphereFramework fwk, final Class clazz) throws Exception;\n }\n\n /**\n *

      \n * Install the classes.\n *

      \n *\n * @author Guillaume DROUET\n * @version 1.0\n * @since 2.2.0\n */\n private static class InstallMetaServiceProcedure implements MetaServiceProcedure {\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void apply(final AtmosphereFramework fwk, final Class c) throws Exception {\n if (AtmosphereInterceptor.class.isAssignableFrom(c)) {\n fwk.interceptor(fwk.newClassInstance(AtmosphereInterceptor.class, c));\n } else if (Broadcaster.class.isAssignableFrom(c)) {\n fwk.setDefaultBroadcasterClassName(c.getName());\n } else if (BroadcasterListener.class.isAssignableFrom(c)) {\n fwk.addBroadcasterListener(fwk.newClassInstance(BroadcasterListener.class, c));\n } else if (BroadcasterCache.class.isAssignableFrom(c)) {\n fwk.setBroadcasterCacheClassName(c.getName());\n } else if (BroadcastFilter.class.isAssignableFrom(c)) {\n fwk.broadcasterFilters.add(c.getName());\n } else if (BroadcasterCacheInspector.class.isAssignableFrom(c)) {\n fwk.inspectors.add(fwk.newClassInstance(BroadcasterCacheInspector.class, c));\n } else if (AsyncSupportListener.class.isAssignableFrom(c)) {\n fwk.asyncSupportListeners.add(fwk.newClassInstance(AsyncSupportListener.class, c));\n } else if (AsyncSupport.class.isAssignableFrom(c)) {\n fwk.setAsyncSupport(fwk.newClassInstance(AsyncSupport.class, c));\n } else if (BroadcasterCacheListener.class.isAssignableFrom(c)) {\n fwk.broadcasterCacheListeners.add(fwk.newClassInstance(BroadcasterCacheListener.class, c));\n } else if (BroadcasterConfig.FilterManipulator.class.isAssignableFrom(c)) {\n fwk.filterManipulators.add(fwk.newClassInstance(BroadcasterConfig.FilterManipulator.class, c));\n } else if (WebSocketProtocol.class.isAssignableFrom(c)) {\n fwk.webSocketProtocolClassName = c.getName();\n } else if (WebSocketProcessor.class.isAssignableFrom(c)) {\n fwk.webSocketProcessorClassName = c.getName();\n } else if (AtmosphereResourceFactory.class.isAssignableFrom(c)) {\n fwk.setAndConfigureAtmosphereResourceFactory(fwk.newClassInstance(AtmosphereResourceFactory.class, c));\n } else if (AtmosphereFrameworkListener.class.isAssignableFrom(c)) {\n fwk.frameworkListener(fwk.newClassInstance(AtmosphereFrameworkListener.class, c));\n } else if (WebSocketFactory.class.isAssignableFrom(c)) {\n fwk.webSocketFactory(fwk.newClassInstance(WebSocketFactory.class, c));\n } else if (AtmosphereFramework.class.isAssignableFrom(c)) {\n // No OPS\n } else if (EndpointMapper.class.isAssignableFrom(c)) {\n fwk.endPointMapper(fwk.newClassInstance(EndpointMapper.class, c));\n } else {\n logger.warn(\"{} is not a framework service that could be installed\", c.getName());\n }\n }\n }\n\n /**\n *

      \n * Exclude the services.\n *

      \n *\n * @author Guillaume DROUET\n * @version 1.0\n * @since 2.2.0\n */\n private static class ExcludeMetaServiceProcedure implements MetaServiceProcedure {\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void apply(final AtmosphereFramework fwk, final Class c) {\n if (AtmosphereInterceptor.class.isAssignableFrom(c)) {\n fwk.excludeInterceptor(c.getName());\n } else {\n logger.warn(\"{} is not a framework service that could be excluded, pull request is welcome ;-)\", c.getName());\n }\n }\n }\n }\n\n public static class DefaultAtmosphereObjectFactory implements AtmosphereObjectFactory {\n public String toString() {\n return \"DefaultAtmosphereObjectFactory\";\n }\n\n @Override\n public void configure(AtmosphereConfig config) {\n }\n\n @Override\n public U newClassInstance(Class classType,\n Class defaultType) throws InstantiationException, IllegalAccessException {\n return defaultType.newInstance();\n }\n\n @Override\n public AtmosphereObjectFactory allowInjectionOf(java.lang.Object o) {\n return this;\n }\n }\n\n /**\n * Create an AtmosphereFramework.\n */\n public AtmosphereFramework() {\n this(false, true);\n }\n\n /**\n * Create an AtmosphereFramework and initialize it via {@link AtmosphereFramework#init(javax.servlet.ServletConfig)}.\n */\n public AtmosphereFramework(ServletConfig sc) throws ServletException {\n this(false, true);\n // TODO: What?\n init(sc);\n }\n\n /**\n * Create an AtmosphereFramework.\n *\n * @param isFilter true if this instance is used as an {@link AtmosphereFilter}\n */\n public AtmosphereFramework(boolean isFilter, boolean autoDetectHandlers) {\n this.isFilter = isFilter;\n this.autoDetectHandlers = autoDetectHandlers;\n config = newAtmosphereConfig();\n }\n\n /**\n * Create an instance of {@link org.atmosphere.cpr.AtmosphereConfig}\n */\n protected AtmosphereConfig newAtmosphereConfig() {\n return new AtmosphereConfig(this);\n }\n\n /**\n * The order of addition is quite important here.\n */\n private void populateBroadcasterType() {\n broadcasterTypes.add(KAFKA_BROADCASTER);\n broadcasterTypes.add(HAZELCAST_BROADCASTER);\n broadcasterTypes.add(XMPP_BROADCASTER);\n broadcasterTypes.add(REDIS_BROADCASTER);\n broadcasterTypes.add(JGROUPS_BROADCASTER);\n broadcasterTypes.add(JMS_BROADCASTER);\n broadcasterTypes.add(RMI_BROADCASTER);\n broadcasterTypes.add(RABBITMQ_BROADCASTER);\n }\n\n /**\n * The order of addition is quite important here.\n */\n private void populateObjectFactoryType() {\n objectFactoryType.add(CDI_INJECTOR);\n objectFactoryType.add(SPRING_INJECTOR);\n objectFactoryType.add(GUICE_INJECTOR);\n }\n\n /**\n * Add an {@link AtmosphereHandler} serviced by the {@link Servlet}\n * This API is exposed to allow embedding an Atmosphere application.\n *\n * @param mapping The servlet mapping (servlet path)\n * @param h implementation of an {@link AtmosphereHandler}\n * @param l An array of {@link AtmosphereInterceptor}.\n */\n public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, List l) {\n if (!mapping.startsWith(\"/\")) {\n mapping = \"/\" + mapping;\n }\n createWrapperAndConfigureHandler(h, mapping, l);\n\n if (!isInit) {\n logger.info(\"Installed AtmosphereHandler {} mapped to context-path: {}\", h.getClass().getName(), mapping);\n logger.info(\"Installed the following AtmosphereInterceptor mapped to AtmosphereHandler {}\", h.getClass().getName());\n if (!l.isEmpty()) {\n for (AtmosphereInterceptor s : l) {\n logger.info(\"\\t{} : {}\", s.getClass().getName(), s);\n }\n }\n }\n return this;\n }\n\n /**\n * Add an {@link AtmosphereHandler} serviced by the {@link Servlet}.\n * This API is exposed to allow embedding an Atmosphere application.\n *\n * @param mapping The servlet mapping (servlet path)\n * @param h implementation of an {@link AtmosphereHandler}\n * @param broadcaster The {@link Broadcaster} associated with AtmosphereHandler\n * @param l A list of {@link AtmosphereInterceptor}s\n */\n public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, Broadcaster broadcaster, List l) {\n if (!mapping.startsWith(\"/\")) {\n mapping = \"/\" + mapping;\n }\n\n createWrapperAndConfigureHandler(h, mapping, l).broadcaster = broadcaster;\n\n if (!isInit) {\n logger.info(\"Installed AtmosphereHandler {} mapped to context-path {} and Broadcaster Class {}\", h.getClass().getName(), mapping, broadcaster.getClass().getName());\n } else {\n logger.debug(\"Installed AtmosphereHandler {} mapped to context-path {} and Broadcaster Class {}\",\n h.getClass().getName(), mapping, broadcaster.getClass().getName());\n }\n\n if (!l.isEmpty()) {\n logger.info(\"Installed AtmosphereInterceptor {} mapped to AtmosphereHandler {}\", l, h.getClass().getName());\n }\n return this;\n }\n\n\n /**\n * Add an {@link AtmosphereHandler} serviced by the {@link Servlet}.\n * This API is exposed to allow embedding an Atmosphere application.\n *\n * @param mapping The servlet mapping (servlet path)\n * @param h implementation of an {@link AtmosphereHandler}\n * @param broadcasterId The {@link Broadcaster#getID} value.\n * @param l A list of {@link AtmosphereInterceptor}\n */\n public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, String broadcasterId, List l) {\n if (!mapping.startsWith(\"/\")) {\n mapping = \"/\" + mapping;\n }\n\n createWrapperAndConfigureHandler(h, mapping, l).broadcaster.setID(broadcasterId);\n\n logger.info(\"Installed AtmosphereHandler {} mapped to context-path: {}\", h.getClass().getName(), mapping);\n if (!l.isEmpty()) {\n logger.info(\"Installed AtmosphereInterceptor {} mapped to AtmosphereHandler {}\", l, h.getClass().getName());\n }\n return this;\n }\n\n protected AtmosphereHandlerWrapper createWrapperAndConfigureHandler(AtmosphereHandler h, String mapping, List l) {\n AtmosphereHandlerWrapper w = new AtmosphereHandlerWrapper(broadcasterFactory, h, mapping, config);\n addMapping(mapping, w);\n addInterceptorToWrapper(w, l);\n initServletProcessor(h);\n return w;\n }\n\n /**\n * Add an {@link AtmosphereHandler} serviced by the {@link Servlet}\n * This API is exposed to allow embedding an Atmosphere application.\n *\n * @param mapping The servlet mapping (servlet path)\n * @param h implementation of an {@link AtmosphereHandler}\n */\n public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h) {\n addAtmosphereHandler(mapping, h, Collections.emptyList());\n return this;\n }\n\n private AtmosphereFramework addMapping(String path, AtmosphereHandlerWrapper w) {\n atmosphereHandlers.put(normalizePath(path), w);\n return this;\n }\n\n public String normalizePath(String path) {\n // We are using JAXRS mapping algorithm.\n if (path.contains(\"*\")) {\n path = path.replace(\"*\", mappingRegex);\n }\n\n if (path.endsWith(\"/\")) {\n path = path + mappingRegex;\n }\n return path;\n }\n\n\n /**\n * Add an {@link AtmosphereHandler} serviced by the {@link Servlet}.\n * This API is exposed to allow embedding an Atmosphere application.\n *\n * @param mapping The servlet mapping (servlet path)\n * @param h implementation of an {@link AtmosphereHandler}\n * @param broadcasterId The {@link Broadcaster#getID} value\n */\n public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, String broadcasterId) {\n addAtmosphereHandler(mapping, h, broadcasterId, Collections.emptyList());\n return this;\n }\n\n private void initServletProcessor(AtmosphereHandler h) {\n if (!isInit) return;\n\n try {\n if (h instanceof AtmosphereServletProcessor) {\n ((AtmosphereServletProcessor) h).init(config);\n }\n } catch (ServletException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * Add an {@link AtmosphereHandler} serviced by the {@link Servlet}.\n * This API is exposed to allow embedding an Atmosphere application.\n *\n * @param mapping The servlet mapping (servlet path)\n * @param h implementation of an {@link AtmosphereHandler}\n * @param broadcaster The {@link Broadcaster} associated with AtmosphereHandler.\n */\n public AtmosphereFramework addAtmosphereHandler(String mapping, AtmosphereHandler h, Broadcaster broadcaster) {\n addAtmosphereHandler(mapping, h, broadcaster, Collections.emptyList());\n return this;\n }\n\n /**\n * Remove an {@link AtmosphereHandler}.\n *\n * @param mapping the mapping used when invoking {@link #addAtmosphereHandler(String, AtmosphereHandler)};\n * @return true if removed\n */\n public AtmosphereFramework removeAtmosphereHandler(String mapping) {\n\n if (mapping.endsWith(\"/\")) {\n mapping += mappingRegex;\n }\n\n atmosphereHandlers.remove(mapping);\n return this;\n }\n\n /**\n * Remove all {@link AtmosphereHandler}s.\n */\n public AtmosphereFramework removeAllAtmosphereHandler() {\n atmosphereHandlers.clear();\n return this;\n }\n\n /**\n * Remove all init parameters.\n */\n public AtmosphereFramework removeAllInitParams() {\n initParams.clear();\n return this;\n }\n\n /**\n * Add init-param like if they were defined in web.xml\n *\n * @param name The name\n * @param value The value\n */\n public AtmosphereFramework addInitParameter(String name, String value) {\n initParams.put(name, value);\n return this;\n }\n\n protected void readSystemProperties() {\n if (System.getProperty(PROPERTY_NATIVE_COMETSUPPORT) != null) {\n useNativeImplementation = Boolean\n .parseBoolean(System.getProperty(PROPERTY_NATIVE_COMETSUPPORT));\n isCometSupportSpecified = true;\n }\n\n if (System.getProperty(PROPERTY_BLOCKING_COMETSUPPORT) != null) {\n useBlockingImplementation = Boolean\n .parseBoolean(System.getProperty(PROPERTY_BLOCKING_COMETSUPPORT));\n isCometSupportSpecified = true;\n }\n atmosphereDotXmlPath = System.getProperty(PROPERTY_ATMOSPHERE_XML, atmosphereDotXmlPath);\n\n if (System.getProperty(DISABLE_ONSTATE_EVENT) != null) {\n initParams.put(DISABLE_ONSTATE_EVENT, System.getProperty(DISABLE_ONSTATE_EVENT));\n }\n }\n\n /**\n * Path specific container using their own property.\n */\n public void patchContainer() {\n System.setProperty(\"org.apache.catalina.STRICT_SERVLET_COMPLIANCE\", \"false\");\n }\n\n /**\n * Initialize the AtmosphereFramework. Invoke this method after having properly configured this class using the setters.\n */\n public AtmosphereFramework init() {\n try {\n init(servletConfig == null ? new VoidServletConfig(initParams) : servletConfig, false);\n } catch (ServletException e) {\n logger.error(\"\", e);\n }\n return this;\n }\n\n /**\n * Initialize the AtmosphereFramework using the {@link ServletContext}.\n *\n * @param sc the {@link ServletContext}\n */\n public AtmosphereFramework init(final ServletConfig sc) throws ServletException {\n return init(sc, true);\n }\n\n /**\n * Prevent Atmosphere from scanning the entire class path.\n */\n protected void preventOOM() {\n\n String s = config.getInitParameter(ApplicationConfig.SCAN_CLASSPATH);\n if (s != null) {\n allowAllClassesScan = Boolean.parseBoolean(s);\n }\n\n try {\n Class.forName(\"org.testng.Assert\");\n allowAllClassesScan = false;\n } catch (ClassNotFoundException e) {\n }\n }\n\n /**\n * Initialize the AtmosphereFramework using the {@link ServletContext}.\n *\n * @param sc the {@link ServletContext}\n */\n public AtmosphereFramework init(final ServletConfig sc, boolean wrap) throws ServletException {\n if (isInit) return this;\n\n servletConfig(sc, wrap);\n readSystemProperties();\n populateBroadcasterType();\n populateObjectFactoryType();\n loadMetaService();\n onPreInit();\n\n try {\n\n ServletContextFactory.getDefault().init(sc.getServletContext());\n\n preventOOM();\n doInitParams(servletConfig);\n doInitParamsForWebSocket(servletConfig);\n lookupDefaultObjectFactoryType();\n\n if (logger.isTraceEnabled()) {\n asyncSupportListener(newClassInstance(AsyncSupportListener.class, AsyncSupportListenerAdapter.class));\n }\n\n configureObjectFactory();\n configureAnnotationPackages();\n\n configureBroadcasterFactory();\n configureMetaBroadcaster();\n configureAtmosphereResourceFactory();\n if (isSessionSupportSpecified) {\n sessionFactory();\n }\n configureScanningPackage(servletConfig, ApplicationConfig.ANNOTATION_PACKAGE);\n configureScanningPackage(servletConfig, FrameworkConfig.JERSEY2_SCANNING_PACKAGE);\n configureScanningPackage(servletConfig, FrameworkConfig.JERSEY_SCANNING_PACKAGE);\n // Force scanning of the packages defined.\n defaultPackagesToScan();\n\n installAnnotationProcessor(servletConfig);\n\n autoConfigureService(servletConfig.getServletContext());\n\n // Reconfigure in case an annotation changed the default.\n configureBroadcasterFactory();\n patchContainer();\n configureBroadcaster();\n loadConfiguration(servletConfig);\n initWebSocket();\n initEndpointMapper();\n initDefaultSerializer();\n\n autoDetectContainer();\n configureWebDotXmlAtmosphereHandler(servletConfig);\n asyncSupport.init(servletConfig);\n initAtmosphereHandler(servletConfig);\n configureAtmosphereInterceptor(servletConfig);\n analytics();\n\n // http://java.net/jira/browse/ATMOSPHERE-157\n if (sc.getServletContext() != null) {\n sc.getServletContext().setAttribute(BroadcasterFactory.class.getName(), broadcasterFactory);\n }\n\n String s = config.getInitParameter(ApplicationConfig.BROADCASTER_SHARABLE_THREAD_POOLS);\n if (s != null) {\n sharedThreadPools = Boolean.parseBoolean(s);\n }\n\n this.shutdownHook = new Thread(AtmosphereFramework.this::destroy);\n\n Runtime.getRuntime().addShutdownHook(this.shutdownHook);\n\n if (logger.isInfoEnabled()) {\n info();\n }\n\n if (initializationError != null) {\n logger.trace(\"ContainerInitalizer exception. May not be an issue if Atmosphere started properly \", initializationError);\n }\n\n universe();\n } catch (Throwable t) {\n logger.error(\"Failed to initialize Atmosphere Framework\", t);\n\n if (t instanceof ServletException) {\n throw (ServletException) t;\n }\n\n throw new ServletException(t);\n }\n isInit = true;\n config.initComplete();\n\n // wlc 12.x\n if (WebLogicServlet30WithWebSocket.class.isAssignableFrom(asyncSupport.getClass())) {\n servletConfig.getServletContext().setAttribute(AtmosphereConfig.class.getName(), config);\n }\n\n onPostInit();\n\n return this;\n }\n\n protected void servletConfig(final ServletConfig sc, boolean wrap) {\n if (wrap) {\n\n String value = sc.getServletContext().getInitParameter(USE_SERVLET_CONTEXT_PARAMETERS);\n final boolean useServletContextParameters = Boolean.parseBoolean(value);\n\n servletConfig = new ServletConfig() {\n\n final AtomicBoolean done = new AtomicBoolean();\n\n public String getServletName() {\n return sc.getServletName();\n }\n\n public ServletContext getServletContext() {\n return sc.getServletContext();\n }\n\n public String getInitParameter(String name) {\n String param = initParams.get(name);\n if (param == null) {\n param = sc.getInitParameter(name);\n\n if (param == null && useServletContextParameters) {\n param = sc.getServletContext().getInitParameter(name);\n }\n }\n return param;\n }\n\n public Enumeration getInitParameterNames() {\n if (!done.getAndSet(true)) {\n Enumeration en = sc.getInitParameterNames();\n if (en != null) {\n while (en.hasMoreElements()) {\n String name = en.nextElement();\n if (!initParams.containsKey(name)) {\n initParams.put(name, sc.getInitParameter(name));\n }\n }\n }\n }\n return Collections.enumeration(initParams.keySet());\n }\n };\n } else {\n servletConfig = sc;\n }\n }\n\n public void reconfigureInitParams(boolean reconfigureInitParams) {\n if (reconfigureInitParams) {\n doInitParams(servletConfig, reconfigureInitParams);\n doInitParamsForWebSocket(servletConfig);\n }\n }\n\n private void info() {\n\n if (logger.isTraceEnabled()) {\n Enumeration e = servletConfig.getInitParameterNames();\n logger.trace(\"Configured init-params\");\n String n;\n while (e.hasMoreElements()) {\n n = e.nextElement();\n logger.trace(\"\\t{} = {}\", n, servletConfig.getInitParameter(n));\n }\n }\n\n logger.info(\"Using EndpointMapper {}\", endpointMapper.getClass());\n for (String i : broadcasterFilters) {\n logger.info(\"Using BroadcastFilter: {}\", i);\n }\n\n if (broadcasterCacheClassName == null || DefaultBroadcasterCache.class.getName().equals(broadcasterCacheClassName)) {\n logger.warn(\"No BroadcasterCache configured. Broadcasted message between client reconnection will be LOST. \" +\n \"It is recommended to configure the {}\", UUIDBroadcasterCache.class.getName());\n } else {\n logger.info(\"Using BroadcasterCache: {}\", broadcasterCacheClassName);\n }\n\n String s = config.getInitParameter(BROADCASTER_WAIT_TIME);\n\n logger.info(\"Default Broadcaster Class: {}\", broadcasterClassName);\n logger.info(\"Broadcaster Shared List Resources: {}\", config.getInitParameter(BROADCASTER_SHAREABLE_LISTENERS, false));\n logger.info(\"Broadcaster Polling Wait Time {}\", s == null ? DefaultBroadcaster.POLLING_DEFAULT : s);\n logger.info(\"Shared ExecutorService supported: {}\", sharedThreadPools);\n\n ExecutorService executorService = ExecutorsFactory.getMessageDispatcher(config, Broadcaster.ROOT_MASTER);\n if (executorService != null) {\n if (ThreadPoolExecutor.class.isAssignableFrom(executorService.getClass())) {\n long max = ((ThreadPoolExecutor) executorService).getMaximumPoolSize();\n logger.info(\"Messaging Thread Pool Size: {}\",\n ((ThreadPoolExecutor) executorService).getMaximumPoolSize() == 2147483647 ? \"Unlimited\" : max);\n } else {\n logger.info(\"Messaging ExecutorService Pool Size unavailable - Not instance of ThreadPoolExecutor\");\n }\n }\n\n executorService = ExecutorsFactory.getAsyncOperationExecutor(config, Broadcaster.ROOT_MASTER);\n if (executorService != null) {\n if (ThreadPoolExecutor.class.isAssignableFrom(executorService.getClass())) {\n logger.info(\"Async I/O Thread Pool Size: {}\",\n ((ThreadPoolExecutor) executorService).getMaximumPoolSize());\n } else {\n logger.info(\"Async I/O ExecutorService Pool Size unavailable - Not instance of ThreadPoolExecutor\");\n }\n }\n logger.info(\"Using BroadcasterFactory: {}\", broadcasterFactory.getClass().getName());\n logger.info(\"Using AtmosphereResurceFactory: {}\", arFactory.getClass().getName());\n logger.info(\"Using WebSocketProcessor: {}\", webSocketProcessorClassName);\n if (defaultSerializerClassName != null && !defaultSerializerClassName.isEmpty()) {\n logger.info(\"Using Serializer: {}\", defaultSerializerClassName);\n }\n\n WebSocketProcessor wp = WebSocketProcessorFactory.getDefault().getWebSocketProcessor(this);\n boolean b = false;\n if (DefaultWebSocketProcessor.class.isAssignableFrom(wp.getClass())) {\n b = ((DefaultWebSocketProcessor) wp).invokeInterceptors();\n }\n logger.info(\"Invoke AtmosphereInterceptor on WebSocket message {}\", b);\n logger.info(\"HttpSession supported: {}\", config.isSupportSession());\n\n logger.info(\"Atmosphere is using {} for dependency injection and object creation\", objectFactory);\n logger.info(\"Atmosphere is using async support: {} running under container: {}\",\n getAsyncSupport().getClass().getName(), asyncSupport.getContainerName());\n logger.info(\"Atmosphere Framework {} started.\", Version.getRawVersion());\n\n logger.info(\"\\n\\n\\tFor Atmosphere Framework Commercial Support, visit \\n\\t{} \" +\n \"or send an email to {}\\n\", \"http://www.async-io.org/\", \"support@async-io.org\");\n\n if (logger.isTraceEnabled()) {\n for (Entry e : atmosphereHandlers.entrySet()) {\n logger.trace(\"\\nConfigured AtmosphereHandler {}\\n\", e.getKey());\n logger.trace(\"{}\", e.getValue());\n }\n }\n }\n\n protected void universe() {\n Universe.broadcasterFactory(broadcasterFactory);\n Universe.resourceFactory(arFactory);\n Universe.sessionResourceFactory(sessionFactory);\n Universe.framework(this);\n }\n\n private void configureAnnotationPackages() {\n // We must scan the default annotation set.\n annotationPackages.add(Processor.class.getPackage().getName());\n\n String s = config.getInitParameter(ApplicationConfig.CUSTOM_ANNOTATION_PACKAGE);\n if (s != null) {\n String[] l = s.split(\",\");\n for (String p : l) {\n annotationPackages.addLast(p);\n }\n }\n }\n\n protected void analytics() {\n if (!config.getInitParameter(ApplicationConfig.ANALYTICS, true)) return;\n\n final String container = getServletContext().getServerInfo();\n Thread t = new Thread(() -> {\n try {\n logger.debug(\"Retrieving Atmosphere's latest version from http://async-io.org/version.html\");\n HttpURLConnection urlConnection = (HttpURLConnection)\n URI.create(\"http://async-io.org/version.html\").toURL().openConnection();\n urlConnection.setRequestProperty(\"User-Agent\", \"Mozilla/5.0\");\n urlConnection.setRequestProperty(\"Connection\", \"keep-alive\");\n urlConnection.setRequestProperty(\"Cache-Control\", \"max-age=0\");\n urlConnection.setRequestProperty(\"Accept\", \"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\");\n urlConnection.setRequestProperty(\"Accept-Language\", \"en-US,en;q=0.8\");\n urlConnection.setRequestProperty(\"Accept-Charset\", \"ISO-8859-1,utf-8;q=0.7,*;q=0.3\");\n urlConnection.setRequestProperty(\"If-Modified-Since\", \"ISO-8859-1,utf-8;q=0.7,*;q=0.3\");\n urlConnection.setInstanceFollowRedirects(true);\n\n BufferedReader in = new BufferedReader(new InputStreamReader(\n urlConnection.getInputStream()));\n\n String inputLine;\n String newVersion = Version.getRawVersion();\n String clientVersion = null;\n String nextMajorRelease = null;\n boolean nextAvailable = false;\n if (!newVersion.contains(\"SNAPSHOT\")) {\n try {\n while ((inputLine = in.readLine().trim()) != null) {\n if (inputLine.startsWith(\"ATMO23_VERSION=\")) {\n newVersion = inputLine.substring(\"ATMO23_VERSION=\".length());\n } else if (inputLine.startsWith(\"CLIENT3_VERSION=\")) {\n clientVersion = inputLine.substring(\"CLIENT3_VERSION=\".length());\n break;\n } else if (inputLine.startsWith(\"ATMO_RELEASE_VERSION=\")) {\n nextMajorRelease = inputLine.substring(\"ATMO_RELEASE_VERSION=\".length());\n if (nextMajorRelease.compareTo(Version.getRawVersion()) > 0\n && !nextMajorRelease.toLowerCase().contains(\"rc\")\n && !nextMajorRelease.toLowerCase().contains(\"beta\")) {\n nextAvailable = true;\n }\n }\n }\n } finally {\n if (clientVersion != null) {\n logger.info(\"Latest version of Atmosphere's JavaScript Client {}\", clientVersion);\n }\n if (newVersion.compareTo(Version.getRawVersion()) > 0) {\n if (nextAvailable) {\n logger.info(\"\\n\\n\\tAtmosphere Framework Updates\\n\\tMinor available (bugs fixes): {}\\n\\tMajor available (new features): {}\", newVersion, nextMajorRelease);\n } else {\n logger.info(\"\\n\\n\\tAtmosphere Framework Updates:\\n\\tMinor Update available (bugs fixes): {}\", newVersion);\n }\n } else if (nextAvailable) {\n logger.info(\"\\n\\n\\tAtmosphere Framework Updates:\\n\\tMajor Update available (new features): {}\", nextMajorRelease);\n }\n try {\n in.close();\n } catch (IOException ex) {\n }\n urlConnection.disconnect();\n }\n }\n\n JGoogleAnalyticsTracker tracker = new JGoogleAnalyticsTracker(ModuleDetection.detect(), Version.getRawVersion(), \"UA-31990725-1\");\n tracker.trackSynchronously(new FocusPoint(container, new FocusPoint(\"Atmosphere\")));\n\n } catch (Throwable e) {\n }\n });\n t.setDaemon(true);\n t.start();\n }\n\n /**\n * Configure the list of {@link AtmosphereInterceptor}.\n *\n * @param sc a ServletConfig\n */\n protected void configureAtmosphereInterceptor(ServletConfig sc) {\n String s = sc.getInitParameter(ApplicationConfig.ATMOSPHERE_INTERCEPTORS);\n if (s != null) {\n String[] list = s.split(\",\");\n for (String a : list) {\n try {\n AtmosphereInterceptor ai = newClassInstance(AtmosphereInterceptor.class,\n (Class) IOUtils.loadClass(getClass(), a.trim()));\n interceptor(ai);\n } catch (Exception e) {\n logger.warn(\"\", e);\n }\n }\n }\n\n s = sc.getInitParameter(ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTOR);\n if (!Boolean.parseBoolean(s)) {\n logger.info(\"Installing Default AtmosphereInterceptors\");\n\n for (Class a : DEFAULT_ATMOSPHERE_INTERCEPTORS) {\n if (!excludedInterceptors.contains(a.getName())) {\n interceptors.add(newAInterceptor(a));\n } else {\n logger.info(\"Dropping Interceptor {}\", a.getName());\n }\n }\n logger.info(\"Set {} to disable them.\", ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTOR);\n }\n addDefaultOrAppInterceptors();\n }\n\n protected AtmosphereInterceptor newAInterceptor(Class a) {\n AtmosphereInterceptor ai = null;\n try {\n ai = newClassInstance(AtmosphereInterceptor.class,\n (Class) IOUtils.loadClass(getClass(), a.getName()));\n logger.info(\"\\t{} : {}\", a.getName(), ai);\n } catch (Exception ex) {\n logger.warn(\"\", ex);\n }\n return ai;\n }\n\n private static class InterceptorComparator implements Comparator {\n @Override\n public int compare(AtmosphereInterceptor i1, AtmosphereInterceptor i2) {\n InvokationOrder.PRIORITY p1, p2;\n\n if (i1 instanceof InvokationOrder) {\n p1 = ((InvokationOrder) i1).priority();\n } else {\n p1 = InvokationOrder.PRIORITY.AFTER_DEFAULT;\n }\n\n if (i2 instanceof InvokationOrder) {\n p2 = ((InvokationOrder) i2).priority();\n } else {\n p2 = InvokationOrder.PRIORITY.AFTER_DEFAULT;\n }\n\n int orderResult = 0;\n\n switch (p1) {\n case AFTER_DEFAULT:\n switch (p2) {\n case BEFORE_DEFAULT:\n case FIRST_BEFORE_DEFAULT:\n orderResult = 1;\n break;\n }\n break;\n\n case BEFORE_DEFAULT:\n switch (p2) {\n case AFTER_DEFAULT:\n orderResult = -1;\n break;\n case FIRST_BEFORE_DEFAULT:\n orderResult = 1;\n break;\n }\n break;\n\n case FIRST_BEFORE_DEFAULT:\n switch (p2) {\n case AFTER_DEFAULT:\n case BEFORE_DEFAULT:\n orderResult = -1;\n break;\n }\n break;\n }\n\n return orderResult;\n }\n }\n\n protected void configureWebDotXmlAtmosphereHandler(ServletConfig sc) {\n String s = sc.getInitParameter(ATMOSPHERE_HANDLER);\n if (s != null) {\n try {\n\n String mapping = sc.getInitParameter(ATMOSPHERE_HANDLER_MAPPING);\n if (mapping == null) {\n mapping = Broadcaster.ROOT_MASTER;\n }\n addAtmosphereHandler(mapping, newClassInstance(AtmosphereHandler.class,\n (Class) IOUtils.loadClass(getClass(), s)));\n } catch (Exception ex) {\n logger.warn(\"Unable to load WebSocketHandle instance\", ex);\n }\n }\n }\n\n protected void configureScanningPackage(ServletConfig sc, String value) {\n String packageName = sc.getInitParameter(value);\n if (packageName != null) {\n String[] list = packageName.split(\",\");\n Collections.addAll(packages, list);\n }\n }\n\n protected void defaultPackagesToScan() {\n // Atmosphere HA/Pro\n packages.add(\"io.async.control\");\n packages.add(\"io.async.satellite\");\n packages.add(\"io.async.postman\");\n }\n\n public void configureBroadcasterFactory() {\n try {\n // Check auto supported one\n if (!isBroadcasterSpecified) {\n broadcasterClassName = lookupDefaultBroadcasterType(broadcasterClassName);\n }\n\n if (broadcasterFactoryClassName != null && broadcasterFactory == null) {\n broadcasterFactory = newClassInstance(BroadcasterFactory.class,\n (Class) IOUtils.loadClass(getClass(), broadcasterFactoryClassName));\n Class bc =\n (Class) IOUtils.loadClass(getClass(), broadcasterClassName);\n broadcasterFactory.configure(bc, broadcasterLifeCyclePolicy, config);\n }\n\n if (broadcasterFactory == null) {\n Class bc =\n (Class) IOUtils.loadClass(getClass(), broadcasterClassName);\n broadcasterFactory = newClassInstance(BroadcasterFactory.class, DefaultBroadcasterFactory.class);\n broadcasterFactory.configure(bc, broadcasterLifeCyclePolicy, config);\n }\n\n for (BroadcasterListener b : broadcasterListeners) {\n broadcasterFactory.addBroadcasterListener(b);\n }\n } catch (Exception ex) {\n logger.error(\"Unable to configure Broadcaster/Factory/Cache\", ex);\n }\n }\n\n protected void configureBroadcaster() {\n\n try {\n Iterator> i = atmosphereHandlers.entrySet().iterator();\n AtmosphereHandlerWrapper w;\n Entry e;\n while (i.hasNext()) {\n e = i.next();\n w = e.getValue();\n\n if (w.broadcaster == null) {\n w.broadcaster = broadcasterFactory.get(w.mapping);\n } else {\n if (broadcasterCacheClassName != null\n && w.broadcaster.getBroadcasterConfig().getBroadcasterCache().getClass().getName().equals(\n DefaultBroadcasterCache.class.getName())) {\n BroadcasterCache cache = newClassInstance(BroadcasterCache.class,\n (Class) IOUtils.loadClass(getClass(), broadcasterCacheClassName));\n cache.configure(config);\n w.broadcaster.getBroadcasterConfig().setBroadcasterCache(cache);\n }\n }\n }\n } catch (Exception ex) {\n logger.error(\"Unable to configure Broadcaster/Factory/Cache\", ex);\n }\n }\n\n protected void installAnnotationProcessor(ServletConfig sc) {\n String s = sc.getInitParameter(ApplicationConfig.ANNOTATION_PROCESSOR);\n if (s != null) {\n annotationProcessorClassName = s;\n }\n }\n\n protected void doInitParamsForWebSocket(ServletConfig sc) {\n String s = sc.getInitParameter(WEBSOCKET_SUPPORT);\n if (s != null) {\n webSocketEnabled = Boolean.parseBoolean(s);\n sessionSupport(false);\n }\n s = sc.getInitParameter(WEBSOCKET_PROTOCOL);\n if (s != null) {\n webSocketProtocolClassName = s;\n }\n\n s = sc.getInitParameter(WEBSOCKET_PROCESSOR);\n if (s != null) {\n webSocketProcessorClassName = s;\n }\n\n s = config.getInitParameter(ApplicationConfig.WEBSOCKET_SUPPORT_SERVLET3);\n if (s != null) {\n useServlet30 = Boolean.parseBoolean(s);\n }\n }\n\n /**\n * Read init params from web.xml and apply them.\n *\n * @param sc {@link ServletConfig}\n */\n protected void doInitParams(ServletConfig sc) {\n doInitParams(sc, false);\n }\n\n /**\n * Read init params from web.xml and apply them.\n *\n * @param sc {@link ServletConfig}\n */\n protected void doInitParams(ServletConfig sc, boolean reconfigure) {\n String s = sc.getInitParameter(PROPERTY_NATIVE_COMETSUPPORT);\n if (s != null) {\n useNativeImplementation = Boolean.parseBoolean(s);\n if (useNativeImplementation) isCometSupportSpecified = true;\n }\n s = sc.getInitParameter(PROPERTY_BLOCKING_COMETSUPPORT);\n if (s != null) {\n useBlockingImplementation = Boolean.parseBoolean(s);\n if (useBlockingImplementation) isCometSupportSpecified = true;\n }\n s = sc.getInitParameter(PROPERTY_USE_STREAM);\n if (s != null) {\n useStreamForFlushingComments = Boolean.parseBoolean(s);\n }\n s = sc.getInitParameter(PROPERTY_COMET_SUPPORT);\n if (asyncSupport == null && s != null && !reconfigure) {\n asyncSupport = new DefaultAsyncSupportResolver(config).newCometSupport(s);\n isCometSupportSpecified = true;\n }\n s = sc.getInitParameter(BROADCASTER_CLASS);\n if (s != null) {\n broadcasterClassName = s;\n isBroadcasterSpecified = true;\n }\n s = sc.getInitParameter(BROADCASTER_CACHE);\n if (s != null) {\n broadcasterCacheClassName = s;\n }\n\n s = sc.getInitParameter(PROPERTY_SESSION_SUPPORT);\n if (s == null) {\n s = sc.getServletContext().getInitParameter(PROPERTY_SESSION_SUPPORT);\n }\n\n if (s != null || SessionSupport.initializationHint) {\n boolean sessionSupport = Boolean.parseBoolean(s) || SessionSupport.initializationHint;\n config.setSupportSession(sessionSupport);\n if (sessionSupport && (sc.getServletContext().getMajorVersion() < 3 || !SessionSupport.initializationHint)) {\n logger.warn(\"SessionSupport error. Make sure you also define {} as a listener in web.xml, see https://github.com/Atmosphere/atmosphere/wiki/Enabling-HttpSession-Support\", SessionSupport.class.getName());\n }\n isSessionSupportSpecified = true;\n }\n s = sc.getInitParameter(PROPERTY_ALLOW_SESSION_TIMEOUT_REMOVAL);\n if (s != null) {\n config.setSessionTimeoutRemovalAllowed(Boolean.parseBoolean(s));\n }\n s = sc.getInitParameter(PROPERTY_THROW_EXCEPTION_ON_CLONED_REQUEST);\n if (s != null) {\n config.setThrowExceptionOnCloned(Boolean.parseBoolean(s));\n isThrowExceptionOnClonedRequestSpecified = true;\n }\n s = sc.getInitParameter(DISABLE_ONSTATE_EVENT);\n if (s != null) {\n initParams.put(DISABLE_ONSTATE_EVENT, s);\n } else {\n initParams.put(DISABLE_ONSTATE_EVENT, \"false\");\n }\n s = sc.getInitParameter(BROADCAST_FILTER_CLASSES);\n if (s != null) {\n broadcasterFilters.addAll(Arrays.asList(s.split(\",\")));\n logger.info(\"Installing BroadcastFilter class(es) {}\", s);\n }\n s = sc.getInitParameter(BROADCASTER_LIFECYCLE_POLICY);\n if (s != null) {\n broadcasterLifeCyclePolicy = s;\n }\n s = sc.getInitParameter(BROADCASTER_FACTORY);\n if (s != null) {\n broadcasterFactoryClassName = s;\n }\n s = sc.getInitParameter(ATMOSPHERE_HANDLER_PATH);\n if (s != null) {\n handlersPath = s;\n }\n s = sc.getInitParameter(PROPERTY_ATMOSPHERE_XML);\n if (s != null) {\n atmosphereDotXmlPath = s;\n }\n s = sc.getInitParameter(META_SERVICE_PATH);\n if (s != null) {\n metaServicePath = s;\n }\n s = sc.getInitParameter(ApplicationConfig.HANDLER_MAPPING_REGEX);\n if (s != null) {\n mappingRegex = s;\n }\n\n s = sc.getInitParameter(FrameworkConfig.JERSEY_SCANNING_PACKAGE);\n if (s != null) {\n packages.add(s);\n }\n\n s = sc.getInitParameter(ApplicationConfig.DEFAULT_SERIALIZER);\n if (s != null) {\n defaultSerializerClassName = s;\n }\n\n s = sc.getInitParameter(ApplicationConfig.DISABLE_ATMOSPHEREINTERCEPTORS);\n if (s != null) {\n excludedInterceptors.addAll(Arrays.asList(s.trim().replace(\" \", \"\").split(\",\")));\n }\n }\n\n public void loadConfiguration(ServletConfig sc) throws ServletException {\n\n if (!autoDetectHandlers) return;\n\n try {\n URL url = sc.getServletContext().getResource(handlersPath);\n ClassLoader urlC = url == null ? getClass().getClassLoader() : new URLClassLoader(new URL[]{url},\n Thread.currentThread().getContextClassLoader());\n loadAtmosphereDotXml(sc.getServletContext().\n getResourceAsStream(atmosphereDotXmlPath), urlC);\n\n if (atmosphereHandlers.isEmpty()) {\n autoDetectAtmosphereHandlers(sc.getServletContext(), urlC);\n\n if (atmosphereHandlers.isEmpty()) {\n detectSupportedFramework(sc);\n }\n }\n\n autoDetectWebSocketHandler(sc.getServletContext(), urlC);\n } catch (Throwable t) {\n throw new ServletException(t);\n }\n }\n\n /**\n * Auto-detect Jersey when no atmosphere.xml file is specified.\n *\n * @param sc {@link ServletConfig}\n * @return true if Jersey classes are detected\n * @throws ClassNotFoundException\n */\n protected boolean detectSupportedFramework(ServletConfig sc) throws Exception {\n\n String broadcasterClassNameTmp = null;\n\n boolean isJersey;\n try {\n IOUtils.loadClass(getClass(), JERSEY_CONTAINER);\n isJersey = true;\n\n if (!isBroadcasterSpecified) {\n broadcasterClassNameTmp = lookupDefaultBroadcasterType(JERSEY_BROADCASTER);\n\n IOUtils.loadClass(getClass(), broadcasterClassNameTmp);\n }\n useStreamForFlushingComments = true;\n\n StringBuilder packagesInit = new StringBuilder();\n for (String s : packages) {\n packagesInit.append(s).append(\",\");\n }\n\n initParams.put(FrameworkConfig.JERSEY_SCANNING_PACKAGE, packagesInit.toString());\n } catch (Throwable t) {\n logger.trace(\"\", t);\n return false;\n }\n\n logger.debug(\"Missing META-INF/atmosphere.xml but found the Jersey runtime. Starting Jersey\");\n\n // Atmosphere 1.1 : could add regressions\n // Jersey will itself handle the headers.\n //initParams.put(WRITE_HEADERS, \"false\");\n\n ReflectorServletProcessor rsp = newClassInstance(ReflectorServletProcessor.class, ReflectorServletProcessor.class);\n if (broadcasterClassNameTmp != null) broadcasterClassName = broadcasterClassNameTmp;\n configureDetectedFramework(rsp, isJersey);\n sessionSupport(false);\n initParams.put(DISABLE_ONSTATE_EVENT, \"true\");\n\n String mapping = sc.getInitParameter(PROPERTY_SERVLET_MAPPING);\n if (mapping == null) {\n mapping = sc.getInitParameter(ATMOSPHERE_HANDLER_MAPPING);\n if (mapping == null) {\n mapping = Broadcaster.ROOT_MASTER;\n }\n }\n Class bc = (Class) IOUtils.loadClass(getClass(), broadcasterClassName);\n\n broadcasterFactory.destroy();\n\n broadcasterFactory = newClassInstance(BroadcasterFactory.class, DefaultBroadcasterFactory.class);\n broadcasterFactory.configure(bc, broadcasterLifeCyclePolicy, config);\n for (BroadcasterListener b : broadcasterListeners) {\n broadcasterFactory.addBroadcasterListener(b);\n }\n\n Broadcaster b;\n\n try {\n b = broadcasterFactory.get(bc, mapping);\n } catch (IllegalStateException ex) {\n logger.warn(\"Two Broadcaster's named {}. Renaming the second one to {}\", mapping, sc.getServletName() + mapping);\n b = broadcasterFactory.get(bc, sc.getServletName() + mapping);\n }\n\n addAtmosphereHandler(mapping, rsp, b);\n return true;\n }\n\n protected void configureDetectedFramework(ReflectorServletProcessor rsp, boolean isJersey) {\n rsp.setServletClassName(JERSEY_CONTAINER);\n }\n\n protected String lookupDefaultBroadcasterType(String defaultB) {\n if (autodetectBroadcaster()) {\n for (String b : broadcasterTypes) {\n try {\n Class.forName(b);\n logger.info(\"Detected a Broadcaster {} on the classpath. \" +\n \"This broadcaster will be used by default and will override any annotated resources. \" +\n \"Set {} to false to change the behavior\", b, ApplicationConfig.AUTODETECT_BROADCASTER);\n isBroadcasterSpecified = true;\n return b;\n } catch (ClassNotFoundException e) {\n }\n }\n }\n\n return defaultB;\n }\n\n boolean autodetectBroadcaster() {\n if (servletConfig == null) {\n return true;\n }\n\n String autodetect = servletConfig.getInitParameter(ApplicationConfig.AUTODETECT_BROADCASTER);\n return autodetect == null || Boolean.parseBoolean(autodetect);\n }\n\n protected AtmosphereObjectFactory lookupDefaultObjectFactoryType() {\n\n if (objectFactory != null && !DefaultAtmosphereObjectFactory.class.getName().equals(objectFactory.getClass()\n .getName())) return objectFactory;\n\n for (String b : objectFactoryType) {\n try {\n Class c = Class.forName(b);\n objectFactory = (AtmosphereObjectFactory) c.newInstance();\n break;\n } catch (ClassNotFoundException e) {\n logger.trace(e.getMessage() + \" not found\");\n } catch (Exception e) {\n logger.trace(\"\", e);\n }\n }\n\n if (objectFactory == null || DefaultAtmosphereObjectFactory.class.getName().equals(objectFactory.getClass()\n .getName())) {\n try {\n IOUtils.loadClass(getClass(), INJECT_LIBARY);\n objectFactory = new InjectableObjectFactory();\n } catch (Exception e) {\n logger.trace(\"javax.inject.Inject nor installed. Using DefaultAtmosphereObjectFactory\");\n objectFactory = new DefaultAtmosphereObjectFactory();\n }\n }\n\n objectFactory.configure(config);\n return objectFactory;\n }\n\n public void sessionSupport(boolean sessionSupport) {\n if (!isSessionSupportSpecified) {\n config.setSupportSession(sessionSupport);\n } else if (!config.isSupportSession()) {\n // Don't turn off session support. Once it's on, leave it on.\n config.setSupportSession(sessionSupport);\n }\n }\n\n /**\n * Initialize {@link AtmosphereServletProcessor}.\n *\n * @param sc the {@link ServletConfig}\n * @throws javax.servlet.ServletException\n * @Deprecated\n */\n public void initAtmosphereHandler(ServletConfig sc) throws ServletException {\n initAtmosphereHandler();\n }\n\n public void initAtmosphereHandler() throws ServletException {\n\n AtmosphereHandler a;\n AtmosphereHandlerWrapper w;\n for (Entry h : atmosphereHandlers.entrySet()) {\n w = h.getValue();\n a = w.atmosphereHandler;\n if (a instanceof AtmosphereServletProcessor) {\n ((AtmosphereServletProcessor) a).init(config);\n }\n }\n checkWebSocketSupportState();\n }\n\n public void checkWebSocketSupportState() {\n if (atmosphereHandlers.isEmpty() && !SimpleHttpProtocol.class.isAssignableFrom(webSocketProtocol.getClass())) {\n logger.debug(\"Adding a void AtmosphereHandler mapped to /* to allow WebSocket application only\");\n addAtmosphereHandler(Broadcaster.ROOT_MASTER, new AbstractReflectorAtmosphereHandler() {\n @Override\n public void onRequest(AtmosphereResource r) throws IOException {\n logger.debug(\"No AtmosphereHandler defined.\");\n if (!r.transport().equals(AtmosphereResource.TRANSPORT.WEBSOCKET)) {\n WebSocket.notSupported(r.getRequest(), r.getResponse());\n }\n }\n\n @Override\n public void destroy() {\n }\n });\n }\n }\n\n public void initWebSocket() {\n if (webSocketProtocolInitialized) return;\n\n if (webSocketProtocol == null) {\n try {\n webSocketProtocol = newClassInstance(WebSocketProtocol.class,\n (Class) IOUtils.loadClass(this.getClass(), webSocketProtocolClassName));\n logger.info(\"Installed WebSocketProtocol {} \", webSocketProtocolClassName);\n } catch (Exception ex) {\n logger.error(\"Cannot load the WebSocketProtocol {}\", getWebSocketProtocolClassName(), ex);\n try {\n webSocketProtocol = newClassInstance(WebSocketProtocol.class, SimpleHttpProtocol.class);\n } catch (Exception e) {\n }\n }\n }\n webSocketProtocolInitialized = true;\n webSocketProtocol.configure(config);\n }\n\n public void initEndpointMapper() {\n String s = servletConfig.getInitParameter(ApplicationConfig.ENDPOINT_MAPPER);\n if (s != null) {\n try {\n endpointMapper = newClassInstance(EndpointMapper.class, (Class) IOUtils.loadClass(this.getClass(), s));\n logger.info(\"Installed EndpointMapper {} \", s);\n } catch (Exception ex) {\n logger.error(\"Cannot load the EndpointMapper {}\", s, ex);\n }\n }\n endpointMapper.configure(config);\n }\n\n protected void closeAtmosphereResource() {\n for (AtmosphereResource r : config.resourcesFactory().findAll()) {\n try {\n r.resume().close();\n } catch (Exception e) {\n logger.trace(\"\", e);\n }\n }\n }\n\n public AtmosphereFramework destroy() {\n\n if (isDestroyed.getAndSet(true)) return this;\n\n onPreDestroy();\n\n closeAtmosphereResource();\n destroyInterceptors();\n\n // Invoke ShutdownHook.\n config.destroy();\n\n BroadcasterFactory factory = broadcasterFactory;\n if (factory != null) {\n factory.destroy();\n }\n\n if (asyncSupport != null && AsynchronousProcessor.class.isAssignableFrom(asyncSupport.getClass())) {\n ((AsynchronousProcessor) asyncSupport).shutdown();\n }\n\n // We just need one bc to shutdown the shared thread pool\n for (Entry entry : atmosphereHandlers.entrySet()) {\n AtmosphereHandlerWrapper handlerWrapper = entry.getValue();\n try {\n handlerWrapper.atmosphereHandler.destroy();\n } catch (Throwable t) {\n logger.warn(\"\", t);\n }\n }\n\n if (metaBroadcaster != null) metaBroadcaster.destroy();\n if (arFactory != null) arFactory.destroy();\n if (sessionFactory != null) sessionFactory.destroy();\n\n WebSocketProcessorFactory.getDefault().destroy();\n\n ExecutorsFactory.reset(config);\n\n resetStates();\n\n onPostDestroy();\n\n try {\n if (this.shutdownHook != null) {\n Runtime.getRuntime().removeShutdownHook(this.shutdownHook);\n shutdownHook = null;\n }\n } catch (IllegalStateException ex) {\n logger.trace(\"\", ex);\n }\n\n config.properties().clear();\n return this;\n }\n\n protected void destroyInterceptors() {\n for (AtmosphereHandlerWrapper w : atmosphereHandlers.values()) {\n for (AtmosphereInterceptor i : w.interceptors) {\n try {\n i.destroy();\n } catch (Throwable ex) {\n logger.warn(\"\", ex);\n }\n }\n }\n }\n\n public AtmosphereFramework resetStates() {\n isInit = false;\n executeFirstSet = false;\n\n broadcasterFilters.clear();\n asyncSupportListeners.clear();\n possibleComponentsCandidate.clear();\n initParams.clear();\n atmosphereHandlers.clear();\n broadcasterTypes.clear();\n objectFactoryType.clear();\n inspectors.clear();\n broadcasterListeners.clear();\n packages.clear();\n annotationPackages.clear();\n excludedInterceptors.clear();\n broadcasterCacheListeners.clear();\n filterManipulators.clear();\n interceptors.clear();\n\n broadcasterFactory = null;\n arFactory = null;\n metaBroadcaster = null;\n sessionFactory = null;\n annotationFound = false;\n return this;\n }\n\n protected void loadMetaService() {\n try {\n Map config = (Map) servletConfig.getServletContext().getAttribute(AtmosphereFramework.MetaServiceAction.class.getName());\n if (config == null) {\n config = IOUtils.readServiceFile(metaServicePath + AtmosphereFramework.class.getName());\n }\n\n for (final Map.Entry action : config.entrySet()) {\n try {\n final Class c = IOUtils.loadClass(AtmosphereFramework.class, action.getKey());\n action.getValue().apply(this, c);\n } catch (ClassNotFoundException ex) {\n if (action.getKey().startsWith(ASYNC_IO)) {\n logger.trace(\"Unable to load class {}\", ex.getMessage());\n } else {\n logger.warn(\"\", ex);\n }\n }\n }\n } catch (Exception ex) {\n logger.warn(\"\", ex);\n }\n }\n\n /**\n * Load AtmosphereHandler defined under META-INF/atmosphere.xml.\n *\n * @param stream The input stream we read from.\n * @param c The classloader\n */\n protected void loadAtmosphereDotXml(InputStream stream, ClassLoader c)\n throws IOException, ServletException {\n\n if (stream == null) {\n return;\n }\n\n logger.info(\"Found Atmosphere Configuration under {}\", atmosphereDotXmlPath);\n AtmosphereConfigReader.getInstance().parse(config, stream);\n AtmosphereHandler handler = null;\n for (AtmosphereHandlerConfig atmoHandler : config.getAtmosphereHandlerConfig()) {\n try {\n if (!atmoHandler.getClassName().startsWith(\"@\")) {\n if (!ReflectorServletProcessor.class.getName().equals(atmoHandler.getClassName())) {\n handler = newClassInstance(AtmosphereHandler.class,\n (Class) IOUtils.loadClass(this.getClass(), atmoHandler.getClassName()));\n } else {\n handler = newClassInstance(AtmosphereHandler.class, ReflectorServletProcessor.class);\n }\n logger.info(\"Installed AtmosphereHandler {} mapped to context-path: {}\", handler, atmoHandler.getContextRoot());\n }\n\n for (ApplicationConfiguration a : atmoHandler.getApplicationConfig()) {\n initParams.put(a.getParamName(), a.getParamValue());\n }\n\n for (FrameworkConfiguration a : atmoHandler.getFrameworkConfig()) {\n initParams.put(a.getParamName(), a.getParamValue());\n }\n\n for (AtmosphereHandlerProperty handlerProperty : atmoHandler.getProperties()) {\n\n if (handlerProperty.getValue() != null && handlerProperty.getValue().contains(\"jersey\")) {\n initParams.put(DISABLE_ONSTATE_EVENT, \"true\");\n useStreamForFlushingComments = true;\n broadcasterClassName = lookupDefaultBroadcasterType(JERSEY_BROADCASTER);\n broadcasterFactory.destroy();\n broadcasterFactory = null;\n configureBroadcasterFactory();\n configureBroadcaster();\n }\n\n if (handler != null) {\n IntrospectionUtils.setProperty(handler, handlerProperty.getName(), handlerProperty.getValue());\n IntrospectionUtils.addProperty(handler, handlerProperty.getName(), handlerProperty.getValue());\n }\n }\n\n sessionSupport(Boolean.parseBoolean(atmoHandler.getSupportSession()));\n\n if (handler != null) {\n String broadcasterClass = atmoHandler.getBroadcaster();\n Broadcaster b;\n /*\n * If there is more than one AtmosphereHandler defined, their Broadcaster\n * may clash each other with the BroadcasterFactory. In that case we will use the\n * last one defined.\n */\n if (broadcasterClass != null) {\n broadcasterClassName = broadcasterClass;\n ClassLoader cl = Thread.currentThread().getContextClassLoader();\n Class bc = (Class) cl.loadClass(broadcasterClassName);\n broadcasterFactory = newClassInstance(BroadcasterFactory.class, DefaultBroadcasterFactory.class);\n broadcasterFactory.configure(bc, broadcasterLifeCyclePolicy, config);\n }\n\n b = broadcasterFactory.lookup(atmoHandler.getContextRoot(), true);\n\n AtmosphereHandlerWrapper wrapper = new AtmosphereHandlerWrapper(handler, b, config);\n addMapping(atmoHandler.getContextRoot(), wrapper);\n\n String bc = atmoHandler.getBroadcasterCache();\n if (bc != null) {\n broadcasterCacheClassName = bc;\n }\n\n if (atmoHandler.getCometSupport() != null) {\n asyncSupport = (AsyncSupport) c.loadClass(atmoHandler.getCometSupport())\n .getDeclaredConstructor(new Class[]{AtmosphereConfig.class})\n .newInstance(new Object[]{config});\n }\n\n if (atmoHandler.getBroadcastFilterClasses() != null) {\n broadcasterFilters.addAll(atmoHandler.getBroadcastFilterClasses());\n }\n\n LinkedList l = new LinkedList();\n if (atmoHandler.getAtmosphereInterceptorClasses() != null) {\n for (String a : atmoHandler.getAtmosphereInterceptorClasses()) {\n try {\n AtmosphereInterceptor ai = newClassInstance(AtmosphereInterceptor.class,\n (Class) IOUtils.loadClass(getClass(), a));\n l.add(ai);\n } catch (Throwable e) {\n logger.warn(\"\", e);\n }\n }\n }\n addInterceptorToWrapper(wrapper, l);\n\n if (!l.isEmpty()) {\n logger.info(\"Installed AtmosphereInterceptor {} mapped to AtmosphereHandler {}\", l, atmoHandler.getClassName());\n }\n }\n } catch (Throwable t) {\n logger.warn(\"Unable to load AtmosphereHandler class: \" + atmoHandler.getClassName(), t);\n throw new ServletException(t);\n }\n\n }\n }\n\n /**\n * Set the {@link AsyncSupport} implementation. Make sure you don't set an implementation that only works on\n * some container. See {@link BlockingIOCometSupport} for an example.\n *\n * @param asyncSupport\n */\n public AtmosphereFramework setAsyncSupport(AsyncSupport asyncSupport) {\n this.asyncSupport = asyncSupport;\n return this;\n }\n\n /**\n * @param asyncSupport\n * @return\n * @Deprecated - Use {@link #setAsyncSupport(AsyncSupport)}\n */\n public AtmosphereFramework setCometSupport(AsyncSupport asyncSupport) {\n return setAsyncSupport(asyncSupport);\n }\n\n /**\n * Return the current {@link AsyncSupport}.\n *\n * @return the current {@link AsyncSupport}\n */\n public AsyncSupport getAsyncSupport() {\n return asyncSupport;\n }\n\n /**\n * Return the current {@link AsyncSupport}.\n *\n * @return the current {@link AsyncSupport}\n * @deprecated Use getAsyncSupport\n */\n public AsyncSupport getCometSupport() {\n return asyncSupport;\n }\n\n /**\n * Returns an instance of AsyncSupportResolver {@link AsyncSupportResolver}.\n *\n * @return CometSupportResolver\n */\n protected AsyncSupportResolver createAsyncSupportResolver() {\n return new DefaultAsyncSupportResolver(config);\n }\n\n\n /**\n * Auto detect the underlying Servlet Container we are running on.\n */\n protected void autoDetectContainer() {\n // Was defined in atmosphere.xml\n if (getAsyncSupport() == null) {\n setAsyncSupport(createAsyncSupportResolver()\n .resolve(useNativeImplementation, useBlockingImplementation, useServlet30));\n }\n }\n\n /**\n * Auto detect instance of {@link AtmosphereHandler} in case META-INF/atmosphere.xml\n * is missing.\n *\n * @param servletContext {@link ServletContext}\n * @param classloader {@link ClassLoader} to load the class.\n * @throws java.net.MalformedURLException\n */\n public void autoDetectAtmosphereHandlers(ServletContext servletContext, ClassLoader classloader)\n throws MalformedURLException {\n\n // If Handler has been added\n if (!atmosphereHandlers.isEmpty()) return;\n\n logger.info(\"Auto detecting atmosphere handlers {}\", handlersPath);\n\n String realPath = servletContext.getRealPath(handlersPath);\n\n // Weblogic bug\n if (realPath == null) {\n URL u = servletContext.getResource(handlersPath);\n if (u == null) return;\n realPath = u.getPath();\n }\n\n loadAtmosphereHandlersFromPath(classloader, realPath);\n }\n\n public void loadAtmosphereHandlersFromPath(ClassLoader classloader, String realPath) {\n File file = new File(realPath);\n\n if (file.exists() && file.isDirectory()) {\n getFiles(file);\n scanDone = true;\n\n for (String className : possibleComponentsCandidate) {\n try {\n className = className.replace('\\\\', '/');\n className = className.replaceFirst(\"^.*/(WEB-INF|target)(?:/scala-[^/]+)?/(test-)?classes/(.*)\\\\.class\", \"$3\").replace(\"/\", \".\");\n Class clazz = classloader.loadClass(className);\n\n if (AtmosphereHandler.class.isAssignableFrom(clazz)) {\n AtmosphereHandler handler = newClassInstance(AtmosphereHandler.class, (Class) clazz);\n addMapping(\"/\" + handler.getClass().getSimpleName(),\n new AtmosphereHandlerWrapper(broadcasterFactory, handler, \"/\" + handler.getClass().getSimpleName(), config));\n logger.info(\"Installed AtmosphereHandler {} mapped to context-path: {}\", handler, handler.getClass().getName());\n }\n } catch (Throwable t) {\n logger.trace(\"failed to load class as an AtmosphereHandler: \" + className, t);\n }\n }\n }\n }\n\n /**\n * Auto detect instance of {@link org.atmosphere.websocket.WebSocketHandler} in case META-INF/atmosphere.xml\n * is missing.\n *\n * @param servletContext {@link ServletContext}\n * @param classloader {@link ClassLoader} to load the class.\n * @throws java.net.MalformedURLException\n */\n protected void autoDetectWebSocketHandler(ServletContext servletContext, ClassLoader classloader)\n throws MalformedURLException {\n\n if (hasNewWebSocketProtocol) return;\n\n logger.info(\"Auto detecting WebSocketHandler in {}\", handlersPath);\n loadWebSocketFromPath(classloader, realPath(servletContext, handlersPath));\n }\n\n protected void loadWebSocketFromPath(ClassLoader classloader, String realPath) {\n File file = new File(realPath);\n\n if (file.exists() && file.isDirectory()) {\n getFiles(file);\n scanDone = true;\n\n for (String className : possibleComponentsCandidate) {\n try {\n className = className.replace('\\\\', '/');\n className = className.replaceFirst(\"^.*/(WEB-INF|target)(?:/scala-[^/]+)?/(test-)?classes/(.*)\\\\.class\", \"$3\").replace(\"/\", \".\");\n Class clazz = classloader.loadClass(className);\n\n if (WebSocketProtocol.class.isAssignableFrom(clazz)) {\n webSocketProtocol = newClassInstance(WebSocketProtocol.class, (Class) clazz);\n logger.info(\"Installed WebSocketProtocol {}\", webSocketProtocol);\n }\n } catch (Throwable t) {\n logger.trace(\"failed to load class as an WebSocketProtocol: \" + className, t);\n }\n }\n }\n }\n\n /**\n * Get a list of possible candidates to load as {@link AtmosphereHandler}.\n *\n * @param f the real path {@link File}\n */\n private void getFiles(File f) {\n if (scanDone) return;\n\n File[] files = f.listFiles();\n for (File test : Objects.requireNonNull(files)) {\n if (test.isDirectory()) {\n getFiles(test);\n } else {\n String clazz = test.getAbsolutePath();\n if (clazz.endsWith(\".class\")) {\n possibleComponentsCandidate.add(clazz);\n }\n }\n }\n }\n\n /**\n * Configure some attributes on the {@link AtmosphereRequest}.\n *\n * @param req {@link AtmosphereRequest}\n */\n public AtmosphereFramework configureRequestResponse(AtmosphereRequest req, AtmosphereResponse res) throws UnsupportedEncodingException {\n req.setAttribute(PROPERTY_USE_STREAM, useStreamForFlushingComments);\n req.setAttribute(BROADCASTER_CLASS, broadcasterClassName);\n req.setAttribute(ATMOSPHERE_CONFIG, config);\n req.setAttribute(THROW_EXCEPTION_ON_CLONED_REQUEST, \"\" + config.isThrowExceptionOnCloned());\n\n boolean skip = true;\n String s = config.getInitParameter(ALLOW_QUERYSTRING_AS_REQUEST);\n if (s != null) {\n skip = Boolean.parseBoolean(s);\n }\n\n if (!skip || req.getAttribute(WEBSOCKET_SUSPEND) == null) {\n Map headers = configureQueryStringAsRequest(req);\n String body = headers.remove(ATMOSPHERE_POST_BODY);\n if (body != null && body.isEmpty()) {\n body = null;\n }\n\n // Reconfigure the request. Clear the Atmosphere queryString\n req.headers(headers)\n .method(body != null && req.getMethod().equalsIgnoreCase(\"GET\") ? \"POST\" : req.getMethod());\n\n if (body != null) {\n req.body(URLDecoder.decode(body, req.getCharacterEncoding() == null ? \"UTF-8\" : req.getCharacterEncoding()));\n }\n }\n\n s = req.getHeader(X_ATMOSPHERE_TRACKING_ID);\n\n // Lookup for websocket\n if (s == null || s.equals(\"0\")) {\n String unique = config.getInitParameter(ApplicationConfig.UNIQUE_UUID_WEBSOCKET);\n if (Boolean.parseBoolean(unique)) {\n s = (String) req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID);\n }\n }\n\n if (s == null || s.equals(\"0\")) {\n s = config.uuidProvider().generateUuid();\n res.setHeader(HeaderConfig.X_FIRST_REQUEST, \"true\");\n res.setHeader(X_ATMOSPHERE_TRACKING_ID, s);\n String contentType = config.getInitParameter(CONTENT_TYPE_FIRST_RESPONSE);\n if (contentType != null) {\n res.setHeader(\"Content-Type\", contentType);\n }\n } else {\n // This may breaks 1.0.0 application because the WebSocket's associated AtmosphereResource will\n // all have the same UUID, and retrieving the original one for WebSocket, so we don't set it at all.\n // Null means it is not an HTTP request.\n if (req.resource() == null) {\n res.setHeader(X_ATMOSPHERE_TRACKING_ID, s);\n } else if (req.getAttribute(WebSocket.WEBSOCKET_INITIATED) == null) {\n // WebSocket reconnect, in case an application manually set the header\n // (impossible to retrieve the headers normally with WebSocket or SSE)\n res.setHeader(X_ATMOSPHERE_TRACKING_ID, s);\n }\n }\n\n if (req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID) == null) {\n req.setAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID, s);\n }\n return this;\n }\n\n /**\n * Invoke the proprietary {@link AsyncSupport}.\n *\n * @param req\n * @param res\n * @return an {@link Action}\n * @throws IOException\n * @throws ServletException\n */\n public Action doCometSupport(AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException {\n\n if (isDestroyed.get()) return Action.CANCELLED;\n\n Action a = null;\n try {\n configureRequestResponse(req, res);\n a = asyncSupport.service(req, res);\n } catch (IllegalStateException ex) {\n boolean isJBoss = ex.getMessage() != null && ex.getMessage().startsWith(\"JBoss failed\");\n if (ex.getMessage() != null && (ex.getMessage().startsWith(\"Tomcat failed\") || isJBoss)) {\n if (!isFilter) {\n logger.warn(\"Failed using comet support: {}, error: {} Is the NIO or APR Connector enabled?\", asyncSupport.getClass().getName(),\n ex.getMessage());\n }\n logger.error(\"If you have more than one Connector enabled, make sure they both use the same protocol, \" +\n \"e.g NIO/APR or HTTP for all. If not, {} will be used and cannot be changed.\", BlockingIOCometSupport.class.getName(), ex);\n\n AsyncSupport current = asyncSupport;\n asyncSupport = asyncSupport.supportWebSocket() && !isJBoss ? new Tomcat7BIOSupportWithWebSocket(config) : new BlockingIOCometSupport(config);\n if (current instanceof AsynchronousProcessor) {\n ((AsynchronousProcessor) current).shutdown();\n }\n\n asyncSupport.init(config.getServletConfig());\n logger.warn(\"Using \" + asyncSupport.getClass().getName());\n\n a = asyncSupport.service(req, res);\n } else {\n logger.error(\"AtmosphereFramework exception\", ex);\n throw ex;\n }\n } finally {\n if (a != null) {\n notify(a.type(), req, res);\n }\n\n if (!externalizeDestroy) {\n if (req != null && a != null && a.type() != Action.TYPE.SUSPEND) {\n req.destroy();\n res.destroy();\n notify(Action.TYPE.DESTROYED, req, res);\n }\n }\n }\n return a;\n }\n\n /**\n * Return the default {@link Broadcaster} class name.\n *\n * @return the broadcasterClassName\n */\n public String getDefaultBroadcasterClassName() {\n return broadcasterClassName;\n }\n\n /**\n * Set the default {@link Broadcaster} class name.\n *\n * @param bccn the broadcasterClassName to set\n */\n public AtmosphereFramework setDefaultBroadcasterClassName(String bccn) {\n if (isBroadcasterSpecified) {\n logger.trace(\"Broadcaster {} already set in web.xml\", broadcasterClassName);\n return this;\n }\n isBroadcasterSpecified = true;\n\n broadcasterClassName = bccn;\n\n // Must reconfigure.\n broadcasterFactory = null;\n configureBroadcasterFactory();\n\n // We must recreate all previously created Broadcaster.\n for (AtmosphereHandlerWrapper w : atmosphereHandlers.values()) {\n // If case one listener is initializing the framework.\n if (w.broadcaster != null) {\n w.broadcaster = broadcasterFactory.lookup(w.broadcaster.getID(), true);\n }\n }\n return this;\n }\n\n /**\n * true if Atmosphere uses {@link AtmosphereResponseImpl#getOutputStream()}\n * by default for write operation.\n *\n * @return the useStreamForFlushingComments\n */\n public boolean isUseStreamForFlushingComments() {\n return useStreamForFlushingComments;\n }\n\n public boolean isUseServlet30() {\n return useServlet30;\n }\n\n /**\n * Set to true so Atmosphere uses {@link AtmosphereResponseImpl#getOutputStream()}\n * by default for write operation. Default is false.\n *\n * @param useStreamForFlushingComments the useStreamForFlushingComments to set\n */\n public AtmosphereFramework setUseStreamForFlushingComments(boolean useStreamForFlushingComments) {\n this.useStreamForFlushingComments = useStreamForFlushingComments;\n return this;\n }\n\n /**\n * Get the {@link BroadcasterFactory} which is used by Atmosphere to construct\n * {@link Broadcaster}.\n *\n * @return {@link BroadcasterFactory}\n */\n public BroadcasterFactory getBroadcasterFactory() {\n if (broadcasterFactory == null) {\n configureBroadcasterFactory();\n }\n return broadcasterFactory;\n }\n\n /**\n * Set the {@link BroadcasterFactory} which is used by Atmosphere to construct\n * {@link Broadcaster}.\n *\n * @return {@link BroadcasterFactory}\n */\n public AtmosphereFramework setBroadcasterFactory(final BroadcasterFactory broadcasterFactory) {\n this.broadcasterFactory = broadcasterFactory;\n configureBroadcaster();\n return this;\n }\n\n /**\n * Return the {@link org.atmosphere.cpr.BroadcasterCache} class name.\n *\n * @return the {@link org.atmosphere.cpr.BroadcasterCache} class name\n */\n public String getBroadcasterCacheClassName() {\n return broadcasterCacheClassName;\n }\n\n /**\n * Set the {@link org.atmosphere.cpr.BroadcasterCache} class name.\n *\n * @param broadcasterCacheClassName\n */\n public AtmosphereFramework setBroadcasterCacheClassName(String broadcasterCacheClassName) {\n this.broadcasterCacheClassName = broadcasterCacheClassName;\n return this;\n }\n\n /**\n * Add a new Broadcaster class name that AtmosphereServlet can use when initializing requests, and when the\n * atmosphere.xml broadcaster element is unspecified.\n *\n * @param broadcasterTypeString\n */\n public AtmosphereFramework addBroadcasterType(String broadcasterTypeString) {\n broadcasterTypes.add(broadcasterTypeString);\n return this;\n }\n\n public ConcurrentLinkedQueue broadcasterTypes() {\n return broadcasterTypes;\n }\n\n public String getWebSocketProtocolClassName() {\n return webSocketProtocolClassName;\n }\n\n public AtmosphereFramework setWebSocketProtocolClassName(String webSocketProtocolClassName) {\n hasNewWebSocketProtocol = true;\n this.webSocketProtocolClassName = webSocketProtocolClassName;\n return this;\n }\n\n public Map getAtmosphereHandlers() {\n return atmosphereHandlers;\n }\n\n protected Map configureQueryStringAsRequest(AtmosphereRequest request) {\n Map headers = new HashMap();\n\n StringBuilder q = new StringBuilder();\n try {\n String qs = request.getQueryString();\n if (qs != null && !qs.isEmpty()) {\n String[] params = qs.split(\"&\");\n String[] s;\n for (String p : params) {\n s = p.split(\"=\", 2);\n final String header = s[0];\n final String value = s.length > 1 ? s[1] : \"\";\n\n if (header.equalsIgnoreCase(\"Content-Type\")) {\n // Use the one set by the user first.\n if (request.getContentType() == null ||\n !request.getContentType().equalsIgnoreCase(s.length > 1 ? value : \"\")) {\n request.contentType(s.length > 1 ? URLDecoder.decode(value, \"UTF-8\") : \"\");\n }\n }\n if (!header.isEmpty()\n && !header.toLowerCase().startsWith(\"x-atmo\")\n && !header.equalsIgnoreCase(HeaderConfig.X_HEARTBEAT_SERVER)\n && !header.equalsIgnoreCase(\"Content-Type\")\n && !header.equalsIgnoreCase(\"_\")) {\n q.append(header).append(\"=\").append(s.length > 1 ? value : \"\").append(\"&\");\n }\n headers.put(header, s.length > 1 ? value : \"\");\n }\n }\n } catch (Exception ex) {\n logger.error(\"Unable to parse query string\", ex);\n }\n String disallowModifyQueryString = config.getInitParameter(ApplicationConfig.DISALLOW_MODIFY_QUERYSTRING);\n if (disallowModifyQueryString == null ||\n disallowModifyQueryString.length() == 0 || \"false\".equalsIgnoreCase(disallowModifyQueryString)) {\n if (q.length() > 0) {\n q.deleteCharAt(q.length() - 1);\n }\n request.queryString(q.toString());\n }\n\n logger.trace(\"Query String translated to headers {}\", headers);\n return headers;\n }\n\n public WebSocketProtocol getWebSocketProtocol() {\n // TODO: Spagetthi code, needs to rework.\n // Make sure we initialized the WebSocketProtocol\n initWebSocket();\n return webSocketProtocol;\n }\n\n public boolean isUseNativeImplementation() {\n return useNativeImplementation;\n }\n\n public AtmosphereFramework setUseNativeImplementation(boolean useNativeImplementation) {\n this.useNativeImplementation = useNativeImplementation;\n return this;\n }\n\n public boolean isUseBlockingImplementation() {\n return useBlockingImplementation;\n }\n\n public AtmosphereFramework setUseBlockingImplementation(boolean useBlockingImplementation) {\n this.useBlockingImplementation = useBlockingImplementation;\n return this;\n }\n\n public String getAtmosphereDotXmlPath() {\n return atmosphereDotXmlPath;\n }\n\n public AtmosphereFramework setAtmosphereDotXmlPath(String atmosphereDotXmlPath) {\n this.atmosphereDotXmlPath = atmosphereDotXmlPath;\n return this;\n }\n\n public String getHandlersPath() {\n return handlersPath;\n }\n\n public AtmosphereFramework setHandlersPath(String handlersPath) {\n this.handlersPath = handlersPath;\n return this;\n }\n\n /**\n * Return the location of the JARs containing the application classes. Default is WEB-INF/lib.\n *\n * @return the location of the JARs containing the application classes. Default is WEB-INF/lib\n */\n public String getLibPath() {\n return libPath;\n }\n\n /**\n * Set the location of the JARs containing the application.\n *\n * @param libPath the location of the JARs containing the application.\n * @return this\n */\n public AtmosphereFramework setLibPath(String libPath) {\n this.libPath = libPath;\n return this;\n }\n\n /**\n * The current {@link org.atmosphere.websocket.WebSocketProcessor} used to handle websocket requests.\n *\n * @return {@link org.atmosphere.websocket.WebSocketProcessor}\n */\n public String getWebSocketProcessorClassName() {\n return webSocketProcessorClassName;\n }\n\n /**\n * Set the {@link org.atmosphere.websocket.WebSocketProcessor} class name used to process WebSocket requests. Default is\n * {@link DefaultWebSocketProcessor}\n *\n * @param webSocketProcessorClassName {@link org.atmosphere.websocket.WebSocketProcessor}\n * @return this\n */\n public AtmosphereFramework setWebsocketProcessorClassName(String webSocketProcessorClassName) {\n this.webSocketProcessorClassName = webSocketProcessorClassName;\n return this;\n }\n\n /**\n * Add an {@link AtmosphereInterceptor} implementation. The adding order of {@link AtmosphereInterceptor} will be used, e.g\n * the first added {@link AtmosphereInterceptor} will always be called first.\n *\n * @param c {@link AtmosphereInterceptor}\n * @return this\n */\n public AtmosphereFramework interceptor(AtmosphereInterceptor c) {\n if (!checkDuplicate(c)) {\n interceptors.add(c);\n if (isInit) {\n addInterceptorToAllWrappers(c);\n }\n }\n return this;\n }\n\n protected void addDefaultOrAppInterceptors() {\n for (AtmosphereInterceptor c : interceptors) {\n addInterceptorToAllWrappers(c);\n }\n }\n\n protected void addInterceptorToAllWrappers(AtmosphereInterceptor c) {\n c.configure(config);\n InvokationOrder.PRIORITY p = InvokationOrder.class.isAssignableFrom(c.getClass()) ? ((InvokationOrder) c).priority() : InvokationOrder.AFTER_DEFAULT;\n\n logger.info(\"Installed AtmosphereInterceptor {} with priority {} \", c, p.name());\n //need insert this new interceptor into all the existing handlers\n for (AtmosphereHandlerWrapper wrapper : atmosphereHandlers.values()) {\n addInterceptorToWrapper(wrapper, c);\n }\n }\n\n protected void addInterceptorToWrapper(AtmosphereHandlerWrapper wrapper, AtmosphereInterceptor c) {\n if (!checkDuplicate(wrapper.interceptors, c.getClass())) {\n wrapper.interceptors.add(c);\n wrapper.interceptors.sort(new InterceptorComparator());\n }\n }\n\n protected void addInterceptorToWrapper(AtmosphereHandlerWrapper wrapper, List interceptors) {\n\n for (AtmosphereInterceptor c : this.interceptors) {\n addInterceptorToWrapper(wrapper, c);\n }\n\n for (AtmosphereInterceptor c : interceptors) {\n addInterceptorToWrapper(wrapper, c);\n c.configure(config);\n }\n }\n\n /**\n *

      \n * Checks if an instance of the specified {@link AtmosphereInterceptor} implementation exists in the\n * {@link #interceptors}.\n *

      \n *\n * @param c the implementation\n * @return {@code false} if an instance of the same interceptor's class already exists in {@link #interceptors}, {@code true} otherwise\n */\n private boolean checkDuplicate(final AtmosphereInterceptor c) {\n return checkDuplicate(interceptors, c.getClass());\n }\n\n /**\n *

      \n * Checks in the specified list if there is at least one instance of the given\n * {@link AtmosphereInterceptor interceptor} implementation class.\n *

      \n *\n * @param interceptorList the interceptors\n * @param c the interceptor class\n * @return {@code false} if an instance of the class already exists in the list, {@code true} otherwise\n */\n private boolean checkDuplicate(final List interceptorList, Class c) {\n for (final AtmosphereInterceptor i : interceptorList) {\n if (i.getClass().equals(c)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Return the list of {@link AtmosphereInterceptor}.\n *\n * @return the list of {@link AtmosphereInterceptor}\n */\n public LinkedList interceptors() {\n return interceptors;\n }\n\n /**\n * Set the {@link AnnotationProcessor} class name.\n *\n * @param annotationProcessorClassName the {@link AnnotationProcessor} class name.\n * @return this\n */\n public AtmosphereFramework annotationProcessorClassName(String annotationProcessorClassName) {\n this.annotationProcessorClassName = annotationProcessorClassName;\n return this;\n }\n\n /**\n * Add an {@link AsyncSupportListener}.\n *\n * @param asyncSupportListener an {@link AsyncSupportListener}\n * @return this;\n */\n public AtmosphereFramework asyncSupportListener(AsyncSupportListener asyncSupportListener) {\n asyncSupportListeners.add(asyncSupportListener);\n return this;\n }\n\n /**\n * Return the list of {@link AsyncSupportListener}s.\n *\n * @return\n */\n public List asyncSupportListeners() {\n return asyncSupportListeners;\n }\n\n /**\n * Add {@link BroadcasterListener} to all created {@link Broadcaster}s.\n */\n public AtmosphereFramework addBroadcasterListener(BroadcasterListener b) {\n broadcasterFactory.addBroadcasterListener(b);\n broadcasterListeners.add(b);\n return this;\n }\n\n /**\n * Add {@link BroadcasterCacheListener} to the {@link BroadcasterCache}.\n */\n public AtmosphereFramework addBroadcasterCacheListener(BroadcasterCacheListener b) {\n broadcasterCacheListeners.add(b);\n return this;\n }\n\n public List broadcasterCacheListeners() {\n return broadcasterCacheListeners;\n }\n\n /**\n * Add a {@link BroadcasterCacheInspector} which will be associated with the defined {@link BroadcasterCache}.\n *\n * @param b {@link BroadcasterCacheInspector}\n * @return this;\n */\n public AtmosphereFramework addBroadcasterCacheInjector(BroadcasterCacheInspector b) {\n inspectors.add(b);\n return this;\n }\n\n /**\n * Return the list of {@link BroadcasterCacheInspector}s.\n *\n * @return the list of {@link BroadcasterCacheInspector}s\n */\n public ConcurrentLinkedQueue inspectors() {\n return inspectors;\n }\n\n /**\n * Return a configured instance of {@link AtmosphereConfig}.\n *\n * @return a configured instance of {@link AtmosphereConfig}\n */\n public AtmosphereConfig getAtmosphereConfig() {\n return config;\n }\n\n /**\n * Return the {@link ServletContext}\n *\n * @return the {@link ServletContext}\n */\n public ServletContext getServletContext() {\n return servletConfig.getServletContext();\n }\n\n public ServletConfig getServletConfig() {\n return servletConfig;\n }\n\n /**\n * Return the list of {@link BroadcastFilter}s.\n *\n * @return the list of {@link BroadcastFilter}s\n */\n public List broadcasterFilters() {\n return broadcasterFilters;\n }\n\n /**\n * Add a {@link BroadcastFilter}.\n *\n * @return\n */\n public AtmosphereFramework broadcasterFilters(BroadcastFilter f) {\n broadcasterFilters.add(f.getClass().getName());\n\n for (Broadcaster b : config.getBroadcasterFactory().lookupAll()) {\n b.getBroadcasterConfig().addFilter(f);\n }\n return this;\n }\n\n /**\n * Returns true if {@link java.util.concurrent.ExecutorService} is shared among all components.\n *\n * @return true if {@link java.util.concurrent.ExecutorService} is shared amongst all components\n */\n public boolean isShareExecutorServices() {\n return sharedThreadPools;\n }\n\n /**\n * Set to true to have a {@link java.util.concurrent.ExecutorService} shared among all components.\n *\n * @param sharedThreadPools\n * @return this\n */\n public AtmosphereFramework shareExecutorServices(boolean sharedThreadPools) {\n this.sharedThreadPools = sharedThreadPools;\n return this;\n }\n\n protected void autoConfigureService(ServletContext sc) throws IOException {\n String path = handlersPath != DEFAULT_HANDLER_PATH ? handlersPath : realPath(sc, handlersPath);\n try {\n annotationProcessor = newClassInstance(AnnotationProcessor.class,\n (Class) IOUtils.loadClass(getClass(), annotationProcessorClassName));\n logger.info(\"Atmosphere is using {} for processing annotation\", annotationProcessorClassName);\n\n annotationProcessor.configure(config);\n\n if (!packages.isEmpty()) {\n for (String s : packages) {\n annotationProcessor.scan(s);\n }\n }\n\n // Second try.\n if (!annotationFound) {\n if (path != null) {\n annotationProcessor.scan(new File(path));\n }\n\n // Always scan library\n String pathLibs = !libPath.equals(DEFAULT_LIB_PATH) ? libPath : realPath(sc, DEFAULT_LIB_PATH);\n if (pathLibs != null) {\n File libFolder = new File(pathLibs);\n File[] jars = libFolder.listFiles((arg0, arg1) -> arg1.endsWith(\".jar\"));\n\n if (jars != null) {\n for (File file : jars) {\n annotationProcessor.scan(file);\n }\n }\n }\n }\n\n if (!annotationFound && allowAllClassesScan) {\n logger.debug(\"Scanning all classes on the classpath\");\n annotationProcessor.scanAll();\n }\n } catch (Throwable e) {\n logger.error(\"\", e);\n } finally {\n if (annotationProcessor != null) {\n annotationProcessor.destroy();\n }\n }\n }\n\n /**\n * The current {@link EndpointMapper} used to map requests to {@link AtmosphereHandler}.\n *\n * @return {@link EndpointMapper}\n */\n public EndpointMapper endPointMapper() {\n return endpointMapper;\n }\n\n /**\n * Set the {@link EndpointMapper}.\n *\n * @param endpointMapper {@link EndpointMapper}\n * @return this\n */\n public AtmosphereFramework endPointMapper(EndpointMapper endpointMapper) {\n this.endpointMapper = endpointMapper;\n return this;\n }\n\n /**\n * Add support for package detection of Atmosphere's Component.\n *\n * @param clazz a Class\n * @return this.\n */\n public AtmosphereFramework addAnnotationPackage(Class clazz) {\n if (clazz.getPackage() == null) {\n logger.error(\"Class {} must have a package defined\", clazz);\n } else {\n packages.add(clazz.getPackage().getName());\n }\n return this;\n }\n\n public AtmosphereFramework notify(Action.TYPE type, AtmosphereRequest request, AtmosphereResponse response) {\n for (AsyncSupportListener l : asyncSupportListeners()) {\n try {\n switch (type) {\n case TIMEOUT:\n l.onTimeout(request, response);\n break;\n case CANCELLED:\n l.onClose(request, response);\n break;\n case SUSPEND:\n l.onSuspend(request, response);\n break;\n case RESUME:\n l.onResume(request, response);\n break;\n case DESTROYED:\n l.onDestroyed(request, response);\n break;\n }\n } catch (Throwable t) {\n logger.warn(\"\", t);\n }\n }\n return this;\n }\n\n public AtmosphereFramework notifyDestroyed(String uuid) {\n for (AtmosphereResourceListener l : atmosphereResourceListeners()) {\n l.onDisconnect(uuid);\n }\n return this;\n }\n\n public AtmosphereFramework notifySuspended(String uuid) {\n for (AtmosphereResourceListener l : atmosphereResourceListeners()) {\n l.onSuspended(uuid);\n }\n return this;\n }\n\n /**\n * Add an {@link WebSocketHandler} mapped to \"/*\".\n * return this\n */\n public AtmosphereFramework addWebSocketHandler(WebSocketHandler handler) {\n addWebSocketHandler(ROOT_MASTER, handler);\n return this;\n }\n\n /**\n * Add an {@link WebSocketHandler} mapped to the path.\n * return this\n */\n public AtmosphereFramework addWebSocketHandler(String path, WebSocketHandler handler) {\n addWebSocketHandler(path, handler, REFLECTOR_ATMOSPHEREHANDLER, Collections.emptyList());\n return this;\n }\n\n /**\n * Add an {@link WebSocketHandler} mapped to the path and the {@link AtmosphereHandler} in case {@link Broadcaster} are\n * used.\n *\n * @param path a path\n * @param handler a {@link WebSocketHandler}\n * @param h an {@link AtmosphereHandler}\n * @return this\n */\n public AtmosphereFramework addWebSocketHandler(String path, WebSocketHandler handler, AtmosphereHandler h) {\n addWebSocketHandler(path, handler, REFLECTOR_ATMOSPHEREHANDLER, Collections.emptyList());\n return this;\n }\n\n /**\n * Add an {@link WebSocketHandler} mapped to the path and the {@link AtmosphereHandler} in case {@link Broadcaster} are\n * used.\n *\n * @param path a path\n * @param handler a {@link WebSocketHandler}\n * @param h an {@link AtmosphereHandler}\n * @param l {@link AtmosphereInterceptor}\n * @return this\n */\n public AtmosphereFramework addWebSocketHandler(String path, WebSocketHandler handler, AtmosphereHandler h, List l) {\n WebSocketProcessorFactory.getDefault().getWebSocketProcessor(this)\n .registerWebSocketHandler(path,\n new WebSocketProcessor.WebSocketHandlerProxy(broadcasterFactory.lookup(path, true).getClass(), handler));\n addAtmosphereHandler(path, h, l);\n return this;\n }\n\n /**\n * Invoked when a {@link AnnotationProcessor} found an annotation.\n *\n * @param b true when found\n * @return this\n */\n public AtmosphereFramework annotationScanned(boolean b) {\n annotationFound = b;\n return this;\n }\n\n /**\n * Return true if the {@link #init()} has been sucessfully executed.\n *\n * @return true if the {@link #init()} has been sucessfully executed.\n */\n public boolean initialized() {\n return isInit;\n }\n\n public List packages() {\n return packages;\n }\n\n /**\n * Return the list of packages the framework should look for {@link org.atmosphere.config.AtmosphereAnnotation}.\n *\n * @return the list of packages the framework should look for {@link org.atmosphere.config.AtmosphereAnnotation}\n */\n public List customAnnotationPackages() {\n return annotationPackages;\n }\n\n /**\n * Add a package containing classes annotated with {@link org.atmosphere.config.AtmosphereAnnotation}.\n *\n * @param p a package\n * @return this;\n */\n public AtmosphereFramework addCustomAnnotationPackage(Class p) {\n annotationPackages.addLast(p.getPackage().getName());\n return this;\n }\n\n /**\n * Instantiate a class\n *\n * @param classType The Required Class's Type\n * @param defaultType The default implementation of the Class's Type.\n * @return the an instance of defaultType\n * @throws InstantiationException\n * @throws IllegalAccessException\n */\n public T newClassInstance(Class classType, Class defaultType) throws InstantiationException, IllegalAccessException {\n return objectFactory.newClassInstance(classType, defaultType);\n }\n\n /**\n * Set an object used for class instantiation.\n * Allows for integration with dependency injection frameworks.\n *\n * @param objectFactory\n */\n public void objectFactory(AtmosphereObjectFactory objectFactory) {\n this.objectFactory = objectFactory;\n this.objectFactory.configure(config);\n }\n\n /**\n * If set to true, the task of finishing the request/response lifecycle will not be handled by this class.\n *\n * @param externalizeDestroy\n * @return this\n */\n public AtmosphereFramework externalizeDestroy(boolean externalizeDestroy) {\n this.externalizeDestroy = externalizeDestroy;\n return this;\n }\n\n /**\n * Return the {@link AnnotationProcessor}\n *\n * @return the {@link AnnotationProcessor}\n */\n public AnnotationProcessor annotationProcessor() {\n return annotationProcessor;\n }\n\n /**\n * Was a {@link Broadcaster} defined in web.xml or programmatically added.\n *\n * @return true is defined.\n */\n public boolean isBroadcasterSpecified() {\n return isBroadcasterSpecified;\n }\n\n protected void configureObjectFactory() {\n String s = config.getInitParameter(ApplicationConfig.OBJECT_FACTORY);\n if (s != null) {\n try {\n AtmosphereObjectFactory aci = (AtmosphereObjectFactory) IOUtils.loadClass(getClass(), s).newInstance();\n logger.debug(\"Found ObjectFactory {}\", aci.getClass().getName());\n objectFactory(aci);\n } catch (Exception ex) {\n logger.warn(\"Unable to load AtmosphereClassInstantiator instance\", ex);\n }\n }\n\n if (!DefaultAtmosphereObjectFactory.class.isAssignableFrom(objectFactory.getClass())) {\n logger.trace(\"ObjectFactory already set to {}\", objectFactory);\n }\n }\n\n /**\n * Exclude an {@link AtmosphereInterceptor} from being added, at startup, by Atmosphere. The default's {@link #DEFAULT_ATMOSPHERE_INTERCEPTORS}\n * are candidates for being excluded.\n *\n * @param interceptor an {@link AtmosphereInterceptor} class name\n * @return this\n */\n public AtmosphereFramework excludeInterceptor(String interceptor) {\n excludedInterceptors.add(interceptor);\n return this;\n }\n\n public AtmosphereFramework filterManipulator(BroadcasterConfig.FilterManipulator m) {\n filterManipulators.add(m);\n return this;\n }\n\n public List filterManipulators() {\n return filterManipulators;\n }\n\n public boolean isAServletFilter() {\n return isFilter;\n }\n\n public ConcurrentLinkedQueue objectFactoryType() {\n return objectFactoryType;\n }\n\n public String mappingRegex() {\n return mappingRegex;\n }\n\n public AtmosphereFramework mappingRegex(String mappingRegex) {\n this.mappingRegex = mappingRegex;\n return this;\n }\n\n public void setUseServlet30(boolean useServlet30) {\n this.useServlet30 = useServlet30;\n }\n\n public boolean webSocketEnabled() {\n return webSocketEnabled;\n }\n\n public AtmosphereFramework webSocketEnabled(boolean webSocketEnabled) {\n this.webSocketEnabled = webSocketEnabled;\n return this;\n }\n\n public String broadcasterLifeCyclePolicy() {\n return broadcasterLifeCyclePolicy;\n }\n\n public AtmosphereFramework broadcasterLifeCyclePolicy(String broadcasterLifeCyclePolicy) {\n this.broadcasterLifeCyclePolicy = broadcasterLifeCyclePolicy;\n return this;\n }\n\n public List broadcasterListeners() {\n return broadcasterListeners;\n }\n\n public boolean sharedThreadPools() {\n return sharedThreadPools;\n }\n\n public AtmosphereFramework sharedThreadPools(boolean sharedThreadPools) {\n this.sharedThreadPools = sharedThreadPools;\n return this;\n }\n\n public boolean allowAllClassesScan() {\n return allowAllClassesScan;\n }\n\n public AtmosphereFramework allowAllClassesScan(boolean allowAllClassesScan) {\n this.allowAllClassesScan = allowAllClassesScan;\n return this;\n }\n\n public AtmosphereObjectFactory objectFactory() {\n return objectFactory;\n }\n\n public boolean externalizeDestroy() {\n return externalizeDestroy;\n }\n\n public List excludedInterceptors() {\n return excludedInterceptors;\n }\n\n public Class[] defaultInterceptors() {\n return DEFAULT_ATMOSPHERE_INTERCEPTORS.toArray(new Class[DEFAULT_ATMOSPHERE_INTERCEPTORS.size()]);\n }\n\n public AtmosphereResourceFactory atmosphereFactory() {\n if (arFactory == null) {\n configureAtmosphereResourceFactory();\n }\n return arFactory;\n }\n\n private AtmosphereFramework configureAtmosphereResourceFactory() {\n if (arFactory != null) return this;\n\n synchronized (this) {\n try {\n arFactory = newClassInstance(AtmosphereResourceFactory.class, DefaultAtmosphereResourceFactory.class);\n } catch (InstantiationException | IllegalAccessException e) {\n logger.error(\"\", e);\n }\n arFactory.configure(config);\n }\n return this;\n }\n\n private AtmosphereFramework configureWebSocketFactory() {\n if (webSocketFactory != null) return this;\n\n synchronized (this) {\n try {\n webSocketFactory = newClassInstance(WebSocketFactory.class, DefaultWebSocketFactory.class);\n } catch (InstantiationException | IllegalAccessException e) {\n logger.error(\"\", e);\n }\n }\n return this;\n }\n\n public MetaBroadcaster metaBroadcaster() {\n return metaBroadcaster;\n }\n\n private AtmosphereFramework configureMetaBroadcaster() {\n try {\n metaBroadcaster = newClassInstance(MetaBroadcaster.class, DefaultMetaBroadcaster.class);\n metaBroadcaster.configure(config);\n } catch (InstantiationException | IllegalAccessException e) {\n logger.error(\"\", e);\n }\n return this;\n }\n\n /**\n * Get the default {@link org.atmosphere.cpr.Serializer} class name to use for {@link org.atmosphere.cpr.AtmosphereResource}s.\n *\n * @return the class name as a string, might be null if not configured\n */\n public String getDefaultSerializerClassName() {\n return defaultSerializerClassName;\n }\n\n /**\n * Get the default {@link org.atmosphere.cpr.Serializer} class to use for {@link org.atmosphere.cpr.AtmosphereResource}s.\n *\n * @return the class, might be null if not configured\n */\n public Class getDefaultSerializerClass() {\n return defaultSerializerClass;\n }\n\n /**\n * Set the default {@link org.atmosphere.cpr.Serializer} class name to use for {@link org.atmosphere.cpr.AtmosphereResource}s.\n *\n * @param defaultSerializerClassName the class name to use\n * @return this\n */\n public AtmosphereFramework setDefaultSerializerClassName(String defaultSerializerClassName) {\n this.defaultSerializerClassName = defaultSerializerClassName;\n initDefaultSerializer();\n return this;\n }\n\n private void initDefaultSerializer() {\n if (defaultSerializerClassName != null && !defaultSerializerClassName.isEmpty()) {\n try {\n @SuppressWarnings(\"unchecked\")\n Class clazz = (Class) IOUtils.loadClass(Serializer.class, defaultSerializerClassName);\n if (Serializer.class.isAssignableFrom(clazz)) {\n defaultSerializerClass = clazz;\n } else {\n logger.error(\"Default Serializer class name does not implement Serializer interface\");\n defaultSerializerClassName = null;\n defaultSerializerClass = null;\n }\n } catch (Exception e) {\n logger.error(\"Unable to set default Serializer\", e);\n defaultSerializerClassName = null;\n defaultSerializerClass = null;\n }\n } else {\n defaultSerializerClassName = null;\n defaultSerializerClass = null;\n }\n }\n\n /**\n * Return the {@link AtmosphereResourceSessionFactory}\n *\n * @return the AtmosphereResourceSessionFactory\n */\n public synchronized AtmosphereResourceSessionFactory sessionFactory() {\n if (sessionFactory == null) {\n try {\n sessionFactory = newClassInstance(AtmosphereResourceSessionFactory.class, DefaultAtmosphereResourceSessionFactory.class);\n } catch (InstantiationException | IllegalAccessException e) {\n logger.error(\"\", e);\n }\n }\n return sessionFactory;\n }\n\n /**\n * Return true is the {@link #destroy()} method has been invoked.\n *\n * @return true is the {@link #destroy()} method has been invoked.\n */\n public boolean isDestroyed() {\n return isDestroyed.get();\n }\n\n /**\n * Add a {@link org.atmosphere.cpr.AtmosphereFrameworkListener}\n *\n * @param l {@link org.atmosphere.cpr.AtmosphereFrameworkListener}\n * @return this;\n */\n public AtmosphereFramework frameworkListener(AtmosphereFrameworkListener l) {\n frameworkListeners.add(l);\n return this;\n }\n\n /**\n * Return the list of {@link org.atmosphere.cpr.AtmosphereFrameworkListener}\n *\n * @return {@link org.atmosphere.cpr.AtmosphereFrameworkListener}\n */\n public List frameworkListeners() {\n return frameworkListeners;\n }\n\n protected void onPreInit() {\n for (AtmosphereFrameworkListener l : frameworkListeners) {\n try {\n l.onPreInit(this);\n } catch (Exception e) {\n logger.error(\"\", e);\n }\n }\n }\n\n protected void onPostInit() {\n for (AtmosphereFrameworkListener l : frameworkListeners) {\n try {\n l.onPostInit(this);\n } catch (Exception e) {\n logger.error(\"\", e);\n }\n }\n }\n\n protected void onPreDestroy() {\n for (AtmosphereFrameworkListener l : frameworkListeners) {\n try {\n l.onPreDestroy(this);\n } catch (Exception e) {\n logger.error(\"\", e);\n }\n }\n }\n\n protected void onPostDestroy() {\n for (AtmosphereFrameworkListener l : frameworkListeners) {\n try {\n l.onPostDestroy(this);\n } catch (Exception e) {\n logger.error(\"\", e);\n }\n }\n }\n\n /**\n * Return the list of {@link org.atmosphere.cpr.AtmosphereResourceListener}\n *\n * @return the list of {@link org.atmosphere.cpr.AtmosphereResourceListener}\n */\n public List atmosphereResourceListeners() {\n return atmosphereResourceListeners;\n }\n\n /**\n * Add a {@link org.atmosphere.cpr.AtmosphereResourceListener}\n *\n * @param atmosphereResourceListener a {@link org.atmosphere.cpr.AtmosphereResourceListener}\n * @return this\n */\n public AtmosphereFramework atmosphereResourceListener(AtmosphereResourceListener atmosphereResourceListener) {\n atmosphereResourceListeners.add(atmosphereResourceListener);\n return this;\n }\n\n /**\n * Set a {@link java.util.UUID} like implementation for generating random UUID String\n *\n * @param uuidProvider\n * @return this\n */\n public AtmosphereFramework uuidProvider(UUIDProvider uuidProvider) {\n this.uuidProvider = uuidProvider;\n return this;\n }\n\n /**\n * Return the {@link org.atmosphere.util.UUIDProvider}\n *\n * @return {@link org.atmosphere.util.UUIDProvider}\n */\n public UUIDProvider uuidProvider() {\n return uuidProvider;\n }\n\n /**\n * Return the {@link WebSocketFactory}\n *\n * @return the {@link WebSocketFactory}\n */\n public WebSocketFactory webSocketFactory() {\n if (webSocketFactory == null) {\n configureWebSocketFactory();\n }\n return webSocketFactory;\n }\n\n /**\n * Configure the {@link WebSocketFactory}\n *\n * @param webSocketFactory the {@link WebSocketFactory}\n * @return this\n */\n public AtmosphereFramework webSocketFactory(WebSocketFactory webSocketFactory) {\n this.webSocketFactory = webSocketFactory;\n return this;\n }\n\n /**\n * If a {@link ContainerInitializer} fail, log the excetion here.\n *\n * @param initializationError\n */\n public void initializationError(IllegalStateException initializationError) {\n this.initializationError = initializationError;\n }\n}\n", "file_name": "AtmosphereFramework.java", "human_label": "Check whether there is at least one instance of the implementation class in the lists. If so, true is returned. Otherwise, false is returned.", "level": "project_runnable", "lineno": "2666", "name": "checkDuplicate", "oracle_context": "{ \"apis\" : \"[equals, getClass]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "org.atmosphere.cpr", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636766fe1a6d9265ec017821", "all_context": "{ \"class_level\" : \"import net.hasor.utils.ClassUtils;\\nimport net.hasor.utils.ObjectUtils;\\nimport java.io.Serializable;\\nimport java.lang.reflect.Array;\\nimport java.util.Collection;\\nimport java.util.Map;\\nimport java.util.WeakHashMap;\\nToStringStyle DEFAULT_STYLE;\\nToStringStyle MULTI_LINE_STYLE;\\nToStringStyle NO_FIELD_NAMES_STYLE;\\nToStringStyle SHORT_PREFIX_STYLE;\\nToStringStyle SIMPLE_STYLE;\\nThreadLocal REGISTRY;\\nboolean useFieldNames;\\nboolean useClassName;\\nboolean useShortClassName;\\nboolean useIdentityHashCode;\\nString contentStart;\\nString contentEnd;\\nString fieldNameValueSeparator;\\nboolean fieldSeparatorAtStart;\\nboolean fieldSeparatorAtEnd;\\nString fieldSeparator;\\nString arrayStart;\\nString arraySeparator;\\nboolean arrayContentDetail;\\nString arrayEnd;\\nboolean defaultFullDetail;\\nString nullText;\\nString sizeStartText;\\nString sizeEndText;\\nString summaryObjectStartText;\\nString summaryObjectEndText;\\nlong serialVersionUID;\\ngetRegistry();\\nregister(Object value);\\nunregister(Object value);\\nToStringStyle();\\nappendSuper(StringBuffer buffer,String superToString);\\nappendToString(StringBuffer buffer,String toString);\\nappendStart(StringBuffer buffer,Object object);\\nappendEnd(StringBuffer buffer,Object object);\\nremoveLastFieldSeparator(StringBuffer buffer);\\nappend(StringBuffer buffer,String fieldName,Object value,Boolean fullDetail);\\nappendInternal(StringBuffer buffer,String fieldName,Object value,boolean detail);\\nappendCyclicObject(StringBuffer buffer,String fieldName,Object value);\\nappendDetail(StringBuffer buffer,String fieldName,Object value);\\nappendDetail(StringBuffer buffer,String fieldName,Collection coll);\\nappendDetail(StringBuffer buffer,String fieldName,Map map);\\nappendSummary(StringBuffer buffer,String fieldName,Object value);\\nappend(StringBuffer buffer,String fieldName,long value);\\nappendDetail(StringBuffer buffer,String fieldName,long value);\\nappend(StringBuffer buffer,String fieldName,int value);\\nappendDetail(StringBuffer buffer,String fieldName,int value);\\nappend(StringBuffer buffer,String fieldName,short value);\\nappendDetail(StringBuffer buffer,String fieldName,short value);\\nappend(StringBuffer buffer,String fieldName,byte value);\\nappendDetail(StringBuffer buffer,String fieldName,byte value);\\nappend(StringBuffer buffer,String fieldName,char value);\\nappendDetail(StringBuffer buffer,String fieldName,char value);\\nappend(StringBuffer buffer,String fieldName,double value);\\nappendDetail(StringBuffer buffer,String fieldName,double value);\\nappend(StringBuffer buffer,String fieldName,float value);\\nappendDetail(StringBuffer buffer,String fieldName,float value);\\nappend(StringBuffer buffer,String fieldName,boolean value);\\nappendDetail(StringBuffer buffer,String fieldName,boolean value);\\nappend(StringBuffer buffer,String fieldName,Object[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,Object[] array);\\nreflectionAppendArrayDetail(StringBuffer buffer,String fieldName,Object array);\\nappendSummary(StringBuffer buffer,String fieldName,Object[] array);\\nappend(StringBuffer buffer,String fieldName,long[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,long[] array);\\nappendSummary(StringBuffer buffer,String fieldName,long[] array);\\nappend(StringBuffer buffer,String fieldName,int[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,int[] array);\\nappendSummary(StringBuffer buffer,String fieldName,int[] array);\\nappend(StringBuffer buffer,String fieldName,short[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,short[] array);\\nappendSummary(StringBuffer buffer,String fieldName,short[] array);\\nappend(StringBuffer buffer,String fieldName,byte[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,byte[] array);\\nappendSummary(StringBuffer buffer,String fieldName,byte[] array);\\nappend(StringBuffer buffer,String fieldName,char[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,char[] array);\\nappendSummary(StringBuffer buffer,String fieldName,char[] array);\\nappend(StringBuffer buffer,String fieldName,double[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,double[] array);\\nappendSummary(StringBuffer buffer,String fieldName,double[] array);\\nappend(StringBuffer buffer,String fieldName,float[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,float[] array);\\nappendSummary(StringBuffer buffer,String fieldName,float[] array);\\nappend(StringBuffer buffer,String fieldName,boolean[] array,Boolean fullDetail);\\nappendDetail(StringBuffer buffer,String fieldName,boolean[] array);\\nappendSummary(StringBuffer buffer,String fieldName,boolean[] array);\\nappendClassName(StringBuffer buffer,Object object);\\nappendIdentityHashCode(StringBuffer buffer,Object object);\\nappendContentStart(StringBuffer buffer);\\nappendContentEnd(StringBuffer buffer);\\nappendNullText(StringBuffer buffer,String fieldName);\\nappendFieldSeparator(StringBuffer buffer);\\nappendFieldStart(StringBuffer buffer,String fieldName);\\nappendFieldEnd(StringBuffer buffer,String fieldName);\\nappendSummarySize(StringBuffer buffer,String fieldName,int size);\\nisFullDetail(Boolean fullDetailRequest);\\ngetShortClassName(Class cls);\\nisUseClassName();\\nsetUseClassName(boolean useClassName);\\nisUseShortClassName();\\nisShortClassName();\\nsetUseShortClassName(boolean useShortClassName);\\nsetShortClassName(boolean shortClassName);\\nisUseIdentityHashCode();\\nsetUseIdentityHashCode(boolean useIdentityHashCode);\\nisUseFieldNames();\\nsetUseFieldNames(boolean useFieldNames);\\nisDefaultFullDetail();\\nsetDefaultFullDetail(boolean defaultFullDetail);\\nisArrayContentDetail();\\nsetArrayContentDetail(boolean arrayContentDetail);\\ngetArrayStart();\\nsetArrayStart(String arrayStart);\\ngetArrayEnd();\\nsetArrayEnd(String arrayEnd);\\ngetArraySeparator();\\nsetArraySeparator(String arraySeparator);\\ngetContentStart();\\nsetContentStart(String contentStart);\\ngetContentEnd();\\nsetContentEnd(String contentEnd);\\ngetFieldNameValueSeparator();\\nsetFieldNameValueSeparator(String fieldNameValueSeparator);\\ngetFieldSeparator();\\nsetFieldSeparator(String fieldSeparator);\\nisFieldSeparatorAtStart();\\nsetFieldSeparatorAtStart(boolean fieldSeparatorAtStart);\\nisFieldSeparatorAtEnd();\\nsetFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd);\\ngetNullText();\\nsetNullText(String nullText);\\ngetSizeStartText();\\nsetSizeStartText(String sizeStartText);\\ngetSizeEndText();\\nsetSizeEndText(String sizeEndText);\\ngetSummaryObjectStartText();\\nsetSummaryObjectStartText(String summaryObjectStartText);\\ngetSummaryObjectEndText();\\nsetSummaryObjectEndText(String summaryObjectEndText);\\nDefaultToStringStyle();\\nreadResolve();\\nNoFieldNameToStringStyle();\\nShortPrefixToStringStyle();\\nSimpleToStringStyle();\\nMultiLineToStringStyle();\\ngetSystemProperty(String property);\\nisRegistered(Object value);\\n\", \"repo_level\" : \"public interface ClassUtils {static String getShortClassName(Object object,String valueIfNull);\\nstatic String getShortClassName(Class cls);\\nstatic String getShortClassName(String className);\\nstatic String getPackageName(Object object,String valueIfNull);\\nstatic String getPackageName(Class cls);\\nstatic String getPackageName(String className);\\nstatic List> getAllSuperclasses(Class cls);\\nstatic List> getAllInterfaces(Class cls);\\nstatic List> convertClassNamesToClasses(List classNames);\\nstatic List convertClassesToClassNames(List classes);\\nstatic boolean isAssignable(Class[] classArray,Class[] toClassArray);\\nstatic boolean isAssignable(Class[] classArray,Class[] toClassArray,boolean autoboxing);\\nstatic boolean isAssignable(Class cls,Class toClass);\\nstatic boolean isAssignable(Class cls,Class toClass,boolean autoboxing);\\nstatic Class primitiveToWrapper(Class cls);\\nstatic Class[] primitivesToWrappers(Class[] classes);\\nstatic Class wrapperToPrimitive(Class cls);\\nstatic Class[] wrappersToPrimitives(Class[] classes);\\nstatic boolean isInnerClass(Class cls);\\nstatic Class getClass(ClassLoader classLoader,String className,boolean initialize);\\nstatic Class getClass(ClassLoader classLoader,String className);\\nstatic Class getClass(String className);\\nstatic Class getClass(String className,boolean initialize);\\nstatic Method getPublicMethod(Class cls,String methodName,Class parameterTypes);\\nstatic Class[] toClass(Object[] array);\\nstatic String getShortCanonicalName(Object object,String valueIfNull);\\nstatic String getShortCanonicalName(Class cls);\\nstatic String getShortCanonicalName(String canonicalName);\\nstatic String getPackageCanonicalName(Object object,String valueIfNull);\\nstatic String getPackageCanonicalName(Class cls);\\nstatic String getPackageCanonicalName(String canonicalName);\\nstatic ClassLoader getClassLoader(ClassLoader classLoader);\\nstatic boolean isLangClass(Class target);\\nstatic String getDescName(Class type);\\nstatic String getDescNameWithOutModifiers(Method method);\\nstatic String getDescName(Method method);\\nstatic Class getSuperClassGenricType(Class clazz,int index);\\nstatic T newInstance(Class clazz);\\n }\\npublic interface ObjectUtils {static Object defaultIfNull(Object object,Object defaultValue);\\nstatic boolean equals(Object object1,Object object2);\\nstatic boolean notEqual(Object object1,Object object2);\\nstatic int hashCode(Object obj);\\nstatic String identityToString(Object object);\\nstatic void identityToString(StringBuffer buffer,Object object);\\nstatic String toString(Object obj);\\nstatic String toString(Object obj,String nullStr);\\nstatic Object min(Comparable c1,Comparable c2);\\nstatic Object max(Comparable c1,Comparable c2);\\nstatic int compare(Comparable c1,Comparable c2);\\nstatic int compare(Comparable c1,Comparable c2,boolean nullGreater);\\n }\\n\" }", "class_name": "ToStringStyle", "code": "protected void appendDetail(StringBuffer buffer,String fieldName,byte[] array){\n buffer.append(arrayStart);\n for (int i=0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer,fieldName,array[i]);\n }\n buffer.append(arrayEnd);\n}\n", "docstring": "/** \n *

      Append to the toString the detail of a byte array.

      \n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,not null\n */\n", "end_lineno": "1092", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.builder;\nimport net.hasor.utils.ClassUtils;\nimport net.hasor.utils.ObjectUtils;\n\nimport java.io.Serializable;\nimport java.lang.reflect.Array;\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.WeakHashMap;\n\n/**\n *

      Controls String formatting for {@link ToStringBuilder}.\n * The main public interface is always via ToStringBuilder.

      \n *\n *

      These classes are intended to be used as Singletons.\n * There is no need to instantiate a new style each time. A program\n * will generally use one of the predefined constants on this class.\n * Alternatively, the {@link StandardToStringStyle} class can be used\n * to set the individual settings. Thus most styles can be achieved\n * without subclassing.

      \n *\n *

      If required, a subclass can override as many or as few of the\n * methods as it requires. Each object type (from boolean\n * to long to Object to int[]) has\n * its own methods to output it. Most have two versions, detail and summary.\n *\n *

      For example, the detail version of the array based methods will\n * output the whole array, whereas the summary method will just output\n * the array length.

      \n *\n *

      If you want to format the output of certain objects, such as dates, you\n * must create a subclass and override a method.\n *

      \n * public class MyStyle extends ToStringStyle {\n *   protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {\n *     if (value instanceof Date) {\n *       value = new SimpleDateFormat(\"yyyy-MM-dd\").format(value);\n *     }\n *     buffer.append(value);\n *   }\n * }\n * 
      \n *

      \n *\n * @author Apache Software Foundation\n * @author Gary Gregory\n * @author Pete Gieser\n * @author Masato Tezuka\n * @since 1.0\n * @version $Id: ToStringStyle.java 907168 2010-02-06 03:33:50Z mbenson $\n */\npublic abstract class ToStringStyle implements Serializable {\n /**\n * The default toString style. Using the Using the Person\n * example from {@link ToStringBuilder}, the output would look like this:\n *\n *
      \n     * Person@182f0db[name=John Doe,age=33,smoker=false]\n     * 
      \n */\n public static final ToStringStyle DEFAULT_STYLE = new DefaultToStringStyle();\n /**\n * The multi line toString style. Using the Using the Person\n * example from {@link ToStringBuilder}, the output would look like this:\n *\n *
      \n     * Person@182f0db[\n     *   name=John Doe\n     *   age=33\n     *   smoker=false\n     * ]\n     * 
      \n */\n public static final ToStringStyle MULTI_LINE_STYLE = new MultiLineToStringStyle();\n /**\n * The no field names toString style. Using the Using the\n * Person example from {@link ToStringBuilder}, the output\n * would look like this:\n *\n *
      \n     * Person@182f0db[John Doe,33,false]\n     * 
      \n */\n public static final ToStringStyle NO_FIELD_NAMES_STYLE = new NoFieldNameToStringStyle();\n /**\n * The short prefix toString style. Using the Person example\n * from {@link ToStringBuilder}, the output would look like this:\n *\n *
      \n     * Person[name=John Doe,age=33,smoker=false]\n     * 
      \n *\n * @since 2.1\n */\n public static final ToStringStyle SHORT_PREFIX_STYLE = new ShortPrefixToStringStyle();\n /**\n * The simple toString style. Using the Using the Person\n * example from {@link ToStringBuilder}, the output would look like this:\n *\n *
      \n     * John Doe,33,false\n     * 
      \n */\n public static final ToStringStyle SIMPLE_STYLE = new SimpleToStringStyle();\n /**\n *

      \n * A registry of objects used by reflectionToString methods\n * to detect cyclical object references and avoid infinite loops.\n *

      \n */\n private static final ThreadLocal REGISTRY = new ThreadLocal();\n\n /**\n *

      \n * Returns the registry of objects being traversed by the reflectionToString\n * methods in the current thread.\n *

      \n *\n * @return Set the registry of objects being traversed\n */\n static Map getRegistry() {\n return (Map) REGISTRY.get();\n }\n\n /**\n *

      \n * Returns true if the registry contains the given object.\n * Used by the reflection methods to avoid infinite loops.\n *

      \n *\n * @param value\n * The object to lookup in the registry.\n * @return boolean true if the registry contains the given\n * object.\n */\n static boolean isRegistered(Object value) {\n Map m = getRegistry();\n return m != null && m.containsKey(value);\n }\n\n /**\n *

      \n * Registers the given object. Used by the reflection methods to avoid\n * infinite loops.\n *

      \n *\n * @param value\n * The object to register.\n */\n static void register(Object value) {\n if (value != null) {\n Map m = getRegistry();\n if (m == null) {\n m = new WeakHashMap();\n REGISTRY.set(m);\n }\n m.put(value, null);\n }\n }\n\n /**\n *

      \n * Unregisters the given object.\n *

      \n *\n *

      \n * Used by the reflection methods to avoid infinite loops.\n *

      \n *\n * @param value\n * The object to unregister.\n */\n static void unregister(Object value) {\n if (value != null) {\n Map m = getRegistry();\n if (m != null) {\n m.remove(value);\n if (m.isEmpty()) {\n REGISTRY.set(null);\n }\n }\n }\n }\n\n /**\n * Whether to use the field names, the default is true.\n */\n private boolean useFieldNames = true;\n /**\n * Whether to use the class name, the default is true.\n */\n private boolean useClassName = true;\n /**\n * Whether to use short class names, the default is false.\n */\n private boolean useShortClassName = false;\n /**\n * Whether to use the identity hash code, the default is true.\n */\n private boolean useIdentityHashCode = true;\n /**\n * The content start '['.\n */\n private String contentStart = \"[\";\n /**\n * The content end ']'.\n */\n private String contentEnd = \"]\";\n /**\n * The field name value separator '='.\n */\n private String fieldNameValueSeparator = \"=\";\n /**\n * Whether the field separator should be added before any other fields.\n */\n private boolean fieldSeparatorAtStart = false;\n /**\n * Whether the field separator should be added after any other fields.\n */\n private boolean fieldSeparatorAtEnd = false;\n /**\n * The field separator ','.\n */\n private String fieldSeparator = \",\";\n /**\n * The array start '{'.\n */\n private String arrayStart = \"{\";\n /**\n * The array separator ','.\n */\n private String arraySeparator = \",\";\n /**\n * The detail for array content.\n */\n private boolean arrayContentDetail = true;\n /**\n * The array end '}'.\n */\n private String arrayEnd = \"}\";\n /**\n * The value to use when fullDetail is null,\n * the default value is true.\n */\n private boolean defaultFullDetail = true;\n /**\n * The null text '<null>'.\n */\n private String nullText = \"\";\n /**\n * The summary size text start '.\n */\n private String sizeStartText = \"'>'.\n */\n private String sizeEndText = \">\";\n /**\n * The summary object text start '<'.\n */\n private String summaryObjectStartText = \"<\";\n /**\n * The summary object text start '>'.\n */\n private String summaryObjectEndText = \">\";\n //----------------------------------------------------------------------------\n\n /**\n *

      Constructor.

      \n */\n protected ToStringStyle() {\n super();\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString the superclass toString.

      \n *

      NOTE: It assumes that the toString has been created from the same ToStringStyle.

      \n *\n *

      A null superToString is ignored.

      \n *\n * @param buffer the StringBuffer to populate\n * @param superToString the super.toString()\n * @since 2.0\n */\n public void appendSuper(StringBuffer buffer, String superToString) {\n appendToString(buffer, superToString);\n }\n\n /**\n *

      Append to the toString another toString.

      \n *

      NOTE: It assumes that the toString has been created from the same ToStringStyle.

      \n *\n *

      A null toString is ignored.

      \n *\n * @param buffer the StringBuffer to populate\n * @param toString the additional toString\n * @since 2.0\n */\n public void appendToString(StringBuffer buffer, String toString) {\n if (toString != null) {\n int pos1 = toString.indexOf(contentStart) + contentStart.length();\n int pos2 = toString.lastIndexOf(contentEnd);\n if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) {\n String data = toString.substring(pos1, pos2);\n if (fieldSeparatorAtStart) {\n removeLastFieldSeparator(buffer);\n }\n buffer.append(data);\n appendFieldSeparator(buffer);\n }\n }\n }\n\n /**\n *

      Append to the toString the start of data indicator.

      \n *\n * @param buffer the StringBuffer to populate\n * @param object the Object to build a toString for\n */\n public void appendStart(StringBuffer buffer, Object object) {\n if (object != null) {\n appendClassName(buffer, object);\n appendIdentityHashCode(buffer, object);\n appendContentStart(buffer);\n if (fieldSeparatorAtStart) {\n appendFieldSeparator(buffer);\n }\n }\n }\n\n /**\n *

      Append to the toString the end of data indicator.

      \n *\n * @param buffer the StringBuffer to populate\n * @param object the Object to build a\n * toString for.\n */\n public void appendEnd(StringBuffer buffer, Object object) {\n if (this.fieldSeparatorAtEnd == false) {\n removeLastFieldSeparator(buffer);\n }\n appendContentEnd(buffer);\n unregister(object);\n }\n\n /**\n *

      Remove the last field separator from the buffer.

      \n *\n * @param buffer the StringBuffer to populate\n * @since 2.0\n */\n protected void removeLastFieldSeparator(StringBuffer buffer) {\n int len = buffer.length();\n int sepLen = fieldSeparator.length();\n if (len > 0 && sepLen > 0 && len >= sepLen) {\n boolean match = true;\n for (int i = 0; i < sepLen; i++) {\n if (buffer.charAt(len - 1 - i) != fieldSeparator.charAt(sepLen - 1 - i)) {\n match = false;\n break;\n }\n }\n if (match) {\n buffer.setLength(len - sepLen);\n }\n }\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString an Object\n * value, printing the full toString of the\n * Object passed in.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (value == null) {\n appendNullText(buffer, fieldName);\n } else {\n appendInternal(buffer, fieldName, value, isFullDetail(fullDetail));\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString an Object,\n * correctly interpreting its type.

      \n *\n *

      This method performs the main lookup by Class type to correctly\n * route arrays, Collections, Maps and\n * Objects to the appropriate method.

      \n *\n *

      Either detail or summary views can be specified.

      \n *\n *

      If a cycle is detected, an object will be appended with the\n * Object.toString() format.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString,\n * not null\n * @param detail output detail or not\n */\n protected void appendInternal(StringBuffer buffer, String fieldName, Object value, boolean detail) {\n if (isRegistered(value) && !(value instanceof Number || value instanceof Boolean || value instanceof Character)) {\n appendCyclicObject(buffer, fieldName, value);\n return;\n }\n register(value);\n try {\n if (value instanceof Collection) {\n if (detail) {\n appendDetail(buffer, fieldName, (Collection) value);\n } else {\n appendSummarySize(buffer, fieldName, ((Collection) value).size());\n }\n } else if (value instanceof Map) {\n if (detail) {\n appendDetail(buffer, fieldName, (Map) value);\n } else {\n appendSummarySize(buffer, fieldName, ((Map) value).size());\n }\n } else if (value instanceof long[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (long[]) value);\n } else {\n appendSummary(buffer, fieldName, (long[]) value);\n }\n } else if (value instanceof int[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (int[]) value);\n } else {\n appendSummary(buffer, fieldName, (int[]) value);\n }\n } else if (value instanceof short[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (short[]) value);\n } else {\n appendSummary(buffer, fieldName, (short[]) value);\n }\n } else if (value instanceof byte[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (byte[]) value);\n } else {\n appendSummary(buffer, fieldName, (byte[]) value);\n }\n } else if (value instanceof char[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (char[]) value);\n } else {\n appendSummary(buffer, fieldName, (char[]) value);\n }\n } else if (value instanceof double[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (double[]) value);\n } else {\n appendSummary(buffer, fieldName, (double[]) value);\n }\n } else if (value instanceof float[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (float[]) value);\n } else {\n appendSummary(buffer, fieldName, (float[]) value);\n }\n } else if (value instanceof boolean[]) {\n if (detail) {\n appendDetail(buffer, fieldName, (boolean[]) value);\n } else {\n appendSummary(buffer, fieldName, (boolean[]) value);\n }\n } else if (value.getClass().isArray()) {\n if (detail) {\n appendDetail(buffer, fieldName, (Object[]) value);\n } else {\n appendSummary(buffer, fieldName, (Object[]) value);\n }\n } else {\n if (detail) {\n appendDetail(buffer, fieldName, value);\n } else {\n appendSummary(buffer, fieldName, value);\n }\n }\n } finally {\n unregister(value);\n }\n }\n\n /**\n *

      Append to the toString an Object\n * value that has been detected to participate in a cycle. This\n * implementation will print the standard string value of the value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString,\n * not null\n *\n * @since 2.2\n */\n protected void appendCyclicObject(StringBuffer buffer, String fieldName, Object value) {\n ObjectUtils.identityToString(buffer, value);\n }\n\n /**\n *

      Append to the toString an Object\n * value, printing the full detail of the Object.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {\n buffer.append(value);\n }\n\n /**\n *

      Append to the toString a Collection.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param coll the Collection to add to the\n * toString, not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, Collection coll) {\n buffer.append(coll);\n }\n\n /**\n *

      Append to the toString a Map.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param map the Map to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, Map map) {\n buffer.append(map);\n }\n\n /**\n *

      Append to the toString an Object\n * value, printing a summary of the Object.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, Object value) {\n buffer.append(summaryObjectStartText);\n buffer.append(getShortClassName(value.getClass()));\n buffer.append(summaryObjectEndText);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a long\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, long value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a long\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, long value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString an int\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, int value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString an int\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, int value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a short\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, short value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a short\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, short value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a byte\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, byte value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a byte\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, byte value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a char\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, char value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a char\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, char value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a double\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, double value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a double\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, double value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a float\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, float value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a float\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, float value) {\n buffer.append(value);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a boolean\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param value the value to add to the toString\n */\n public void append(StringBuffer buffer, String fieldName, boolean value) {\n appendFieldStart(buffer, fieldName);\n appendDetail(buffer, fieldName, value);\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString a boolean\n * value.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param value the value to add to the toString\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, boolean value) {\n buffer.append(value);\n }\n\n /**\n *

      Append to the toString an Object\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, Object[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString the detail of an\n * Object array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, Object[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n Object item = array[i];\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n if (item == null) {\n appendNullText(buffer, fieldName);\n } else {\n appendInternal(buffer, fieldName, item, arrayContentDetail);\n }\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString the detail of an array type.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n * @since 2.0\n */\n protected void reflectionAppendArrayDetail(StringBuffer buffer, String fieldName, Object array) {\n buffer.append(arrayStart);\n int length = Array.getLength(array);\n for (int i = 0; i < length; i++) {\n Object item = Array.get(array, i);\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n if (item == null) {\n appendNullText(buffer, fieldName);\n } else {\n appendInternal(buffer, fieldName, item, arrayContentDetail);\n }\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of an\n * Object array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, Object[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a long\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, long[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * long array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, long[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * long array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, long[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString an int\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, int[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of an\n * int array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, int[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of an\n * int array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, int[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a short\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, short[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * short array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, short[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * short array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, short[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a byte\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, byte[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * byte array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, byte[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * byte array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, byte[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a char\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, char[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * char array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, char[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * char array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, char[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a double\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * double array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, double[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * double array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, double[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a float\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, float[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * float array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, float[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * float array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, float[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString a boolean\n * array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n * @param array the array to add to the toString\n * @param fullDetail true for detail, false\n * for summary info, null for style decides\n */\n public void append(StringBuffer buffer, String fieldName, boolean[] array, Boolean fullDetail) {\n appendFieldStart(buffer, fieldName);\n if (array == null) {\n appendNullText(buffer, fieldName);\n } else if (isFullDetail(fullDetail)) {\n appendDetail(buffer, fieldName, array);\n } else {\n appendSummary(buffer, fieldName, array);\n }\n appendFieldEnd(buffer, fieldName);\n }\n\n /**\n *

      Append to the toString the detail of a\n * boolean array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendDetail(StringBuffer buffer, String fieldName, boolean[] array) {\n buffer.append(arrayStart);\n for (int i = 0; i < array.length; i++) {\n if (i > 0) {\n buffer.append(arraySeparator);\n }\n appendDetail(buffer, fieldName, array[i]);\n }\n buffer.append(arrayEnd);\n }\n\n /**\n *

      Append to the toString a summary of a\n * boolean array.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param array the array to add to the toString,\n * not null\n */\n protected void appendSummary(StringBuffer buffer, String fieldName, boolean[] array) {\n appendSummarySize(buffer, fieldName, array.length);\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Append to the toString the class name.

      \n *\n * @param buffer the StringBuffer to populate\n * @param object the Object whose name to output\n */\n protected void appendClassName(StringBuffer buffer, Object object) {\n if (useClassName && object != null) {\n register(object);\n if (useShortClassName) {\n buffer.append(getShortClassName(object.getClass()));\n } else {\n buffer.append(object.getClass().getName());\n }\n }\n }\n\n /**\n *

      Append the {@link System#identityHashCode(java.lang.Object)}.

      \n *\n * @param buffer the StringBuffer to populate\n * @param object the Object whose id to output\n */\n protected void appendIdentityHashCode(StringBuffer buffer, Object object) {\n if (this.isUseIdentityHashCode() && object != null) {\n register(object);\n buffer.append('@');\n buffer.append(Integer.toHexString(System.identityHashCode(object)));\n }\n }\n\n /**\n *

      Append to the toString the content start.

      \n *\n * @param buffer the StringBuffer to populate\n */\n protected void appendContentStart(StringBuffer buffer) {\n buffer.append(contentStart);\n }\n\n /**\n *

      Append to the toString the content end.

      \n *\n * @param buffer the StringBuffer to populate\n */\n protected void appendContentEnd(StringBuffer buffer) {\n buffer.append(contentEnd);\n }\n\n /**\n *

      Append to the toString an indicator for null.

      \n *\n *

      The default indicator is '<null>'.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n */\n protected void appendNullText(StringBuffer buffer, String fieldName) {\n buffer.append(nullText);\n }\n\n /**\n *

      Append to the toString the field separator.

      \n *\n * @param buffer the StringBuffer to populate\n */\n protected void appendFieldSeparator(StringBuffer buffer) {\n buffer.append(fieldSeparator);\n }\n\n /**\n *

      Append to the toString the field start.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name\n */\n protected void appendFieldStart(StringBuffer buffer, String fieldName) {\n if (useFieldNames && fieldName != null) {\n buffer.append(fieldName);\n buffer.append(fieldNameValueSeparator);\n }\n }\n\n /**\n *

      Append to the toString the field end.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n */\n protected void appendFieldEnd(StringBuffer buffer, String fieldName) {\n appendFieldSeparator(buffer);\n }\n\n /**\n *

      Append to the toString a size summary.

      \n *\n *

      The size summary is used to summarize the contents of\n * Collections, Maps and arrays.

      \n *\n *

      The output consists of a prefix, the passed in size\n * and a suffix.

      \n *\n *

      The default format is '<size=n>'.

      \n *\n * @param buffer the StringBuffer to populate\n * @param fieldName the field name, typically not used as already appended\n * @param size the size to append\n */\n protected void appendSummarySize(StringBuffer buffer, String fieldName, int size) {\n buffer.append(sizeStartText);\n buffer.append(size);\n buffer.append(sizeEndText);\n }\n\n /**\n *

      Is this field to be output in full detail.

      \n *\n *

      This method converts a detail request into a detail level.\n * The calling code may request full detail (true),\n * but a subclass might ignore that and always return\n * false. The calling code may pass in\n * null indicating that it doesn't care about\n * the detail level. In this case the default detail level is\n * used.

      \n *\n * @param fullDetailRequest the detail level requested\n * @return whether full detail is to be shown\n */\n protected boolean isFullDetail(Boolean fullDetailRequest) {\n if (fullDetailRequest == null) {\n return defaultFullDetail;\n }\n return fullDetailRequest;\n }\n\n /**\n *

      Gets the short class name for a class.

      \n *\n *

      The short class name is the classname excluding\n * the package name.

      \n *\n * @param cls the Class to get the short name of\n * @return the short name\n */\n protected String getShortClassName(Class cls) {\n return ClassUtils.getShortClassName(cls);\n }\n // Setters and getters for the customizable parts of the style\n // These methods are not expected to be overridden, except to make public\n // (They are not public so that immutable subclasses can be written)\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether to use the class name.

      \n *\n * @return the current useClassName flag\n */\n protected boolean isUseClassName() {\n return useClassName;\n }\n\n /**\n *

      Sets whether to use the class name.

      \n *\n * @param useClassName the new useClassName flag\n */\n protected void setUseClassName(boolean useClassName) {\n this.useClassName = useClassName;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether to output short or long class names.

      \n *\n * @return the current useShortClassName flag\n * @since 2.0\n */\n protected boolean isUseShortClassName() {\n return useShortClassName;\n }\n\n /**\n *

      Gets whether to output short or long class names.

      \n *\n * @return the current shortClassName flag\n * @deprecated Use {@link #isUseShortClassName()}\n * Method will be removed in Commons Lang 3.0.\n */\n protected boolean isShortClassName() {\n return useShortClassName;\n }\n\n /**\n *

      Sets whether to output short or long class names.

      \n *\n * @param useShortClassName the new useShortClassName flag\n * @since 2.0\n */\n protected void setUseShortClassName(boolean useShortClassName) {\n this.useShortClassName = useShortClassName;\n }\n\n /**\n *

      Sets whether to output short or long class names.

      \n *\n * @param shortClassName the new shortClassName flag\n * @deprecated Use {@link #setUseShortClassName(boolean)}\n * Method will be removed in Commons Lang 3.0.\n */\n protected void setShortClassName(boolean shortClassName) {\n this.useShortClassName = shortClassName;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether to use the identity hash code.

      \n *\n * @return the current useIdentityHashCode flag\n */\n protected boolean isUseIdentityHashCode() {\n return useIdentityHashCode;\n }\n\n /**\n *

      Sets whether to use the identity hash code.

      \n *\n * @param useIdentityHashCode the new useIdentityHashCode flag\n */\n protected void setUseIdentityHashCode(boolean useIdentityHashCode) {\n this.useIdentityHashCode = useIdentityHashCode;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether to use the field names passed in.

      \n *\n * @return the current useFieldNames flag\n */\n protected boolean isUseFieldNames() {\n return useFieldNames;\n }\n\n /**\n *

      Sets whether to use the field names passed in.

      \n *\n * @param useFieldNames the new useFieldNames flag\n */\n protected void setUseFieldNames(boolean useFieldNames) {\n this.useFieldNames = useFieldNames;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether to use full detail when the caller doesn't\n * specify.

      \n *\n * @return the current defaultFullDetail flag\n */\n protected boolean isDefaultFullDetail() {\n return defaultFullDetail;\n }\n\n /**\n *

      Sets whether to use full detail when the caller doesn't\n * specify.

      \n *\n * @param defaultFullDetail the new defaultFullDetail flag\n */\n protected void setDefaultFullDetail(boolean defaultFullDetail) {\n this.defaultFullDetail = defaultFullDetail;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether to output array content detail.

      \n *\n * @return the current array content detail setting\n */\n protected boolean isArrayContentDetail() {\n return arrayContentDetail;\n }\n\n /**\n *

      Sets whether to output array content detail.

      \n *\n * @param arrayContentDetail the new arrayContentDetail flag\n */\n protected void setArrayContentDetail(boolean arrayContentDetail) {\n this.arrayContentDetail = arrayContentDetail;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the array start text.

      \n *\n * @return the current array start text\n */\n protected String getArrayStart() {\n return arrayStart;\n }\n\n /**\n *

      Sets the array start text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param arrayStart the new array start text\n */\n protected void setArrayStart(String arrayStart) {\n if (arrayStart == null) {\n arrayStart = \"\";\n }\n this.arrayStart = arrayStart;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the array end text.

      \n *\n * @return the current array end text\n */\n protected String getArrayEnd() {\n return arrayEnd;\n }\n\n /**\n *

      Sets the array end text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param arrayEnd the new array end text\n */\n protected void setArrayEnd(String arrayEnd) {\n if (arrayEnd == null) {\n arrayEnd = \"\";\n }\n this.arrayEnd = arrayEnd;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the array separator text.

      \n *\n * @return the current array separator text\n */\n protected String getArraySeparator() {\n return arraySeparator;\n }\n\n /**\n *

      Sets the array separator text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param arraySeparator the new array separator text\n */\n protected void setArraySeparator(String arraySeparator) {\n if (arraySeparator == null) {\n arraySeparator = \"\";\n }\n this.arraySeparator = arraySeparator;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the content start text.

      \n *\n * @return the current content start text\n */\n protected String getContentStart() {\n return contentStart;\n }\n\n /**\n *

      Sets the content start text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param contentStart the new content start text\n */\n protected void setContentStart(String contentStart) {\n if (contentStart == null) {\n contentStart = \"\";\n }\n this.contentStart = contentStart;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the content end text.

      \n *\n * @return the current content end text\n */\n protected String getContentEnd() {\n return contentEnd;\n }\n\n /**\n *

      Sets the content end text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param contentEnd the new content end text\n */\n protected void setContentEnd(String contentEnd) {\n if (contentEnd == null) {\n contentEnd = \"\";\n }\n this.contentEnd = contentEnd;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the field name value separator text.

      \n *\n * @return the current field name value separator text\n */\n protected String getFieldNameValueSeparator() {\n return fieldNameValueSeparator;\n }\n\n /**\n *

      Sets the field name value separator text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param fieldNameValueSeparator the new field name value separator text\n */\n protected void setFieldNameValueSeparator(String fieldNameValueSeparator) {\n if (fieldNameValueSeparator == null) {\n fieldNameValueSeparator = \"\";\n }\n this.fieldNameValueSeparator = fieldNameValueSeparator;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the field separator text.

      \n *\n * @return the current field separator text\n */\n protected String getFieldSeparator() {\n return fieldSeparator;\n }\n\n /**\n *

      Sets the field separator text.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param fieldSeparator the new field separator text\n */\n protected void setFieldSeparator(String fieldSeparator) {\n if (fieldSeparator == null) {\n fieldSeparator = \"\";\n }\n this.fieldSeparator = fieldSeparator;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether the field separator should be added at the start\n * of each buffer.

      \n *\n * @return the fieldSeparatorAtStart flag\n * @since 2.0\n */\n protected boolean isFieldSeparatorAtStart() {\n return fieldSeparatorAtStart;\n }\n\n /**\n *

      Sets whether the field separator should be added at the start\n * of each buffer.

      \n *\n * @param fieldSeparatorAtStart the fieldSeparatorAtStart flag\n * @since 2.0\n */\n protected void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) {\n this.fieldSeparatorAtStart = fieldSeparatorAtStart;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets whether the field separator should be added at the end\n * of each buffer.

      \n *\n * @return fieldSeparatorAtEnd flag\n * @since 2.0\n */\n protected boolean isFieldSeparatorAtEnd() {\n return fieldSeparatorAtEnd;\n }\n\n /**\n *

      Sets whether the field separator should be added at the end\n * of each buffer.

      \n *\n * @param fieldSeparatorAtEnd the fieldSeparatorAtEnd flag\n * @since 2.0\n */\n protected void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) {\n this.fieldSeparatorAtEnd = fieldSeparatorAtEnd;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the text to output when null found.

      \n *\n * @return the current text to output when null found\n */\n protected String getNullText() {\n return nullText;\n }\n\n /**\n *

      Sets the text to output when null found.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param nullText the new text to output when null found\n */\n protected void setNullText(String nullText) {\n if (nullText == null) {\n nullText = \"\";\n }\n this.nullText = nullText;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the start text to output when a Collection,\n * Map or array size is output.

      \n *\n *

      This is output before the size value.

      \n *\n * @return the current start of size text\n */\n protected String getSizeStartText() {\n return sizeStartText;\n }\n\n /**\n *

      Sets the start text to output when a Collection,\n * Map or array size is output.

      \n *\n *

      This is output before the size value.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param sizeStartText the new start of size text\n */\n protected void setSizeStartText(String sizeStartText) {\n if (sizeStartText == null) {\n sizeStartText = \"\";\n }\n this.sizeStartText = sizeStartText;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the end text to output when a Collection,\n * Map or array size is output.

      \n *\n *

      This is output after the size value.

      \n *\n * @return the current end of size text\n */\n protected String getSizeEndText() {\n return sizeEndText;\n }\n\n /**\n *

      Sets the end text to output when a Collection,\n * Map or array size is output.

      \n *\n *

      This is output after the size value.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param sizeEndText the new end of size text\n */\n protected void setSizeEndText(String sizeEndText) {\n if (sizeEndText == null) {\n sizeEndText = \"\";\n }\n this.sizeEndText = sizeEndText;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the start text to output when an Object is\n * output in summary mode.

      \n *\n *

      This is output before the size value.

      \n *\n * @return the current start of summary text\n */\n protected String getSummaryObjectStartText() {\n return summaryObjectStartText;\n }\n\n /**\n *

      Sets the start text to output when an Object is\n * output in summary mode.

      \n *\n *

      This is output before the size value.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param summaryObjectStartText the new start of summary text\n */\n protected void setSummaryObjectStartText(String summaryObjectStartText) {\n if (summaryObjectStartText == null) {\n summaryObjectStartText = \"\";\n }\n this.summaryObjectStartText = summaryObjectStartText;\n }\n //---------------------------------------------------------------------\n\n /**\n *

      Gets the end text to output when an Object is\n * output in summary mode.

      \n *\n *

      This is output after the size value.

      \n *\n * @return the current end of summary text\n */\n protected String getSummaryObjectEndText() {\n return summaryObjectEndText;\n }\n\n /**\n *

      Sets the end text to output when an Object is\n * output in summary mode.

      \n *\n *

      This is output after the size value.

      \n *\n *

      null is accepted, but will be converted to\n * an empty String.

      \n *\n * @param summaryObjectEndText the new end of summary text\n */\n protected void setSummaryObjectEndText(String summaryObjectEndText) {\n if (summaryObjectEndText == null) {\n summaryObjectEndText = \"\";\n }\n this.summaryObjectEndText = summaryObjectEndText;\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      Default ToStringStyle.

      \n *\n *

      This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.

      \n */\n private static final class DefaultToStringStyle extends ToStringStyle {\n /**\n * Required for serialization support.\n *\n * @see java.io.Serializable\n */\n private static final long serialVersionUID = 1L;\n\n /**\n *

      Constructor.

      \n *\n *

      Use the static constant rather than instantiating.

      \n */\n DefaultToStringStyle() {\n super();\n }\n\n /**\n *

      Ensure Singleton after serialization.

      \n *\n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.DEFAULT_STYLE;\n }\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      ToStringStyle that does not print out\n * the field names.

      \n *\n *

      This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.\n */\n private static final class NoFieldNameToStringStyle extends ToStringStyle {\n private static final long serialVersionUID = 1L;\n\n /**\n *

      Constructor.

      \n *\n *

      Use the static constant rather than instantiating.

      \n */\n NoFieldNameToStringStyle() {\n super();\n this.setUseFieldNames(false);\n }\n\n /**\n *

      Ensure Singleton after serialization.

      \n *\n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.NO_FIELD_NAMES_STYLE;\n }\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      ToStringStyle that prints out the short\n * class name and no identity hashcode.

      \n *\n *

      This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.

      \n */\n private static final class ShortPrefixToStringStyle extends ToStringStyle {\n private static final long serialVersionUID = 1L;\n\n /**\n *

      Constructor.

      \n *\n *

      Use the static constant rather than instantiating.

      \n */\n ShortPrefixToStringStyle() {\n super();\n this.setUseShortClassName(true);\n this.setUseIdentityHashCode(false);\n }\n\n /**\n *

      Ensure Singleton after serialization.

      \n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.SHORT_PREFIX_STYLE;\n }\n }\n\n /**\n *

      ToStringStyle that does not print out the\n * classname, identity hashcode, content start or field name.

      \n *\n *

      This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.

      \n */\n private static final class SimpleToStringStyle extends ToStringStyle {\n private static final long serialVersionUID = 1L;\n\n /**\n *

      Constructor.

      \n *\n *

      Use the static constant rather than instantiating.

      \n */\n SimpleToStringStyle() {\n super();\n this.setUseClassName(false);\n this.setUseIdentityHashCode(false);\n this.setUseFieldNames(false);\n this.setContentStart(\"\");\n this.setContentEnd(\"\");\n }\n\n /**\n *

      Ensure Singleton after serialization.

      \n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.SIMPLE_STYLE;\n }\n }\n //----------------------------------------------------------------------------\n\n /**\n *

      ToStringStyle that outputs on multiple lines.

      \n *\n *

      This is an inner class rather than using\n * StandardToStringStyle to ensure its immutability.

      \n */\n private static final class MultiLineToStringStyle extends ToStringStyle {\n private static final long serialVersionUID = 1L;\n\n /**\n *

      Constructor.

      \n *\n *

      Use the static constant rather than instantiating.

      \n */\n MultiLineToStringStyle() {\n super();\n String separator = getSystemProperty(\"line.separator\");\n this.setContentStart(\"[\");\n this.setFieldSeparator(separator + \" \");\n this.setFieldSeparatorAtStart(true);\n this.setContentEnd(separator + \"]\");\n }\n\n private String getSystemProperty(final String property) {\n try {\n return System.getProperty(property);\n } catch (SecurityException ex) {\n // we are not allowed to look at this property\n System.err.println(\"Caught a SecurityException reading the system property '\" + property + \"'; the SystemUtils property value will default to null.\");\n return null;\n }\n }\n\n /**\n *

      Ensure Singleton after serialization.

      \n *\n * @return the singleton\n */\n private Object readResolve() {\n return ToStringStyle.MULTI_LINE_STYLE;\n }\n }\n}", "file_name": "ToStringStyle.java", "human_label": "Append a byte array to a buffer.", "level": "class_runnable", "lineno": "1074", "name": "appendDetail", "oracle_context": "{ \"apis\" : \"[append]\", \"classes\" : \"[]\", \"vars\" : \"[length, arrayStart, arraySeparator, arrayEnd]\" }", "package": "net.hasor.utils.builder", "project": "hasor-master" }, { "_id": "636767561a6d9265ec017f63", "all_context": "{ \"class_level\" : \"import java.util.Collection;\\nimport java.util.HashSet;\\nimport java.util.LinkedHashSet;\\nimport java.util.Map;\\nimport java.util.NoSuchElementException;\\nimport java.util.Set;\\nimport org.jgrapht.Graph;\\nimport org.jgrapht.GraphTests;\\nimport org.jgrapht.Graphs;\\nimport org.jgrapht.util.CollectionUtil;\\nBucketList bucketList;\\nV current;\\nBucket head;\\nMap bucketMap;\\nBucket next;\\nBucket prev;\\nSet vertices;\\nLexBreadthFirstIterator(Graph graph);\\nnext();\\nisCrossComponentTraversal();\\nsetCrossComponentTraversal(boolean crossComponentTraversal);\\nadvance();\\ngetUnvisitedNeighbours(V vertex);\\nBucketList(Collection vertices);\\ncontainsBucketWith(V vertex);\\npoll();\\nupdateBuckets(Set vertices);\\nBucket(Collection vertices);\\nBucket(V vertex);\\nremoveVertex(V vertex);\\nremoveSelf();\\ninsertBefore(Bucket bucket);\\naddVertex(V vertex);\\nisEmpty();\\n\", \"repo_level\" : \"public interface Graph { Set getAllEdges(V sourceVertex,V targetVertex);\\n E getEdge(V sourceVertex,V targetVertex);\\n Supplier getVertexSupplier();\\n Supplier getEdgeSupplier();\\n E addEdge(V sourceVertex,V targetVertex);\\n boolean addEdge(V sourceVertex,V targetVertex,E e);\\n V addVertex();\\n boolean addVertex(V v);\\n boolean containsEdge(V sourceVertex,V targetVertex);\\n boolean containsEdge(E e);\\n boolean containsVertex(V v);\\n Set edgeSet();\\n int degreeOf(V vertex);\\n Set edgesOf(V vertex);\\n int inDegreeOf(V vertex);\\n Set incomingEdgesOf(V vertex);\\n int outDegreeOf(V vertex);\\n Set outgoingEdgesOf(V vertex);\\n boolean removeAllEdges(Collection edges);\\n Set removeAllEdges(V sourceVertex,V targetVertex);\\n boolean removeAllVertices(Collection vertices);\\n E removeEdge(V sourceVertex,V targetVertex);\\n boolean removeEdge(E e);\\n boolean removeVertex(V v);\\n Set vertexSet();\\n V getEdgeSource(E e);\\n V getEdgeTarget(E e);\\n GraphType getType();\\n double getEdgeWeight(E e);\\n void setEdgeWeight(E e,double weight);\\ndefault void setEdgeWeight(V sourceVertex,V targetVertex,double weight);\\ndefault GraphIterables iterables();\\n }\\npublic interface Graphs {static E addEdge(Graph g,V sourceVertex,V targetVertex,double weight);\\nstatic E addEdgeWithVertices(Graph g,V sourceVertex,V targetVertex);\\nstatic boolean addEdgeWithVertices(Graph targetGraph,Graph sourceGraph,E edge);\\nstatic E addEdgeWithVertices(Graph g,V sourceVertex,V targetVertex,double weight);\\nstatic boolean addGraph(Graph destination,Graph source);\\nstatic void addGraphReversed(Graph destination,Graph source);\\nstatic boolean addAllEdges(Graph destination,Graph source,Collection edges);\\nstatic boolean addAllVertices(Graph destination,Collection vertices);\\nstatic List neighborListOf(Graph g,V vertex);\\nstatic Set neighborSetOf(Graph g,V vertex);\\nstatic List predecessorListOf(Graph g,V vertex);\\nstatic List successorListOf(Graph g,V vertex);\\nstatic Graph undirectedGraph(Graph g);\\nstatic boolean testIncidence(Graph g,E e,V v);\\nstatic V getOppositeVertex(Graph g,E e,V v);\\nstatic boolean removeVertexAndPreserveConnectivity(Graph graph,V vertex);\\nstatic boolean removeVerticesAndPreserveConnectivity(Graph graph,Predicate predicate);\\nstatic boolean removeVertexAndPreserveConnectivity(Graph graph,Iterable vertices);\\nstatic void addOutgoingEdges(Graph graph,V source,Iterable targets);\\nstatic void addIncomingEdges(Graph graph,V target,Iterable sources);\\nstatic boolean vertexHasSuccessors(Graph graph,V vertex);\\nstatic boolean vertexHasPredecessors(Graph graph,V vertex);\\nstatic VertexToIntegerMapping getVertexToIntegerMapping(Graph graph);\\n }\\npublic interface CollectionUtil {static HashMap newHashMapWithExpectedSize(int expectedSize);\\nstatic LinkedHashMap newLinkedHashMapWithExpectedSize(int expectedSize);\\nstatic HashSet newHashSetWithExpectedSize(int expectedSize);\\nstatic LinkedHashSet newLinkedHashSetWithExpectedSize(int expectedSize);\\nstatic E getElement(Iterable iterable,int index);\\n }\\n\" }", "class_name": "LexBreadthFirstIterator", "code": "@Override public boolean hasNext(){\n if (current != null) {\n return true;\n }\n current=advance();\n if (current != null && nListeners != 0) {\n fireVertexTraversed(createVertexTraversalEvent(current));\n }\n return current != null;\n}\n", "docstring": "/** \n * Checks whether there exist unvisited vertices.\n * @return true if there exist unvisited vertices.\n */\n", "end_lineno": "103", "file_content": "/*\n * (C) Copyright 2018-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.traverse;\n\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.LinkedHashSet;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.jgrapht.Graph;\nimport org.jgrapht.GraphTests;\nimport org.jgrapht.Graphs;\nimport org.jgrapht.util.CollectionUtil;\n\n/**\n * A lexicographical breadth-first iterator for an undirected graph.\n *

      \n * Every vertex has an implicit label (they aren't used explicitly in order to reduce time and\n * memory complexity). When some vertex is returned by this iterator, its index is the number of\n * vertices in this graph minus number of already returned vertices. For a given vertex v its label\n * is a concatenation of indices of already returned vertices, that were also its neighbours, with\n * some separator between them. For example, 7#4#3 is a valid vertex label.\n *

      \n * Iterator chooses vertex with lexicographically largest label and returns it. It breaks ties\n * arbitrarily. For more information on lexicographical BFS see the following article: Corneil D.G.\n * (2004) \n * Lexicographic Breadth First Search – A Survey. In: Hromkovič J., Nagl M., Westfechtel\n * B. (eds) Graph-Theoretic Concepts in Computer Science. WG 2004. Lecture Notes in Computer\n * Science, vol 3353. Springer, Berlin, Heidelberg; and the following\n * paper:CS 762:\n * Graph-theoretic algorithms. Lecture notes of a graduate course. University of Waterloo.\n *

      \n * For this iterator to work correctly the graph must not be modified during iteration. Currently\n * there are no means to ensure that, nor to fail-fast. The results of such modifications are\n * undefined.\n *

      \n * Note: only vertex events are fired by this iterator.\n *\n * @param the graph vertex type.\n * @param the graph edge type.\n * @author Timofey Chudakov\n */\npublic class LexBreadthFirstIterator\n extends\n AbstractGraphIterator\n{\n\n /**\n * Reference to the {@code BucketList} that contains unvisited vertices.\n */\n private BucketList bucketList;\n\n /**\n * Contains current vertex of the {@code graph}.\n */\n private V current;\n\n /**\n * Creates new lexicographical breadth-first iterator for {@code graph}.\n *\n * @param graph the graph to be iterated.\n */\n public LexBreadthFirstIterator(Graph graph)\n {\n super(graph);\n GraphTests.requireUndirected(graph);\n bucketList = new BucketList(graph.vertexSet());\n }\n\n /**\n * Checks whether there exist unvisited vertices.\n *\n * @return true if there exist unvisited vertices.\n */\n @Override\n public boolean hasNext()\n {\n if (current != null) {\n return true;\n }\n current = advance();\n if (current != null && nListeners != 0) {\n fireVertexTraversed(createVertexTraversalEvent(current));\n }\n return current != null;\n }\n\n /**\n * Returns the next vertex in the ordering.\n *\n * @return the next vertex in the ordering.\n */\n @Override\n public V next()\n {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n V result = current;\n current = null;\n if (nListeners != 0) {\n fireVertexFinished(createVertexTraversalEvent(result));\n }\n return result;\n }\n\n /**\n * {@inheritDoc}\n *

      \n * Always returns true since this iterator doesn't care about connected components.\n */\n @Override\n public boolean isCrossComponentTraversal()\n {\n return true;\n }\n\n /**\n * {@inheritDoc}\n *

      \n * Trying to disable the cross components nature of this iterator will result into throwing a\n * {@link IllegalArgumentException}.\n */\n @Override\n public void setCrossComponentTraversal(boolean crossComponentTraversal)\n {\n if (!crossComponentTraversal) {\n throw new IllegalArgumentException(\"Iterator is always cross-component\");\n }\n }\n\n /**\n * Retrieves vertex from the {@code bucketList} and returns it.\n *\n * @return the vertex retrieved from the {@code bucketList}.\n */\n private V advance()\n {\n V vertex = bucketList.poll();\n if (vertex != null) {\n bucketList.updateBuckets(getUnvisitedNeighbours(vertex));\n }\n return vertex;\n }\n\n /**\n * Computes and returns neighbours of {@code vertex} which haven't been visited by this\n * iterator.\n *\n * @param vertex the vertex, whose neighbours are being explored.\n * @return neighbours of {@code vertex} which have yet to be visited by this iterator.\n */\n private Set getUnvisitedNeighbours(V vertex)\n {\n Set unmapped = new LinkedHashSet<>();\n Set edges = graph.edgesOf(vertex);\n for (E edge : edges) {\n V oppositeVertex = Graphs.getOppositeVertex(graph, edge, vertex);\n if (bucketList.containsBucketWith(oppositeVertex)) {\n unmapped.add(oppositeVertex);\n }\n }\n return unmapped;\n }\n\n /**\n * Data structure for performing lexicographical breadth-first search. Allows to add and\n * retrieve vertices from buckets, update their buckets after a new vertex has been added to the\n * LexBFS order. Labels aren't used explicitly, which results in time and space optimization.\n *\n * @author Timofey Chudakov\n */\n class BucketList\n {\n /**\n * Bucket with the vertices that have lexicographically largest label.\n */\n private Bucket head;\n /**\n * Map for mapping vertices to buckets they are currently in. Is used for finding the bucket\n * of the vertex in constant time.\n */\n private Map bucketMap;\n\n /**\n * Creates a {@code BucketList} with a single bucket and all specified {@code vertices} in\n * it.\n *\n * @param vertices the vertices of the graph, that should be stored in the {@code head}\n * bucket.\n */\n BucketList(Collection vertices)\n {\n head = new Bucket(vertices);\n bucketMap = CollectionUtil.newHashMapWithExpectedSize(vertices.size());\n for (V vertex : vertices) {\n bucketMap.put(vertex, head);\n }\n }\n\n /**\n * Checks whether there exists a bucket with the specified {@code vertex}.\n *\n * @param vertex the vertex whose presence in some {@code Bucket} in this {@code BucketList}\n * is checked.\n * @return true if there exists a bucket with {@code vertex} in it, otherwise\n * false.\n */\n boolean containsBucketWith(V vertex)\n {\n return bucketMap.containsKey(vertex);\n }\n\n /**\n * Retrieves element from the head bucket by invoking {@link Bucket#poll()} or null if this\n * {@code BucketList} is empty.\n *

      \n * Removes the head bucket if it becomes empty after the operation.\n *\n * @return vertex returned by {@link Bucket#poll()} invoked on head bucket or null if this\n * {@code BucketList} is empty.\n */\n V poll()\n {\n if (bucketMap.size() > 0) {\n V res = head.poll();\n bucketMap.remove(res);\n if (head.isEmpty()) {\n head = head.next;\n if (head != null) {\n head.prev = null;\n }\n }\n return res;\n } else {\n return null;\n }\n }\n\n /**\n * For every bucket B in this {@code BucketList}, which contains vertices from the set\n * {@code\n * vertices}, creates a new {@code Bucket} B' and moves vertices from B to B' according to\n * the following rule: $B' = B\\cap vertices$ and $B = B\\backslash B'$. For every such\n * {@code Bucket} B only one {@code Bucket} B' is created. If some bucket B becomes empty\n * after this operation, it is removed from the data structure.\n *\n * @param vertices the vertices, that should be moved to new buckets.\n */\n void updateBuckets(Set vertices)\n {\n Set visitedBuckets = new HashSet<>();\n for (V vertex : vertices) {\n Bucket bucket = bucketMap.get(vertex);\n if (visitedBuckets.contains(bucket)) {\n bucket.prev.addVertex(vertex);\n bucketMap.put(vertex, bucket.prev);\n } else {\n visitedBuckets.add(bucket);\n Bucket newBucket = new Bucket(vertex);\n newBucket.insertBefore(bucket);\n bucketMap.put(vertex, newBucket);\n if (head == bucket) {\n head = newBucket;\n }\n }\n bucket.removeVertex(vertex);\n if (bucket.isEmpty()) {\n visitedBuckets.remove(bucket);\n bucket.removeSelf();\n }\n }\n }\n\n /**\n * Plays the role of the container of vertices. All vertices stored in a bucket have\n * identical label. Labels aren't used explicitly.\n *

      \n * Encapsulates operations of addition and removal of vertices from the bucket and removal\n * of a bucket from the data structure.\n */\n private class Bucket\n {\n /**\n * Reference of the bucket with lexicographically smaller label.\n */\n private Bucket next;\n /**\n * Reference of the bucket with lexicographically larger label.\n */\n private Bucket prev;\n /**\n * Set of vertices currently stored in this bucket.\n */\n private Set vertices;\n\n /**\n * Creates a new bucket with all {@code vertices} stored in it.\n *\n * @param vertices vertices to store in this bucket.\n */\n Bucket(Collection vertices)\n {\n this.vertices = new LinkedHashSet<>(vertices);\n }\n\n /**\n * Creates a new Bucket with a single {@code vertex} in it.\n *\n * @param vertex the vertex to store in this bucket.\n */\n Bucket(V vertex)\n {\n this.vertices = new LinkedHashSet<>();\n vertices.add(vertex);\n }\n\n /**\n * Removes the {@code vertex} from this bucket.\n *\n * @param vertex the vertex to remove.\n */\n void removeVertex(V vertex)\n {\n vertices.remove(vertex);\n }\n\n /**\n * Removes this bucket from the data structure.\n */\n void removeSelf()\n {\n if (next != null) {\n next.prev = prev;\n }\n if (prev != null) {\n prev.next = next;\n }\n }\n\n /**\n * Inserts this bucket in the data structure before the {@code bucket}.\n *\n * @param bucket the bucket, that will be the next to this bucket.\n */\n void insertBefore(Bucket bucket)\n {\n this.next = bucket;\n if (bucket != null) {\n this.prev = bucket.prev;\n if (bucket.prev != null) {\n bucket.prev.next = this;\n }\n bucket.prev = this;\n } else {\n this.prev = null;\n }\n }\n\n /**\n * Adds the {@code vertex} to this bucket.\n *\n * @param vertex the vertex to add.\n */\n void addVertex(V vertex)\n {\n vertices.add(vertex);\n }\n\n /**\n * Retrieves one vertex from this bucket.\n *\n * @return vertex, that was removed from this bucket, null if the bucket was empty.\n */\n V poll()\n {\n if (vertices.isEmpty()) {\n return null;\n } else {\n V vertex = vertices.iterator().next();\n vertices.remove(vertex);\n return vertex;\n }\n }\n\n /**\n * Checks whether this bucket is empty.\n *\n * @return true if this bucket doesn't contain any elements, otherwise false.\n */\n boolean isEmpty()\n {\n return vertices.size() == 0;\n }\n }\n }\n}\n", "file_name": "LexBreadthFirstIterator.java", "human_label": "Check whether there are unvisited vertices. If so, return true. Otherwise, return false.", "level": "class_runnable", "lineno": "87", "name": "hasNext", "oracle_context": "{ \"apis\" : \"[advance, fireVertexTraversed, createVertexTraversalEvent]\", \"classes\" : \"[]\", \"vars\" : \"[current]\" }", "package": "org.jgrapht.traverse", "project": "jgrapht-master" }, { "_id": "636766a81a6d9265ec017586", "all_context": "{ \"class_level\" : \"int SAME_FRAME;\\nint SAME_LOCALS_1_STACK_ITEM_FRAME;\\nint SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED;\\nint CHOP_FRAME;\\nint SAME_FRAME_EXTENDED;\\nint APPEND_FRAME;\\nint FULL_FRAME;\\nint ITEM_TOP;\\nint ITEM_INTEGER;\\nint ITEM_FLOAT;\\nint ITEM_DOUBLE;\\nint ITEM_LONG;\\nint ITEM_NULL;\\nint ITEM_UNINITIALIZED_THIS;\\nint ITEM_OBJECT;\\nint ITEM_UNINITIALIZED;\\nint ITEM_ASM_BOOLEAN;\\nint ITEM_ASM_BYTE;\\nint ITEM_ASM_CHAR;\\nint ITEM_ASM_SHORT;\\nint DIM_SIZE;\\nint KIND_SIZE;\\nint FLAGS_SIZE;\\nint VALUE_SIZE;\\nint DIM_SHIFT;\\nint KIND_SHIFT;\\nint FLAGS_SHIFT;\\nint DIM_MASK;\\nint KIND_MASK;\\nint VALUE_MASK;\\nint ARRAY_OF;\\nint ELEMENT_OF;\\nint CONSTANT_KIND;\\nint REFERENCE_KIND;\\nint UNINITIALIZED_KIND;\\nint LOCAL_KIND;\\nint STACK_KIND;\\nint TOP_IF_LONG_OR_DOUBLE_FLAG;\\nint TOP;\\nint BOOLEAN;\\nint BYTE;\\nint CHAR;\\nint SHORT;\\nint INTEGER;\\nint FLOAT;\\nint LONG;\\nint DOUBLE;\\nint NULL;\\nint UNINITIALIZED_THIS;\\nLabel owner;\\nint[] inputLocals;\\nint[] inputStack;\\nint[] outputLocals;\\nint[] outputStack;\\nshort outputStackStart;\\nshort outputStackTop;\\nint initializationCount;\\nint[] initializations;\\nFrame(Label owner);\\ngetAbstractTypeFromDescriptor(SymbolTable symbolTable,String buffer,int offset);\\nsetInputFrameFromDescriptor(SymbolTable symbolTable,int access,String descriptor,int maxLocals);\\ngetLocal(int localIndex);\\nsetLocal(int localIndex,int abstractType);\\npush(SymbolTable symbolTable,String descriptor);\\npop();\\npop(int elements);\\npop(String descriptor);\\naddInitializedType(int abstractType);\\ngetInitializedType(SymbolTable symbolTable,int abstractType);\\nexecute(int opcode,int arg,Symbol argSymbol,SymbolTable symbolTable);\\ngetConcreteOutputType(int abstractOutputType,int numStack);\\nmerge(SymbolTable symbolTable,Frame dstFrame);\\nmerge(SymbolTable symbolTable,int sourceType,int[] dstTypes,int dstIndex);\\naccept(MethodWriter methodWriter);\\npush(int abstractType);\\n\", \"repo_level\" : \"\" }", "class_name": "Frame", "code": "private void pop(final int elements){\n if (outputStackTop >= elements) {\n outputStackTop-=elements;\n }\n else {\n outputStackStart-=elements - outputStackTop;\n outputStackTop=0;\n }\n}\n", "docstring": "/** \n * Pops the given number of abstract types from the output frame stack.\n * @param elements the number of abstract types that must be popped.\n */\n", "end_lineno": "645", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage com.alibaba.fastjson2.internal.asm;\n\n/**\n * @author Eric Bruneton\n */\nclass Frame {\n // Constants used in the StackMapTable attribute.\n // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.4.\n\n static final int SAME_FRAME = 0;\n static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64;\n// static final int RESERVED = 128;\n static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247;\n static final int CHOP_FRAME = 248;\n static final int SAME_FRAME_EXTENDED = 251;\n static final int APPEND_FRAME = 252;\n static final int FULL_FRAME = 255;\n\n static final int ITEM_TOP = 0;\n static final int ITEM_INTEGER = 1;\n static final int ITEM_FLOAT = 2;\n static final int ITEM_DOUBLE = 3;\n static final int ITEM_LONG = 4;\n static final int ITEM_NULL = 5;\n static final int ITEM_UNINITIALIZED_THIS = 6;\n static final int ITEM_OBJECT = 7;\n static final int ITEM_UNINITIALIZED = 8;\n // Additional, ASM specific constants used in abstract types below.\n static final int ITEM_ASM_BOOLEAN = 9;\n static final int ITEM_ASM_BYTE = 10;\n static final int ITEM_ASM_CHAR = 11;\n static final int ITEM_ASM_SHORT = 12;\n\n // The size and offset in bits of each field of an abstract type.\n\n static final int DIM_SIZE = 6;\n static final int KIND_SIZE = 4;\n static final int FLAGS_SIZE = 2;\n static final int VALUE_SIZE = 32 - DIM_SIZE - KIND_SIZE - FLAGS_SIZE;\n\n static final int DIM_SHIFT = KIND_SIZE + FLAGS_SIZE + VALUE_SIZE;\n static final int KIND_SHIFT = FLAGS_SIZE + VALUE_SIZE;\n static final int FLAGS_SHIFT = VALUE_SIZE;\n\n // Bitmasks to get each field of an abstract type.\n\n static final int DIM_MASK = ((1 << DIM_SIZE) - 1) << DIM_SHIFT;\n static final int KIND_MASK = ((1 << KIND_SIZE) - 1) << KIND_SHIFT;\n static final int VALUE_MASK = (1 << VALUE_SIZE) - 1;\n\n // Constants to manipulate the DIM field of an abstract type.\n\n /**\n * The constant to be added to an abstract type to get one with one more array dimension.\n */\n static final int ARRAY_OF = +1 << DIM_SHIFT;\n\n /**\n * The constant to be added to an abstract type to get one with one less array dimension.\n */\n static final int ELEMENT_OF = -1 << DIM_SHIFT;\n\n // Possible values for the KIND field of an abstract type.\n\n static final int CONSTANT_KIND = 1 << KIND_SHIFT;\n static final int REFERENCE_KIND = 2 << KIND_SHIFT;\n static final int UNINITIALIZED_KIND = 3 << KIND_SHIFT;\n static final int LOCAL_KIND = 4 << KIND_SHIFT;\n static final int STACK_KIND = 5 << KIND_SHIFT;\n\n // Possible flags for the FLAGS field of an abstract type.\n\n /**\n * A flag used for LOCAL_KIND and STACK_KIND abstract types, indicating that if the resolved,\n * concrete type is LONG or DOUBLE, TOP should be used instead (because the value has been\n * partially overridden with an xSTORE instruction).\n */\n private static final int TOP_IF_LONG_OR_DOUBLE_FLAG = 1 << FLAGS_SHIFT;\n\n // Useful predefined abstract types (all the possible CONSTANT_KIND types).\n\n private static final int TOP = CONSTANT_KIND | ITEM_TOP;\n private static final int BOOLEAN = CONSTANT_KIND | ITEM_ASM_BOOLEAN;\n private static final int BYTE = CONSTANT_KIND | ITEM_ASM_BYTE;\n private static final int CHAR = CONSTANT_KIND | ITEM_ASM_CHAR;\n private static final int SHORT = CONSTANT_KIND | ITEM_ASM_SHORT;\n private static final int INTEGER = CONSTANT_KIND | ITEM_INTEGER;\n private static final int FLOAT = CONSTANT_KIND | ITEM_FLOAT;\n private static final int LONG = CONSTANT_KIND | ITEM_LONG;\n private static final int DOUBLE = CONSTANT_KIND | ITEM_DOUBLE;\n private static final int NULL = CONSTANT_KIND | ITEM_NULL;\n private static final int UNINITIALIZED_THIS = CONSTANT_KIND | ITEM_UNINITIALIZED_THIS;\n\n // -----------------------------------------------------------------------------------------------\n // Instance fields\n // -----------------------------------------------------------------------------------------------\n\n /**\n * The basic block to which these input and output stack map frames correspond.\n */\n Label owner;\n\n /**\n * The input stack map frame locals. This is an array of abstract types.\n */\n private int[] inputLocals;\n\n /**\n * The input stack map frame stack. This is an array of abstract types.\n */\n int[] inputStack;\n\n /**\n * The output stack map frame locals. This is an array of abstract types.\n */\n private int[] outputLocals;\n\n /**\n * The output stack map frame stack. This is an array of abstract types.\n */\n private int[] outputStack;\n\n /**\n * The start of the output stack, relatively to the input stack. This offset is always negative or\n * null. A null offset means that the output stack must be appended to the input stack. A -n\n * offset means that the first n output stack elements must replace the top n input stack\n * elements, and that the other elements must be appended to the input stack.\n */\n private short outputStackStart;\n\n /**\n * The index of the top stack element in {@link #outputStack}.\n */\n private short outputStackTop;\n\n /**\n * The number of types that are initialized in the basic block. See {@link #initializations}.\n */\n private int initializationCount;\n\n /**\n * The abstract types that are initialized in the basic block. A constructor invocation on an\n * UNINITIALIZED or UNINITIALIZED_THIS abstract type must replace every occurrence of this\n * type in the local variables and in the operand stack. This cannot be done during the first step\n * of the algorithm since, during this step, the local variables and the operand stack types are\n * still abstract. It is therefore necessary to store the abstract types of the constructors which\n * are invoked in the basic block, in order to do this replacement during the second step of the\n * algorithm, where the frames are fully computed. Note that this array can contain abstract types\n * that are relative to the input locals or to the input stack.\n */\n private int[] initializations;\n\n // -----------------------------------------------------------------------------------------------\n // Constructor\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Constructs a new Frame.\n *\n * @param owner the basic block to which these input and output stack map frames correspond.\n */\n Frame(final Label owner) {\n this.owner = owner;\n }\n//\n// /**\n// * Returns the abstract type corresponding to the internal name of a class.\n// *\n// * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n// * @param internalName the internal name of a class. This must not be an array type\n// * descriptor.\n// * @return the abstract type value corresponding to the given internal name.\n// */\n// static int getAbstractTypeFromInternalName(\n// final SymbolTable symbolTable, final String internalName) {\n// return REFERENCE_KIND | symbolTable.addType(internalName);\n// }\n\n /**\n * Returns the abstract type corresponding to the given type descriptor.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param buffer a string ending with a type descriptor.\n * @param offset the start offset of the type descriptor in buffer.\n * @return the abstract type corresponding to the given type descriptor.\n */\n private static int getAbstractTypeFromDescriptor(\n final SymbolTable symbolTable, final String buffer, final int offset) {\n String internalName = null;\n switch (buffer.charAt(offset)) {\n case 'V':\n return 0;\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n return INTEGER;\n case 'F':\n return FLOAT;\n case 'J':\n return LONG;\n case 'D':\n return DOUBLE;\n case 'L':\n if (offset == 0) {\n switch (buffer) {\n case \"Ljava/lang/Object;\":\n internalName = \"java/lang/Object\";\n break;\n case \"Ljava/lang/Class;\":\n internalName = \"java/lang/Class\";\n break;\n case \"Ljava/lang/String;\":\n internalName = \"java/lang/String\";\n break;\n case \"Ljava/util/List;\":\n internalName = \"java/util/List\";\n break;\n case \"Ljava/lang/reflect/Type;\":\n internalName = \"java/lang/reflect/Type\";\n break;\n case \"Ljava/util/function/Supplier;\":\n internalName = \"java/util/function/Supplier\";\n break;\n case \"Lsun/misc/Unsafe;\":\n internalName = \"sun/misc/Unsafe\";\n break;\n case \"Lcom/alibaba/fastjson2/JSONReader;\":\n internalName = \"com/alibaba/fastjson2/JSONReader\";\n break;\n case \"Lcom/alibaba/fastjson2/reader/FieldReader;\":\n internalName = \"com/alibaba/fastjson2/reader/FieldReader\";\n break;\n case \"Lcom/alibaba/fastjson2/reader/ObjectReader;\":\n internalName = \"com/alibaba/fastjson2/reader/ObjectReader\";\n break;\n case \"Lcom/alibaba/fastjson2/JSONWriter;\":\n internalName = \"com/alibaba/fastjson2/JSONWriter\";\n break;\n case \"Lcom/alibaba/fastjson2/writer/FieldWriter;\":\n internalName = \"com/alibaba/fastjson2/writer/FieldWriter\";\n break;\n default:\n break;\n }\n } else if (offset == 2) {\n switch (buffer) {\n case \"()Ljava/lang/Class;\":\n internalName = \"java/lang/Class\";\n break;\n case \"()Ljava/lang/String;\":\n internalName = \"java/lang/String\";\n break;\n default:\n break;\n }\n } else if (offset == 3) {\n switch (buffer) {\n case \"(J)Lcom/alibaba/fastjson2/reader/FieldReader;\":\n internalName = \"com/alibaba/fastjson2/reader/FieldReader\";\n break;\n case \"(I)Ljava/lang/Object;\":\n internalName = \"java/lang/Object\";\n break;\n case \"(I)Ljava/lang/Integer;\":\n internalName = \"java/lang/Integer\";\n break;\n default:\n break;\n }\n } else if (offset == 36) {\n switch (buffer) {\n case \"(Lcom/alibaba/fastjson2/JSONReader;)Lcom/alibaba/fastjson2/reader/ObjectReader;\":\n internalName = \"com/alibaba/fastjson2/reader/ObjectReader\";\n break;\n case \"(Lcom/alibaba/fastjson2/JSONReader;)Ljava/lang/Object;\":\n internalName = \"java/lang/Object\";\n break;\n default:\n break;\n }\n } else if (offset == 54) {\n switch (buffer) {\n case \"(Lcom/alibaba/fastjson2/JSONReader;Ljava/lang/Class;J)Lcom/alibaba/fastjson2/reader/ObjectReader;\":\n internalName = \"com/alibaba/fastjson2/reader/ObjectReader\";\n break;\n case \"(Lcom/alibaba/fastjson2/JSONReader;Ljava/lang/Class;J)Ljava/lang/Object;\":\n internalName = \"java/lang/Object\";\n break;\n default:\n break;\n }\n } else {\n switch (buffer) {\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/Class;)Lcom/alibaba/fastjson2/writer/ObjectWriter;\":\n if (offset == 53) {\n internalName = \"com/alibaba/fastjson2/writer/ObjectWriter\";\n }\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/reflect/Type;)Lcom/alibaba/fastjson2/writer/ObjectWriter;\":\n if (offset == 60) {\n internalName = \"com/alibaba/fastjson2/writer/ObjectWriter\";\n }\n break;\n case \"(Lcom/alibaba/fastjson2/writer/FieldWriter;Ljava/lang/Object;)Ljava/lang/String;\":\n if (offset == 62) {\n internalName = \"java/lang/String\";\n }\n break;\n case \"(Lcom/alibaba/fastjson2/JSONReader;Ljava/lang/reflect/Type;Ljava/lang/Object;J)Ljava/lang/Object;\":\n if (offset == 79) {\n internalName = \"java/lang/Object\";\n }\n break;\n default:\n break;\n }\n }\n\n if (internalName == null) {\n internalName = buffer.substring(offset + 1, buffer.length() - 1);\n }\n return REFERENCE_KIND | symbolTable.addType(internalName);\n case '[':\n int elementDescriptorOffset = offset + 1;\n while (buffer.charAt(elementDescriptorOffset) == '[') {\n ++elementDescriptorOffset;\n }\n int typeValue;\n switch (buffer.charAt(elementDescriptorOffset)) {\n case 'Z':\n typeValue = BOOLEAN;\n break;\n case 'C':\n typeValue = CHAR;\n break;\n case 'B':\n typeValue = BYTE;\n break;\n case 'S':\n typeValue = SHORT;\n break;\n case 'I':\n typeValue = INTEGER;\n break;\n case 'F':\n typeValue = FLOAT;\n break;\n case 'J':\n typeValue = LONG;\n break;\n case 'D':\n typeValue = DOUBLE;\n break;\n case 'L':\n if (offset == 0) {\n switch (buffer) {\n case \"[Lcom/alibaba/fastjson2/writer/FieldWriter;\":\n internalName = \"com/alibaba/fastjson2/reader/FieldReader\";\n break;\n case \"[Lcom/alibaba/fastjson2/reader/FieldReader;\":\n internalName = \"Lcom/alibaba/fastjson2/reader/FieldReader\";\n break;\n default:\n break;\n }\n }\n if (internalName == null) {\n internalName = buffer.substring(elementDescriptorOffset + 1, buffer.length() - 1);\n }\n typeValue = REFERENCE_KIND | symbolTable.addType(internalName);\n break;\n default:\n throw new IllegalArgumentException();\n }\n return ((elementDescriptorOffset - offset) << DIM_SHIFT) | typeValue;\n default:\n throw new IllegalArgumentException();\n }\n }\n\n // -----------------------------------------------------------------------------------------------\n // Methods related to the input frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Sets the input frame from the given method description. This method is used to initialize the\n * first frame of a method, which is implicit (i.e. not stored explicitly in the StackMapTable\n * attribute).\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param access the method's access flags.\n * @param descriptor the method descriptor.\n * @param maxLocals the maximum number of local variables of the method.\n */\n final void setInputFrameFromDescriptor(\n final SymbolTable symbolTable,\n final int access,\n final String descriptor,\n final int maxLocals) {\n inputLocals = new int[maxLocals];\n inputStack = new int[0];\n int inputLocalIndex = 0;\n if ((access & Opcodes.ACC_STATIC) == 0) {\n if ((access & Constants.ACC_CONSTRUCTOR) == 0) {\n inputLocals[inputLocalIndex++] =\n REFERENCE_KIND | symbolTable.addType(symbolTable.className);\n } else {\n inputLocals[inputLocalIndex++] = UNINITIALIZED_THIS;\n }\n }\n for (Type argumentType : Type.getArgumentTypes(descriptor)) {\n int abstractType =\n getAbstractTypeFromDescriptor(symbolTable, argumentType.getDescriptor(), 0);\n inputLocals[inputLocalIndex++] = abstractType;\n if (abstractType == LONG || abstractType == DOUBLE) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n }\n while (inputLocalIndex < maxLocals) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n }\n\n // -----------------------------------------------------------------------------------------------\n // Methods related to the output frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the abstract type stored at the given local variable index in the output frame.\n *\n * @param localIndex the index of the local variable whose value must be returned.\n * @return the abstract type stored at the given local variable index in the output frame.\n */\n private int getLocal(final int localIndex) {\n if (outputLocals == null || localIndex >= outputLocals.length) {\n // If this local has never been assigned in this basic block, it is still equal to its value\n // in the input frame.\n return LOCAL_KIND | localIndex;\n } else {\n int abstractType = outputLocals[localIndex];\n if (abstractType == 0) {\n // If this local has never been assigned in this basic block, so it is still equal to its\n // value in the input frame.\n abstractType = outputLocals[localIndex] = LOCAL_KIND | localIndex;\n }\n return abstractType;\n }\n }\n\n /**\n * Replaces the abstract type stored at the given local variable index in the output frame.\n *\n * @param localIndex the index of the output frame local variable that must be set.\n * @param abstractType the value that must be set.\n */\n private void setLocal(final int localIndex, final int abstractType) {\n // Create and/or resize the output local variables array if necessary.\n if (outputLocals == null) {\n outputLocals = new int[10];\n }\n int outputLocalsLength = outputLocals.length;\n if (localIndex >= outputLocalsLength) {\n int[] newOutputLocals = new int[Math.max(localIndex + 1, 2 * outputLocalsLength)];\n System.arraycopy(outputLocals, 0, newOutputLocals, 0, outputLocalsLength);\n outputLocals = newOutputLocals;\n }\n // Set the local variable.\n outputLocals[localIndex] = abstractType;\n }\n\n /**\n * Pushes the given abstract type on the output frame stack.\n *\n * @param abstractType an abstract type.\n */\n private void push(final int abstractType) {\n // Create and/or resize the output stack array if necessary.\n if (outputStack == null) {\n outputStack = new int[10];\n }\n int outputStackLength = outputStack.length;\n if (outputStackTop >= outputStackLength) {\n int[] newOutputStack = new int[Math.max(outputStackTop + 1, 2 * outputStackLength)];\n System.arraycopy(outputStack, 0, newOutputStack, 0, outputStackLength);\n outputStack = newOutputStack;\n }\n // Pushes the abstract type on the output stack.\n outputStack[outputStackTop++] = abstractType;\n // Updates the maximum size reached by the output stack, if needed (note that this size is\n // relative to the input stack size, which is not known yet).\n short outputStackSize = (short) (outputStackStart + outputStackTop);\n if (outputStackSize > owner.outputStackMax) {\n owner.outputStackMax = outputStackSize;\n }\n }\n\n /**\n * Pushes the abstract type corresponding to the given descriptor on the output frame stack.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param descriptor a type or method descriptor (in which case its return type is pushed).\n */\n private void push(final SymbolTable symbolTable, final String descriptor) {\n final int typeDescriptorOffset;\n switch (descriptor) {\n case \"()J\":\n case \"()V\":\n case \"()Z\":\n case \"()I\":\n case \"()Ljava/lang/Class;\":\n typeDescriptorOffset = 2;\n break;\n case \"(I)V\":\n case \"(J)V\":\n case \"(J)Z\":\n case \"(I)Ljava/lang/Object;\":\n case \"(I)Ljava/lang/Integer;\":\n typeDescriptorOffset = 3;\n break;\n case \"(Ljava/lang/Enum;)V\":\n typeDescriptorOffset = 18;\n break;\n case \"(Ljava/lang/Object;)Z\":\n case \"(Ljava/lang/String;)V\":\n case \"(Ljava/lang/Object;)V\":\n typeDescriptorOffset = 20;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;)V\":\n case \"(Lcom/alibaba/fastjson2/JSONWriter;)Z\":\n typeDescriptorOffset = 36;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;I)V\":\n case \"(Lcom/alibaba/fastjson2/JSONWriter;J)V\":\n typeDescriptorOffset = 37;\n break;\n case \"(Ljava/lang/Object;Ljava/lang/reflect/Type;)Z\":\n typeDescriptorOffset = 44;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/Enum;)V\":\n typeDescriptorOffset = 52;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/Class;)Lcom/alibaba/fastjson2/writer/ObjectWriter;\":\n case \"(Lcom/alibaba/fastjson2/JSONWriter;ZLjava/util/List;)V\":\n typeDescriptorOffset = 53;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/reflect/Type;)Lcom/alibaba/fastjson2/writer/ObjectWriter;\":\n typeDescriptorOffset = 60;\n break;\n case \"(Lcom/alibaba/fastjson2/writer/FieldWriter;Ljava/lang/Object;)Ljava/lang/String;\":\n typeDescriptorOffset = 62;\n break;\n case \"(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;JLjava/util/List;)V\":\n typeDescriptorOffset = 72;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;J)V\":\n typeDescriptorOffset = 97;\n break;\n default:\n if (descriptor.charAt(0) == '(') {\n int currentOffset = 1;\n // Skip the argument types, one at a each loop iteration.\n while (descriptor.charAt(currentOffset) != ')') {\n while (descriptor.charAt(currentOffset) == '[') {\n currentOffset++;\n }\n if (descriptor.charAt(currentOffset++) == 'L') {\n // Skip the argument descriptor content.\n int semiColumnOffset = descriptor.indexOf(';', currentOffset);\n currentOffset = Math.max(currentOffset, semiColumnOffset + 1);\n }\n }\n typeDescriptorOffset = currentOffset + 1;\n } else {\n typeDescriptorOffset = 0;\n }\n break;\n }\n\n int abstractType = getAbstractTypeFromDescriptor(symbolTable, descriptor, typeDescriptorOffset);\n if (abstractType != 0) {\n push(abstractType);\n if (abstractType == LONG || abstractType == DOUBLE) {\n push(TOP);\n }\n }\n }\n\n /**\n * Pops an abstract type from the output frame stack and returns its value.\n *\n * @return the abstract type that has been popped from the output frame stack.\n */\n private int pop() {\n if (outputStackTop > 0) {\n return outputStack[--outputStackTop];\n } else {\n // If the output frame stack is empty, pop from the input stack.\n return STACK_KIND | -(--outputStackStart);\n }\n }\n\n /**\n * Pops the given number of abstract types from the output frame stack.\n *\n * @param elements the number of abstract types that must be popped.\n */\n private void pop(final int elements) {\n if (outputStackTop >= elements) {\n outputStackTop -= elements;\n } else {\n // If the number of elements to be popped is greater than the number of elements in the output\n // stack, clear it, and pop the remaining elements from the input stack.\n outputStackStart -= elements - outputStackTop;\n outputStackTop = 0;\n }\n }\n\n /**\n * Pops as many abstract types from the output frame stack as described by the given descriptor.\n *\n * @param descriptor a type or method descriptor (in which case its argument types are popped).\n */\n private void pop(final String descriptor) {\n char firstDescriptorChar = descriptor.charAt(0);\n if (firstDescriptorChar == '(') {\n pop((Type.getArgumentsAndReturnSizes(descriptor) >> 2) - 1);\n } else if (firstDescriptorChar == 'J' || firstDescriptorChar == 'D') {\n pop(2);\n } else {\n pop(1);\n }\n }\n\n // -----------------------------------------------------------------------------------------------\n // Methods to handle uninitialized types\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Adds an abstract type to the list of types on which a constructor is invoked in the basic\n * block.\n *\n * @param abstractType an abstract type on a which a constructor is invoked.\n */\n private void addInitializedType(final int abstractType) {\n // Create and/or resize the initializations array if necessary.\n if (initializations == null) {\n initializations = new int[2];\n }\n int initializationsLength = initializations.length;\n if (initializationCount >= initializationsLength) {\n int[] newInitializations =\n new int[Math.max(initializationCount + 1, 2 * initializationsLength)];\n System.arraycopy(initializations, 0, newInitializations, 0, initializationsLength);\n initializations = newInitializations;\n }\n // Store the abstract type.\n initializations[initializationCount++] = abstractType;\n }\n\n /**\n * Returns the \"initialized\" abstract type corresponding to the given abstract type.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param abstractType an abstract type.\n * @return the REFERENCE_KIND abstract type corresponding to abstractType if it is\n * UNINITIALIZED_THIS or an UNINITIALIZED_KIND abstract type for one of the types on which a\n * constructor is invoked in the basic block. Otherwise returns abstractType.\n */\n private int getInitializedType(final SymbolTable symbolTable, final int abstractType) {\n if (abstractType == UNINITIALIZED_THIS\n || (abstractType & (DIM_MASK | KIND_MASK)) == UNINITIALIZED_KIND) {\n for (int i = 0; i < initializationCount; ++i) {\n int initializedType = initializations[i];\n int dim = initializedType & DIM_MASK;\n int kind = initializedType & KIND_MASK;\n int value = initializedType & VALUE_MASK;\n if (kind == LOCAL_KIND) {\n initializedType = dim + inputLocals[value];\n } else if (kind == STACK_KIND) {\n initializedType = dim + inputStack[inputStack.length - value];\n }\n if (abstractType == initializedType) {\n if (abstractType == UNINITIALIZED_THIS) {\n return REFERENCE_KIND | symbolTable.addType(symbolTable.className);\n } else {\n return REFERENCE_KIND\n | symbolTable.addType(symbolTable.typeTable[abstractType & VALUE_MASK].value);\n }\n }\n }\n }\n return abstractType;\n }\n\n // -----------------------------------------------------------------------------------------------\n // Main method, to simulate the execution of each instruction on the output frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Simulates the action of the given instruction on the output stack frame.\n *\n * @param opcode the opcode of the instruction.\n * @param arg the numeric operand of the instruction, if any.\n * @param argSymbol the Symbol operand of the instruction, if any.\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n */\n void execute(\n final int opcode, final int arg, final Symbol argSymbol, final SymbolTable symbolTable) {\n final int CONSTANT_INTEGER_TAG = 3;\n final int CONSTANT_FLOAT_TAG = 4;\n final int CONSTANT_LONG_TAG = 5;\n final int CONSTANT_DOUBLE_TAG = 6;\n final int CONSTANT_CLASS_TAG = 7;\n final int CONSTANT_STRING_TAG = 8;\n final int CONSTANT_METHOD_HANDLE_TAG = 15;\n final int CONSTANT_METHOD_TYPE_TAG = 16;\n final int CONSTANT_DYNAMIC_TAG = 17;\n\n // Abstract types popped from the stack or read from local variables.\n int abstractType1;\n int abstractType2;\n int abstractType3;\n int abstractType4;\n switch (opcode) {\n case Opcodes.NOP:\n case Opcodes.INEG:\n case Opcodes.LNEG:\n case Opcodes.FNEG:\n case Opcodes.DNEG:\n case Opcodes.I2B:\n case Opcodes.I2C:\n case Opcodes.I2S:\n case Opcodes.GOTO:\n case Opcodes.RETURN:\n break;\n case Opcodes.ACONST_NULL:\n push(NULL);\n break;\n case Opcodes.ICONST_M1:\n case Opcodes.ICONST_0:\n case Opcodes.ICONST_1:\n case Opcodes.ICONST_2:\n case Opcodes.ICONST_3:\n case Opcodes.ICONST_4:\n case Opcodes.ICONST_5:\n case Opcodes.BIPUSH:\n case Opcodes.SIPUSH:\n case Opcodes.ILOAD:\n push(INTEGER);\n break;\n case Opcodes.LCONST_0:\n case Opcodes.LCONST_1:\n case Opcodes.LLOAD:\n push(LONG);\n push(TOP);\n break;\n case Opcodes.FCONST_0:\n case Opcodes.FCONST_1:\n case Opcodes.FCONST_2:\n case Opcodes.FLOAD:\n push(FLOAT);\n break;\n case Opcodes.DCONST_0:\n case Opcodes.DCONST_1:\n case Opcodes.DLOAD:\n push(DOUBLE);\n push(TOP);\n break;\n case Opcodes.LDC:\n switch (argSymbol.tag) {\n case CONSTANT_INTEGER_TAG:\n push(INTEGER);\n break;\n case CONSTANT_LONG_TAG:\n push(LONG);\n push(TOP);\n break;\n case CONSTANT_FLOAT_TAG:\n push(FLOAT);\n break;\n case CONSTANT_DOUBLE_TAG:\n push(DOUBLE);\n push(TOP);\n break;\n case CONSTANT_CLASS_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/Class\"));\n break;\n case CONSTANT_STRING_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/String\"));\n break;\n case CONSTANT_METHOD_TYPE_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/invoke/MethodType\"));\n break;\n case CONSTANT_METHOD_HANDLE_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/invoke/MethodHandle\"));\n break;\n case CONSTANT_DYNAMIC_TAG:\n push(symbolTable, argSymbol.value);\n break;\n default:\n throw new AssertionError();\n }\n break;\n case Opcodes.ALOAD:\n push(getLocal(arg));\n break;\n case Opcodes.LALOAD:\n case Opcodes.D2L:\n pop(2);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.AALOAD:\n pop(1);\n abstractType1 = pop();\n push(abstractType1 == NULL ? abstractType1 : ELEMENT_OF + abstractType1);\n break;\n case Opcodes.ISTORE:\n case Opcodes.FSTORE:\n case Opcodes.ASTORE:\n abstractType1 = pop();\n setLocal(arg, abstractType1);\n if (arg > 0) {\n int previousLocalType = getLocal(arg - 1);\n if (previousLocalType == LONG || previousLocalType == DOUBLE) {\n setLocal(arg - 1, TOP);\n } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND\n || (previousLocalType & KIND_MASK) == STACK_KIND) {\n // The type of the previous local variable is not known yet, but if it later appears\n // to be LONG or DOUBLE, we should then use TOP instead.\n setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG);\n }\n }\n break;\n case Opcodes.LSTORE:\n case Opcodes.DSTORE:\n pop(1);\n abstractType1 = pop();\n setLocal(arg, abstractType1);\n setLocal(arg + 1, TOP);\n if (arg > 0) {\n int previousLocalType = getLocal(arg - 1);\n if (previousLocalType == LONG || previousLocalType == DOUBLE) {\n setLocal(arg - 1, TOP);\n } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND\n || (previousLocalType & KIND_MASK) == STACK_KIND) {\n // The type of the previous local variable is not known yet, but if it later appears\n // to be LONG or DOUBLE, we should then use TOP instead.\n setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG);\n }\n }\n break;\n case Opcodes.POP:\n case Opcodes.IFEQ:\n case Opcodes.IFNE:\n case Opcodes.IFLT:\n case Opcodes.IFGE:\n case Opcodes.IFGT:\n case Opcodes.IFLE:\n case Opcodes.IRETURN:\n case Opcodes.FRETURN:\n case Opcodes.ARETURN:\n case Opcodes.TABLESWITCH:\n case Opcodes.LOOKUPSWITCH:\n case Opcodes.ATHROW:\n case Opcodes.MONITORENTER:\n case Opcodes.MONITOREXIT:\n case Opcodes.IFNULL:\n case Opcodes.IFNONNULL:\n pop(1);\n break;\n case Opcodes.POP2:\n case Opcodes.IF_ICMPEQ:\n case Opcodes.IF_ICMPNE:\n case Opcodes.IF_ICMPLT:\n case Opcodes.IF_ICMPGE:\n case Opcodes.IF_ICMPGT:\n case Opcodes.IF_ICMPLE:\n case Opcodes.IF_ACMPEQ:\n case Opcodes.IF_ACMPNE:\n case Opcodes.LRETURN:\n case Opcodes.DRETURN:\n pop(2);\n break;\n case Opcodes.DUP:\n abstractType1 = pop();\n push(abstractType1);\n push(abstractType1);\n break;\n case Opcodes.DUP2:\n abstractType1 = pop();\n abstractType2 = pop();\n push(abstractType2);\n push(abstractType1);\n push(abstractType2);\n push(abstractType1);\n break;\n case Opcodes.SWAP:\n abstractType1 = pop();\n abstractType2 = pop();\n push(abstractType1);\n push(abstractType2);\n break;\n case Opcodes.IALOAD:\n case Opcodes.BALOAD:\n case Opcodes.CALOAD:\n case Opcodes.SALOAD:\n case Opcodes.IADD:\n case Opcodes.ISUB:\n case Opcodes.IMUL:\n case Opcodes.IDIV:\n case Opcodes.IREM:\n case Opcodes.IAND:\n case Opcodes.IOR:\n case Opcodes.IXOR:\n case Opcodes.ISHL:\n case Opcodes.ISHR:\n case Opcodes.IUSHR:\n case Opcodes.L2I:\n case Opcodes.D2I:\n case Opcodes.FCMPL:\n case Opcodes.FCMPG:\n pop(2);\n push(INTEGER);\n break;\n case Opcodes.LADD:\n case Opcodes.LSUB:\n case Opcodes.LMUL:\n case Opcodes.LDIV:\n case Opcodes.LREM:\n case Opcodes.LAND:\n case Opcodes.LOR:\n case Opcodes.LXOR:\n pop(4);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.LSHL:\n case Opcodes.LSHR:\n case Opcodes.LUSHR:\n pop(3);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.IINC:\n setLocal(arg, INTEGER);\n break;\n case Opcodes.F2I:\n case Opcodes.ARRAYLENGTH:\n case Opcodes.INSTANCEOF:\n pop(1);\n push(INTEGER);\n break;\n case Opcodes.LCMP:\n case Opcodes.DCMPL:\n case Opcodes.DCMPG:\n pop(4);\n push(INTEGER);\n break;\n case Opcodes.GETSTATIC:\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.PUTSTATIC:\n pop(argSymbol.value);\n break;\n case Opcodes.GETFIELD:\n pop(1);\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.PUTFIELD:\n pop(argSymbol.value);\n pop();\n break;\n case Opcodes.INVOKEVIRTUAL:\n case Opcodes.INVOKESPECIAL:\n case Opcodes.INVOKESTATIC:\n case Opcodes.INVOKEINTERFACE:\n pop(argSymbol.value);\n if (opcode != Opcodes.INVOKESTATIC) {\n abstractType1 = pop();\n if (opcode == Opcodes.INVOKESPECIAL && argSymbol.name.charAt(0) == '<') {\n addInitializedType(abstractType1);\n }\n }\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.NEW:\n push(UNINITIALIZED_KIND | symbolTable.addUninitializedType(argSymbol.value, arg));\n break;\n case Opcodes.CHECKCAST:\n String castType = argSymbol.value;\n pop();\n if (castType.charAt(0) == '[') {\n push(symbolTable, castType);\n } else {\n push(REFERENCE_KIND | symbolTable.addType(castType));\n }\n break;\n default:\n throw new IllegalArgumentException();\n }\n }\n\n // -----------------------------------------------------------------------------------------------\n // Frame merging methods, used in the second step of the stack map frame computation algorithm\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Computes the concrete output type corresponding to a given abstract output type.\n *\n * @param abstractOutputType an abstract output type.\n * @param numStack the size of the input stack, used to resolve abstract output types of\n * STACK_KIND kind.\n * @return the concrete output type corresponding to 'abstractOutputType'.\n */\n private int getConcreteOutputType(final int abstractOutputType, final int numStack) {\n int dim = abstractOutputType & DIM_MASK;\n int kind = abstractOutputType & KIND_MASK;\n if (kind == LOCAL_KIND) {\n // By definition, a LOCAL_KIND type designates the concrete type of a local variable at\n // the beginning of the basic block corresponding to this frame (which is known when\n // this method is called, but was not when the abstract type was computed).\n int concreteOutputType = dim + inputLocals[abstractOutputType & VALUE_MASK];\n if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0\n && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) {\n concreteOutputType = TOP;\n }\n return concreteOutputType;\n } else if (kind == STACK_KIND) {\n // By definition, a STACK_KIND type designates the concrete type of a local variable at\n // the beginning of the basic block corresponding to this frame (which is known when\n // this method is called, but was not when the abstract type was computed).\n int concreteOutputType = dim + inputStack[numStack - (abstractOutputType & VALUE_MASK)];\n if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0\n && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) {\n concreteOutputType = TOP;\n }\n return concreteOutputType;\n } else {\n return abstractOutputType;\n }\n }\n\n final boolean merge(\n final SymbolTable symbolTable, final Frame dstFrame) {\n boolean frameChanged = false;\n\n // Compute the concrete types of the local variables at the end of the basic block corresponding\n // to this frame, by resolving its abstract output types, and merge these concrete types with\n // those of the local variables in the input frame of dstFrame.\n int numLocal = inputLocals.length;\n int numStack = inputStack.length;\n if (dstFrame.inputLocals == null) {\n dstFrame.inputLocals = new int[numLocal];\n frameChanged = true;\n }\n for (int i = 0; i < numLocal; ++i) {\n int concreteOutputType;\n if (outputLocals != null && i < outputLocals.length) {\n int abstractOutputType = outputLocals[i];\n if (abstractOutputType == 0) {\n // If the local variable has never been assigned in this basic block, it is equal to its\n // value at the beginning of the block.\n concreteOutputType = inputLocals[i];\n } else {\n concreteOutputType = getConcreteOutputType(abstractOutputType, numStack);\n }\n } else {\n // If the local variable has never been assigned in this basic block, it is equal to its\n // value at the beginning of the block.\n concreteOutputType = inputLocals[i];\n }\n // concreteOutputType might be an uninitialized type from the input locals or from the input\n // stack. However, if a constructor has been called for this class type in the basic block,\n // then this type is no longer uninitialized at the end of basic block.\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputLocals, i);\n }\n\n // Compute the concrete types of the stack operands at the end of the basic block corresponding\n // to this frame, by resolving its abstract output types, and merge these concrete types with\n // those of the stack operands in the input frame of dstFrame.\n int numInputStack = inputStack.length + outputStackStart;\n if (dstFrame.inputStack == null) {\n dstFrame.inputStack = new int[numInputStack + outputStackTop];\n frameChanged = true;\n }\n // First, do this for the stack operands that have not been popped in the basic block\n // corresponding to this frame, and which are therefore equal to their value in the input\n // frame (except for uninitialized types, which may have been initialized).\n for (int i = 0; i < numInputStack; ++i) {\n int concreteOutputType = inputStack[i];\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputStack, i);\n }\n // Then, do this for the stack operands that have pushed in the basic block (this code is the\n // same as the one above for local variables).\n for (int i = 0; i < outputStackTop; ++i) {\n int abstractOutputType = outputStack[i];\n int concreteOutputType = getConcreteOutputType(abstractOutputType, numStack);\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |=\n merge(symbolTable, concreteOutputType, dstFrame.inputStack, numInputStack + i);\n }\n return frameChanged;\n }\n\n /**\n * Merges the type at the given index in the given abstract type array with the given type.\n * Returns {@literal true} if the type array has been modified by this operation.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param sourceType the abstract type with which the abstract type array element must be merged.\n * This type should be of {@link #CONSTANT_KIND}, {@link #REFERENCE_KIND} or {@link\n * #UNINITIALIZED_KIND} kind, with positive or {@literal null} array dimensions.\n * @param dstTypes an array of abstract types. These types should be of {@link #CONSTANT_KIND},\n * {@link #REFERENCE_KIND} or {@link #UNINITIALIZED_KIND} kind, with positive or {@literal\n * null} array dimensions.\n * @param dstIndex the index of the type that must be merged in dstTypes.\n * @return {@literal true} if the type array has been modified by this operation.\n */\n private static boolean merge(\n final SymbolTable symbolTable,\n final int sourceType,\n final int[] dstTypes,\n final int dstIndex) {\n int dstType = dstTypes[dstIndex];\n if (dstType == sourceType) {\n // If the types are equal, merge(sourceType, dstType) = dstType, so there is no change.\n return false;\n }\n int srcType = sourceType;\n if ((sourceType & ~DIM_MASK) == NULL) {\n if (dstType == NULL) {\n return false;\n }\n srcType = NULL;\n }\n if (dstType == 0) {\n // If dstTypes[dstIndex] has never been assigned, merge(srcType, dstType) = srcType.\n dstTypes[dstIndex] = srcType;\n return true;\n }\n int mergedType;\n if ((dstType & DIM_MASK) != 0 || (dstType & KIND_MASK) == REFERENCE_KIND) {\n // If dstType is a reference type of any array dimension.\n if (srcType == NULL) {\n // If srcType is the NULL type, merge(srcType, dstType) = dstType, so there is no change.\n return false;\n } else if ((srcType & (DIM_MASK | KIND_MASK)) == (dstType & (DIM_MASK | KIND_MASK))) {\n // If srcType has the same array dimension and the same kind as dstType.\n if ((dstType & KIND_MASK) == REFERENCE_KIND) {\n // If srcType and dstType are reference types with the same array dimension,\n // merge(srcType, dstType) = dim(srcType) | common super class of srcType and dstType.\n mergedType =\n (srcType & DIM_MASK)\n | REFERENCE_KIND\n | symbolTable.addMergedType(srcType & VALUE_MASK, dstType & VALUE_MASK);\n } else {\n // If srcType and dstType are array types of equal dimension but different element types,\n // merge(srcType, dstType) = dim(srcType) - 1 | java/lang/Object.\n int mergedDim = ELEMENT_OF + (srcType & DIM_MASK);\n mergedType = mergedDim | REFERENCE_KIND | symbolTable.addType(\"java/lang/Object\");\n }\n } else if ((srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND) {\n // If srcType is any other reference or array type,\n // merge(srcType, dstType) = min(srcDdim, dstDim) | java/lang/Object\n // where srcDim is the array dimension of srcType, minus 1 if srcType is an array type\n // with a non reference element type (and similarly for dstDim).\n int srcDim = srcType & DIM_MASK;\n if (srcDim != 0 && (srcType & KIND_MASK) != REFERENCE_KIND) {\n srcDim = ELEMENT_OF + srcDim;\n }\n int dstDim = dstType & DIM_MASK;\n if (dstDim != 0 && (dstType & KIND_MASK) != REFERENCE_KIND) {\n dstDim = ELEMENT_OF + dstDim;\n }\n mergedType =\n Math.min(srcDim, dstDim) | REFERENCE_KIND | symbolTable.addType(\"java/lang/Object\");\n } else {\n // If srcType is any other type, merge(srcType, dstType) = TOP.\n mergedType = TOP;\n }\n } else if (dstType == NULL) {\n // If dstType is the NULL type, merge(srcType, dstType) = srcType, or TOP if srcType is not a\n // an array type or a reference type.\n mergedType =\n (srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND ? srcType : TOP;\n } else {\n // If dstType is any other type, merge(srcType, dstType) = TOP whatever srcType.\n mergedType = TOP;\n }\n if (mergedType != dstType) {\n dstTypes[dstIndex] = mergedType;\n return true;\n }\n return false;\n }\n\n // -----------------------------------------------------------------------------------------------\n // Frame output methods, to generate StackMapFrame attributes\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Makes the given {@link MethodWriter} visit the input frame of this {@link Frame}. The visit is\n * done with the {@link MethodWriter#visitFrameStart}, {@link MethodWriter#visitAbstractType} and\n * {@link MethodWriter#visitFrameEnd} methods.\n *\n * @param methodWriter the {@link MethodWriter} that should visit the input frame of this {@link\n * Frame}.\n */\n final void accept(final MethodWriter methodWriter) {\n // Compute the number of locals, ignoring TOP types that are just after a LONG or a DOUBLE, and\n // all trailing TOP types.\n int[] localTypes = inputLocals;\n int numLocal = 0;\n int numTrailingTop = 0;\n int i = 0;\n while (i < localTypes.length) {\n int localType = localTypes[i];\n i += (localType == LONG || localType == DOUBLE) ? 2 : 1;\n if (localType == TOP) {\n numTrailingTop++;\n } else {\n numLocal += numTrailingTop + 1;\n numTrailingTop = 0;\n }\n }\n // Compute the stack size, ignoring TOP types that are just after a LONG or a DOUBLE.\n int[] stackTypes = inputStack;\n int numStack = 0;\n i = 0;\n while (i < stackTypes.length) {\n int stackType = stackTypes[i];\n i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1;\n numStack++;\n }\n // Visit the frame and its content.\n int frameIndex = methodWriter.visitFrameStart(owner.bytecodeOffset, numLocal, numStack);\n i = 0;\n while (numLocal-- > 0) {\n int localType = localTypes[i];\n i += (localType == LONG || localType == DOUBLE) ? 2 : 1;\n methodWriter.visitAbstractType(frameIndex++, localType);\n }\n i = 0;\n while (numStack-- > 0) {\n int stackType = stackTypes[i];\n i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1;\n methodWriter.visitAbstractType(frameIndex++, stackType);\n }\n methodWriter.visitFrameEnd();\n }\n//\n// /**\n// * Put the given abstract type in the given ByteVector, using the JVMS verification_type_info\n// * format used in StackMapTable attributes.\n// *\n// * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n// * @param abstractType an abstract type, restricted to {@link Frame#CONSTANT_KIND}, {@link\n// * Frame#REFERENCE_KIND} or {@link Frame#UNINITIALIZED_KIND} types.\n// * @param output where the abstract type must be put.\n// * @see JVMS\n// * 4.7.4\n// */\n// static void putAbstractType(\n// final SymbolTable symbolTable, final int abstractType, final ByteVector output) {\n// int arrayDimensions = (abstractType & Frame.DIM_MASK) >> DIM_SHIFT;\n// if (arrayDimensions == 0) {\n// int typeValue = abstractType & VALUE_MASK;\n// switch (abstractType & KIND_MASK) {\n// case CONSTANT_KIND:\n// output.putByte(typeValue);\n// break;\n// case REFERENCE_KIND:\n// output\n// .putByte(ITEM_OBJECT)\n// .putShort(symbolTable.addConstantUtf8Reference(/*CONSTANT_CLASS_TAG*/ 7, symbolTable.typeTable[typeValue].value).index);\n// break;\n// case UNINITIALIZED_KIND:\n// output.putByte(ITEM_UNINITIALIZED).putShort((int) symbolTable.typeTable[typeValue].data);\n// break;\n// default:\n// throw new AssertionError();\n// }\n// } else {\n// // Case of an array type, we need to build its descriptor first.\n// StringBuilder typeDescriptor = new StringBuilder();\n// while (arrayDimensions-- > 0) {\n// typeDescriptor.append('[');\n// }\n// if ((abstractType & KIND_MASK) == REFERENCE_KIND) {\n// typeDescriptor\n// .append('L')\n// .append(symbolTable.typeTable[abstractType & VALUE_MASK].value)\n// .append(';');\n// } else {\n// switch (abstractType & VALUE_MASK) {\n// case Frame.ITEM_ASM_BOOLEAN:\n// typeDescriptor.append('Z');\n// break;\n// case Frame.ITEM_ASM_BYTE:\n// typeDescriptor.append('B');\n// break;\n// case Frame.ITEM_ASM_CHAR:\n// typeDescriptor.append('C');\n// break;\n// case Frame.ITEM_ASM_SHORT:\n// typeDescriptor.append('S');\n// break;\n// case Frame.ITEM_INTEGER:\n// typeDescriptor.append('I');\n// break;\n// case Frame.ITEM_FLOAT:\n// typeDescriptor.append('F');\n// break;\n// case Frame.ITEM_LONG:\n// typeDescriptor.append('J');\n// break;\n// case Frame.ITEM_DOUBLE:\n// typeDescriptor.append('D');\n// break;\n// default:\n// throw new AssertionError();\n// }\n// }\n// output\n// .putByte(ITEM_OBJECT)\n// .putShort(symbolTable.addConstantUtf8Reference(/*CONSTANT_CLASS_TAG*/ 7, typeDescriptor.toString()).index);\n// }\n// }\n}\n", "file_name": "Frame.java", "human_label": "Pop the given number of elements from the stack.", "level": "self_contained", "lineno": "631", "name": "pop", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[outputStackTop, outputStackStart]\" }", "package": "com.alibaba.fastjson2.internal.asm", "project": "fastjson2-main" }, { "_id": "636767e11a6d9265ec018795", "all_context": "{ \"class_level\" : \"import java.util.Arrays;\\nimport java.util.List;\\nimport lombok.Getter;\\nimport lombok.Setter;\\nimport lombok.ToString;\\nimport org.apache.commons.lang3.StringUtils;\\nimport org.apache.skywalking.oap.server.core.analysis.metrics.DataTable;\\nimport org.apache.skywalking.oap.server.core.query.type.Bucket;\\nimport org.apache.skywalking.oap.server.core.query.type.HeatMap;\\nString group;\\nlong[] buckets;\\nlong[] values;\\nBucketedValues(long[] buckets,long[] values);\\n\", \"repo_level\" : \"public interface DataTable {public Long get(String key);\\npublic void put(String key,Long value);\\npublic void valueAccumulation(String key,Long value);\\npublic long sumOfValues();\\npublic boolean keysEqual(DataTable that);\\npublic List sortedKeys(Comparator keyComparator);\\npublic List sortedValues(Comparator keyComparator);\\npublic Set keys();\\npublic boolean hasData();\\npublic boolean hasKey(String key);\\npublic int size();\\npublic String toStorageData();\\npublic void toObject(String data);\\npublic void copyFrom(DataTable source);\\npublic DataTable append(DataTable dataTable);\\n }\\npublic interface Bucket {public Bucket setMin(int min);\\npublic Bucket setMax(int max);\\npublic Bucket infiniteMin();\\npublic Bucket infiniteMax();\\npublic boolean isInfiniteMin();\\npublic boolean isInfiniteMax();\\npublic int duration();\\n }\\npublic interface HeatMap {public void addBucket(Bucket bucket);\\npublic void buildColumn(String id,String rawdata,int defaultValue);\\npublic void fixMissingColumns(List ids,int defaultValue);\\npublic void addValue(Long value);\\npublic int compare(String k1,String k2);\\n }\\n\" }", "class_name": "BucketedValues", "code": "public boolean isCompatible(DataTable dataset){\n final List sortedKeys=dataset.sortedKeys(new HeatMap.KeyComparator(true));\n long[] existedBuckets=new long[sortedKeys.size()];\n for (int i=0; i < sortedKeys.size(); i++) {\n String key=sortedKeys.get(i);\n if (key.equals(Bucket.INFINITE_NEGATIVE)) {\n existedBuckets[i]=Long.MIN_VALUE;\n }\n else {\n if (key.contains(\":\")) {\n key=StringUtils.substringAfterLast(key,\":\");\n }\n existedBuckets[i]=Long.parseLong(key);\n }\n }\n return Arrays.equals(buckets,existedBuckets);\n}\n", "docstring": "/** \n * @return true if the bucket is same.\n */\n", "end_lineno": "88", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.core.analysis.meter.function;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport lombok.Getter;\nimport lombok.Setter;\nimport lombok.ToString;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.skywalking.oap.server.core.analysis.metrics.DataTable;\nimport org.apache.skywalking.oap.server.core.query.type.Bucket;\nimport org.apache.skywalking.oap.server.core.query.type.HeatMap;\n\n/**\n * BucketedValues represents a value set, which elements are grouped by time bucket.\n */\n@ToString\n@Getter\npublic class BucketedValues {\n\n @Setter\n private String group;\n /**\n * The element in the buckets represent the minimal value of this bucket, the max is defined by the next element.\n * Such as 0, 10, 50, 100 means buckets are [0, 10), [10, 50), [50, 100), [100, infinite+).\n *\n * The {@link Long#MIN_VALUE} could be the first bucket element to indicate there is no minimal value.\n */\n private long[] buckets;\n /**\n * {@link #buckets} and {@link #values} arrays should have the same length. The element in the values, represents\n * the amount in the same index bucket.\n */\n private long[] values;\n\n /**\n * @param buckets Read {@link #buckets}\n * @param values Read {@link #values}\n */\n public BucketedValues(final long[] buckets, final long[] values) {\n if (buckets == null || values == null || buckets.length == 0 || values.length == 0) {\n throw new IllegalArgumentException(\"buckets and values can't be null.\");\n }\n if (buckets.length != values.length) {\n throw new IllegalArgumentException(\"The length of buckets and values should be same.\");\n }\n this.buckets = buckets;\n this.values = values;\n }\n\n /**\n * @return true if the bucket is same.\n */\n public boolean isCompatible(DataTable dataset) {\n final List sortedKeys = dataset.sortedKeys(new HeatMap.KeyComparator(true));\n long[] existedBuckets = new long[sortedKeys.size()];\n for (int i = 0; i < sortedKeys.size(); i++) {\n String key = sortedKeys.get(i);\n if (key.equals(Bucket.INFINITE_NEGATIVE)) {\n existedBuckets[i] = Long.MIN_VALUE;\n } else {\n // remove the group name\n if (key.contains(\":\")) {\n key = StringUtils.substringAfterLast(key, \":\");\n }\n existedBuckets[i] = Long.parseLong(key);\n }\n }\n\n return Arrays.equals(buckets, existedBuckets);\n }\n}\n", "file_name": "BucketedValues.java", "human_label": "Check whether the existed buckets are the same as the buckets.", "level": "plib_runnable", "lineno": "68", "name": "isCompatible", "oracle_context": "{ \"apis\" : \"[KeyComparator, size, get, equals, contains, substringAfterLast, parseLong]\", \"classes\" : \"[List, long[], String, HeatMap, Bucket, Long]\", \"vars\" : \"[INFINITE_NEGATIVE, MIN_VALUE, buckets]\" }", "package": "org.apache.skywalking.oap.server.core.analysis.meter.function", "project": "skywalking-master" }, { "_id": "636767791a6d9265ec018263", "all_context": "{ \"class_level\" : \"import org.apache.log4j.spi.ThrowableRenderer;\\nimport java.io.File;\\nimport java.lang.reflect.Method;\\nimport java.net.URL;\\nimport java.security.CodeSource;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nMethod getStackTraceMethod;\\nMethod getClassNameMethod;\\nEnhancedThrowableRenderer();\\nformatElement(Object element,Map classMap);\\nfindClass(String className);\\ndoRender(Throwable throwable);\\n\", \"repo_level\" : \"public interface ThrowableRenderer {public String[] doRender(Throwable t);\\n }\\n\" }", "class_name": "EnhancedThrowableRenderer", "code": "private Class findClass(final String className) throws ClassNotFoundException {\n try {\n return Thread.currentThread().getContextClassLoader().loadClass(className);\n }\n catch ( ClassNotFoundException e) {\n try {\n return Class.forName(className);\n }\n catch ( ClassNotFoundException e1) {\n return getClass().getClassLoader().loadClass(className);\n }\n }\n}\n", "docstring": "/** \n * Find class given class name.\n * @param className class name, may not be null.\n * @return class, will not be null.\n * @throws ClassNotFoundException thrown if class can not be found.\n */\n", "end_lineno": "166", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.log4j;\n\nimport org.apache.log4j.spi.ThrowableRenderer;\n\nimport java.io.File;\nimport java.lang.reflect.Method;\nimport java.net.URL;\nimport java.security.CodeSource;\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Enhanced implementation of ThrowableRenderer. Uses Throwable.getStackTrace\n * if running on JDK 1.4 or later and delegates to DefaultThrowableRenderer.render\n * on earlier virtual machines.\n *\n * @since 1.2.16\n */\npublic final class EnhancedThrowableRenderer implements ThrowableRenderer {\n /**\n * Throwable.getStackTrace() method.\n */\n private Method getStackTraceMethod;\n /**\n * StackTraceElement.getClassName() method.\n */\n private Method getClassNameMethod;\n\n\n /**\n * Construct new instance.\n */\n public EnhancedThrowableRenderer() {\n try {\n Class[] noArgs = null;\n getStackTraceMethod = Throwable.class.getMethod(\"getStackTrace\", noArgs);\n Class ste = Class.forName(\"java.lang.StackTraceElement\");\n getClassNameMethod = ste.getMethod(\"getClassName\", noArgs);\n } catch(Exception ex) {\n }\n }\n\n /**\n * {@inheritDoc}\n */\n public String[] doRender(final Throwable throwable) {\n if (getStackTraceMethod != null) {\n try {\n Object[] noArgs = null;\n Object[] elements = (Object[]) getStackTraceMethod.invoke(throwable, noArgs);\n String[] lines = new String[elements.length + 1];\n lines[0] = throwable.toString();\n Map classMap = new HashMap();\n for(int i = 0; i < elements.length; i++) {\n lines[i+1] = formatElement(elements[i], classMap);\n }\n return lines;\n } catch(Exception ex) {\n }\n }\n return DefaultThrowableRenderer.render(throwable);\n }\n\n /**\n * Format one element from stack trace.\n * @param element element, may not be null.\n * @param classMap map of class name to location.\n * @return string representation of element.\n */\n private String formatElement(final Object element, final Map classMap) {\n StringBuffer buf = new StringBuffer(\"\\tat \");\n buf.append(element);\n try {\n String className = getClassNameMethod.invoke(element, (Object[]) null).toString();\n Object classDetails = classMap.get(className);\n if (classDetails != null) {\n buf.append(classDetails);\n } else {\n Class cls = findClass(className);\n int detailStart = buf.length();\n buf.append('[');\n try {\n CodeSource source = cls.getProtectionDomain().getCodeSource();\n if (source != null) {\n URL locationURL = source.getLocation();\n if (locationURL != null) {\n //\n // if a file: URL\n //\n if (\"file\".equals(locationURL.getProtocol())) {\n String path = locationURL.getPath();\n if (path != null) {\n //\n // find the last file separator character\n //\n int lastSlash = path.lastIndexOf('/');\n int lastBack = path.lastIndexOf(File.separatorChar);\n if (lastBack > lastSlash) {\n lastSlash = lastBack;\n }\n //\n // if no separator or ends with separator (a directory)\n // then output the URL, otherwise just the file name.\n //\n if (lastSlash <= 0 || lastSlash == path.length() - 1) {\n buf.append(locationURL);\n } else {\n buf.append(path.substring(lastSlash + 1));\n }\n }\n } else {\n buf.append(locationURL);\n }\n }\n }\n } catch(SecurityException ex) {\n }\n buf.append(':');\n Package pkg = cls.getPackage();\n if (pkg != null) {\n String implVersion = pkg.getImplementationVersion();\n if (implVersion != null) {\n buf.append(implVersion);\n }\n }\n buf.append(']');\n classMap.put(className, buf.substring(detailStart));\n }\n } catch(Exception ex) {\n }\n return buf.toString();\n }\n\n /**\n * Find class given class name.\n * @param className class name, may not be null.\n * @return class, will not be null.\n * @throws ClassNotFoundException thrown if class can not be found.\n */\n private Class findClass(final String className) throws ClassNotFoundException {\n try {\n return Thread.currentThread().getContextClassLoader().loadClass(className);\n } catch (ClassNotFoundException e) {\n try {\n return Class.forName(className);\n } catch (ClassNotFoundException e1) {\n return getClass().getClassLoader().loadClass(className);\n }\n }\n }\n\n}\n", "file_name": "EnhancedThrowableRenderer.java", "human_label": "Find class by the given class name.", "level": "slib_runnable", "lineno": "150", "name": "findClass", "oracle_context": "{ \"apis\" : \"[loadClass, getContextClassLoader, currentThread, forName, getClassLoader, getClass]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "org.apache.log4j", "project": "logging-log4j1-main" }, { "_id": "636767611a6d9265ec018112", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.alg.connectivity.*;\\nimport org.jgrapht.alg.interfaces.*;\\nimport org.jgrapht.traverse.*;\\nimport java.util.*;\\nGraph graph;\\nlong serialVersionUID;\\nList path;\\nSet cycleSet;\\nV root;\\nCycleDetector(Graph graph);\\ndetectCyclesContainingVertex(V v);\\nfindCycles();\\nfindCyclesContainingVertex(V v);\\nexecute(Set s,V v);\\nProbeIterator(Graph graph,Set cycleSet,V startVertex);\\nencounterVertexAgain(V vertex,E edge);\\nprovideNextVertex();\\ndetectCycles();\\n\", \"repo_level\" : \"\" }", "class_name": "CycleDetector$ProbeIterator", "code": "@Override protected V provideNextVertex(){\n V v=super.provideNextVertex();\n for (int i=path.size() - 1; i >= 0; --i) {\n if (graph.containsEdge(path.get(i),v)) {\n break;\n }\n path.remove(i);\n }\n path.add(v);\n return v;\n}\n", "docstring": "/** \n * {@inheritDoc}\n */\n", "end_lineno": "239", "file_content": "/*\n * (C) Copyright 2004-2021, by John V Sichi and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.cycle;\n\nimport org.jgrapht.*;\nimport org.jgrapht.alg.connectivity.*;\nimport org.jgrapht.alg.interfaces.*;\nimport org.jgrapht.traverse.*;\n\nimport java.util.*;\n\n/**\n * Performs cycle detection on a graph. The inspected graph is specified at construction time\n * and cannot be modified. Currently, the detector supports only directed graphs.\n *\n * @param the graph vertex type\n * @param the graph edge type\n *\n * @author John V. Sichi\n */\npublic class CycleDetector\n{\n /**\n * Graph on which cycle detection is being performed.\n */\n private Graph graph;\n\n /**\n * Creates a cycle detector for the specified graph. Currently only directed graphs are\n * supported.\n *\n * @param graph the directed graph in which to detect cycles\n */\n public CycleDetector(Graph graph)\n {\n this.graph = GraphTests.requireDirected(graph);\n }\n\n /**\n * Performs yes/no cycle detection on the entire graph.\n *\n * @return true iff the graph contains at least one cycle\n */\n public boolean detectCycles()\n {\n try {\n execute(null, null);\n } catch (CycleDetectedException ex) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Performs yes/no cycle detection on an individual vertex.\n *\n * @param v the vertex to test\n *\n * @return true if v is on at least one cycle\n */\n public boolean detectCyclesContainingVertex(V v)\n {\n try {\n execute(null, v);\n } catch (CycleDetectedException ex) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Finds the vertex set for the subgraph of all cycles.\n *\n * @return set of all vertices which participate in at least one cycle in this graph\n */\n public Set findCycles()\n {\n // ProbeIterator can't be used to handle this case,\n // so use StrongConnectivityAlgorithm instead.\n StrongConnectivityAlgorithm inspector =\n new KosarajuStrongConnectivityInspector<>(graph);\n List> components = inspector.stronglyConnectedSets();\n\n // A vertex participates in a cycle if either of the following is\n // true: (a) it is in a component whose size is greater than 1\n // or (b) it is a self-loop\n\n Set set = new LinkedHashSet<>();\n for (Set component : components) {\n if (component.size() > 1) {\n // cycle\n set.addAll(component);\n } else {\n V v = component.iterator().next();\n if (graph.containsEdge(v, v)) {\n // self-loop\n set.add(v);\n }\n }\n }\n\n return set;\n }\n\n /**\n * Finds the vertex set for the subgraph of all cycles which contain a particular vertex.\n *\n *

      \n * REVIEW jvs 25-Aug-2006: This implementation is not guaranteed to cover all cases. If you want\n * to be absolutely certain that you report vertices from all cycles containing v, it's safer\n * (but less efficient) to use StrongConnectivityAlgorithm instead and return the strongly\n * connected component containing v.\n *\n * @param v the vertex to test\n *\n * @return set of all vertices reachable from v via at least one cycle\n */\n public Set findCyclesContainingVertex(V v)\n {\n Set set = new LinkedHashSet<>();\n execute(set, v);\n\n return set;\n }\n\n private void execute(Set s, V v)\n {\n ProbeIterator iter = new ProbeIterator<>(graph, s, v);\n\n while (iter.hasNext()) {\n iter.next();\n }\n }\n\n /**\n * Exception thrown internally when a cycle is detected during a yes/no cycle test. Must be\n * caught by top-level detection method.\n */\n private static class CycleDetectedException\n extends\n RuntimeException\n {\n private static final long serialVersionUID = 3834305137802950712L;\n }\n\n /**\n * Version of DFS which maintains a backtracking path used to probe for cycles.\n */\n private static class ProbeIterator\n extends\n DepthFirstIterator\n {\n private List path;\n private Set cycleSet;\n private V root;\n\n ProbeIterator(Graph graph, Set cycleSet, V startVertex)\n {\n super(graph, startVertex);\n this.path = new ArrayList<>();\n this.cycleSet = cycleSet;\n this.root = startVertex;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n protected void encounterVertexAgain(V vertex, E edge)\n {\n super.encounterVertexAgain(vertex, edge);\n\n int i;\n\n if (root != null) {\n // For rooted detection, the path must either\n // double back to the root, or to a node of a cycle\n // which has already been detected.\n if (vertex.equals(root)) {\n i = 0;\n } else if ((cycleSet != null) && cycleSet.contains(vertex)) {\n i = 0;\n } else {\n return;\n }\n } else {\n i = path.indexOf(vertex);\n }\n\n if (i > -1) {\n if (cycleSet == null) {\n // we're doing yes/no cycle detection\n throw new CycleDetectedException();\n } else {\n for (; i < path.size(); ++i) {\n cycleSet.add(path.get(i));\n }\n }\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n protected V provideNextVertex()\n {\n V v = super.provideNextVertex();\n\n // backtrack\n for (int i = path.size() - 1; i >= 0; --i) {\n if (graph.containsEdge(path.get(i), v)) {\n break;\n }\n\n path.remove(i);\n }\n\n path.add(v);\n\n return v;\n }\n }\n}\n", "file_name": "CycleDetector.java", "human_label": "Get next vertext from a graph.", "level": "class_runnable", "lineno": "219", "name": "provideNextVertex", "oracle_context": "{ \"apis\" : \"[size, containsEdge, get, remove, add]\", \"classes\" : \"[V]\", \"vars\" : \"[path, graph]\" }", "package": "org.jgrapht.alg.cycle", "project": "jgrapht-master" }, { "_id": "636767131a6d9265ec017b23", "all_context": "{ \"class_level\" : \"int FLAG_DEBUG_ONLY;\\nint FLAG_JUMP_TARGET;\\nint FLAG_RESOLVED;\\nint FLAG_REACHABLE;\\nint FLAG_SUBROUTINE_CALLER;\\nint FLAG_SUBROUTINE_START;\\nint FLAG_SUBROUTINE_END;\\nint LINE_NUMBERS_CAPACITY_INCREMENT;\\nint FORWARD_REFERENCES_CAPACITY_INCREMENT;\\nint FORWARD_REFERENCE_TYPE_MASK;\\nint FORWARD_REFERENCE_TYPE_SHORT;\\nint FORWARD_REFERENCE_TYPE_WIDE;\\nint FORWARD_REFERENCE_HANDLE_MASK;\\nLabel EMPTY_LIST;\\nObject info;\\nshort flags;\\nshort lineNumber;\\nint[] otherLineNumbers;\\nint bytecodeOffset;\\nint[] forwardReferences;\\nshort inputStackSize;\\nshort outputStackSize;\\nshort outputStackMax;\\nshort subroutineId;\\nFrame frame;\\nLabel nextBasicBlock;\\nEdge outgoingEdges;\\nLabel nextListElement;\\nLabel();\\ngetOffset();\\ngetCanonicalInstance();\\naccept(MethodVisitor methodVisitor,boolean visitLineNumbers);\\nput(ByteVector code,int sourceInsnBytecodeOffset,boolean wideReference);\\naddForwardReference(int sourceInsnBytecodeOffset,int referenceType,int referenceHandle);\\nresolve(byte[] code,int bytecodeOffset);\\nmarkSubroutine(short subroutineId);\\naddSubroutineRetSuccessors(Label subroutineCaller);\\npushSuccessors(Label listOfLabelsToProcess);\\ntoString();\\n\", \"repo_level\" : \"\" }", "class_name": "Label", "code": "final void addLineNumber(final int lineNumber){\n if (this.lineNumber == 0) {\n this.lineNumber=(short)lineNumber;\n }\n else {\n if (otherLineNumbers == null) {\n otherLineNumbers=new int[LINE_NUMBERS_CAPACITY_INCREMENT];\n }\n int otherLineNumberIndex=++otherLineNumbers[0];\n if (otherLineNumberIndex >= otherLineNumbers.length) {\n int[] newLineNumbers=new int[otherLineNumbers.length + LINE_NUMBERS_CAPACITY_INCREMENT];\n System.arraycopy(otherLineNumbers,0,newLineNumbers,0,otherLineNumbers.length);\n otherLineNumbers=newLineNumbers;\n }\n otherLineNumbers[otherLineNumberIndex]=lineNumber;\n }\n}\n", "docstring": "/** \n * Adds a source line number corresponding to this label.\n * @param lineNumber a source line number (which should be strictly positive).\n */\n", "end_lineno": "316", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage net.hasor.utils.asm;\n/**\n * A position in the bytecode of a method. Labels are used for jump, goto, and switch instructions,\n * and for try catch blocks. A label designates the instruction that is just after. Note\n * however that there can be other elements between a label and the instruction it designates (such\n * as other labels, stack map frames, line numbers, etc.).\n *\n * @author Eric Bruneton\n */\npublic class Label {\n /**\n * A flag indicating that a label is only used for debug attributes. Such a label is not the start\n * of a basic block, the target of a jump instruction, or an exception handler. It can be safely\n * ignored in control flow graph analysis algorithms (for optimization purposes).\n */\n static final int FLAG_DEBUG_ONLY = 1;\n /**\n * A flag indicating that a label is the target of a jump instruction, or the start of an\n * exception handler.\n */\n static final int FLAG_JUMP_TARGET = 2;\n /** A flag indicating that the bytecode offset of a label is known. */\n static final int FLAG_RESOLVED = 4;\n /** A flag indicating that a label corresponds to a reachable basic block. */\n static final int FLAG_REACHABLE = 8;\n /**\n * A flag indicating that the basic block corresponding to a label ends with a subroutine call. By\n * construction in {@link MethodWriter#visitJumpInsn}, labels with this flag set have at least two\n * outgoing edges:\n *\n *

        \n *
      • the first one corresponds to the instruction that follows the jsr instruction in the\n * bytecode, i.e. where execution continues when it returns from the jsr call. This is a\n * virtual control flow edge, since execution never goes directly from the jsr to the next\n * instruction. Instead, it goes to the subroutine and eventually returns to the instruction\n * following the jsr. This virtual edge is used to compute the real outgoing edges of the\n * basic blocks ending with a ret instruction, in {@link #addSubroutineRetSuccessors}.\n *
      • the second one corresponds to the target of the jsr instruction,\n *
      \n */\n static final int FLAG_SUBROUTINE_CALLER = 16;\n /**\n * A flag indicating that the basic block corresponding to a label is the start of a subroutine.\n */\n static final int FLAG_SUBROUTINE_START = 32;\n /** A flag indicating that the basic block corresponding to a label is the end of a subroutine. */\n static final int FLAG_SUBROUTINE_END = 64;\n /**\n * The number of elements to add to the {@link #otherLineNumbers} array when it needs to be\n * resized to store a new source line number.\n */\n static final int LINE_NUMBERS_CAPACITY_INCREMENT = 4;\n /**\n * The number of elements to add to the {@link #forwardReferences} array when it needs to be\n * resized to store a new forward reference.\n */\n static final int FORWARD_REFERENCES_CAPACITY_INCREMENT = 6;\n /**\n * The bit mask to extract the type of a forward reference to this label. The extracted type is\n * either {@link #FORWARD_REFERENCE_TYPE_SHORT} or {@link #FORWARD_REFERENCE_TYPE_WIDE}.\n *\n * @see #forwardReferences\n */\n static final int FORWARD_REFERENCE_TYPE_MASK = 0xF0000000;\n /**\n * The type of forward references stored with two bytes in the bytecode. This is the case, for\n * instance, of a forward reference from an ifnull instruction.\n */\n static final int FORWARD_REFERENCE_TYPE_SHORT = 0x10000000;\n /**\n * The type of forward references stored in four bytes in the bytecode. This is the case, for\n * instance, of a forward reference from a lookupswitch instruction.\n */\n static final int FORWARD_REFERENCE_TYPE_WIDE = 0x20000000;\n /**\n * The bit mask to extract the 'handle' of a forward reference to this label. The extracted handle\n * is the bytecode offset where the forward reference value is stored (using either 2 or 4 bytes,\n * as indicated by the {@link #FORWARD_REFERENCE_TYPE_MASK}).\n *\n * @see #forwardReferences\n */\n static final int FORWARD_REFERENCE_HANDLE_MASK = 0x0FFFFFFF;\n /**\n * A sentinel element used to indicate the end of a list of labels.\n *\n * @see #nextListElement\n */\n static final Label EMPTY_LIST = new Label();\n /**\n * A user managed state associated with this label. Warning: this field is used by the ASM tree\n * package. In order to use it with the ASM tree package you must override the getLabelNode method\n * in MethodNode.\n */\n public Object info;\n /**\n * The type and status of this label or its corresponding basic block. Must be zero or more of\n * {@link #FLAG_DEBUG_ONLY}, {@link #FLAG_JUMP_TARGET}, {@link #FLAG_RESOLVED}, {@link\n * #FLAG_REACHABLE}, {@link #FLAG_SUBROUTINE_CALLER}, {@link #FLAG_SUBROUTINE_START}, {@link\n * #FLAG_SUBROUTINE_END}.\n */\n short flags;\n /**\n * The source line number corresponding to this label, or 0. If there are several source line\n * numbers corresponding to this label, the first one is stored in this field, and the remaining\n * ones are stored in {@link #otherLineNumbers}.\n */\n private short lineNumber;\n /**\n * The source line numbers corresponding to this label, in addition to {@link #lineNumber}, or\n * null. The first element of this array is the number n of source line numbers it contains, which\n * are stored between indices 1 and n (inclusive).\n */\n private int[] otherLineNumbers;\n /**\n * The offset of this label in the bytecode of its method, in bytes. This value is set if and only\n * if the {@link #FLAG_RESOLVED} flag is set.\n */\n int bytecodeOffset;\n /**\n * The forward references to this label. The first element is the number of forward references,\n * times 2 (this corresponds to the index of the last element actually used in this array). Then,\n * each forward reference is described with two consecutive integers noted\n * 'sourceInsnBytecodeOffset' and 'reference':\n *\n *
        \n *
      • 'sourceInsnBytecodeOffset' is the bytecode offset of the instruction that contains the\n * forward reference,\n *
      • 'reference' contains the type and the offset in the bytecode where the forward reference\n * value must be stored, which can be extracted with {@link #FORWARD_REFERENCE_TYPE_MASK}\n * and {@link #FORWARD_REFERENCE_HANDLE_MASK}.\n *
      \n *\n *

      For instance, for an ifnull instruction at bytecode offset x, 'sourceInsnBytecodeOffset' is\n * equal to x, and 'reference' is of type {@link #FORWARD_REFERENCE_TYPE_SHORT} with value x + 1\n * (because the ifnull instruction uses a 2 bytes bytecode offset operand stored one byte after\n * the start of the instruction itself). For the default case of a lookupswitch instruction at\n * bytecode offset x, 'sourceInsnBytecodeOffset' is equal to x, and 'reference' is of type {@link\n * #FORWARD_REFERENCE_TYPE_WIDE} with value between x + 1 and x + 4 (because the lookupswitch\n * instruction uses a 4 bytes bytecode offset operand stored one to four bytes after the start of\n * the instruction itself).\n */\n private int[] forwardReferences;\n // -----------------------------------------------------------------------------------------------\n // Fields for the control flow and data flow graph analysis algorithms (used to compute the\n // maximum stack size or the stack map frames). A control flow graph contains one node per \"basic\n // block\", and one edge per \"jump\" from one basic block to another. Each node (i.e., each basic\n // block) is represented with the Label object that corresponds to the first instruction of this\n // basic block. Each node also stores the list of its successors in the graph, as a linked list of\n // Edge objects.\n //\n // The control flow analysis algorithms used to compute the maximum stack size or the stack map\n // frames are similar and use two steps. The first step, during the visit of each instruction,\n // builds information about the state of the local variables and the operand stack at the end of\n // each basic block, called the \"output frame\", relatively to the frame state at the\n // beginning of the basic block, which is called the \"input frame\", and which is unknown\n // during this step. The second step, in {@link MethodWriter#computeAllFrames} and {@link\n // MethodWriter#computeMaxStackAndLocal}, is a fix point algorithm\n // that computes information about the input frame of each basic block, from the input state of\n // the first basic block (known from the method signature), and by the using the previously\n // computed relative output frames.\n //\n // The algorithm used to compute the maximum stack size only computes the relative output and\n // absolute input stack heights, while the algorithm used to compute stack map frames computes\n // relative output frames and absolute input frames.\n /**\n * The number of elements in the input stack of the basic block corresponding to this label. This\n * field is computed in {@link MethodWriter#computeMaxStackAndLocal}.\n */\n short inputStackSize;\n /**\n * The number of elements in the output stack, at the end of the basic block corresponding to this\n * label. This field is only computed for basic blocks that end with a RET instruction.\n */\n short outputStackSize;\n /**\n * The maximum height reached by the output stack, relatively to the top of the input stack, in\n * the basic block corresponding to this label. This maximum is always positive or {@literal\n * null}.\n */\n short outputStackMax;\n /**\n * The id of the subroutine to which this basic block belongs, or 0. If the basic block belongs to\n * several subroutines, this is the id of the \"oldest\" subroutine that contains it (with the\n * convention that a subroutine calling another one is \"older\" than the callee). This field is\n * computed in {@link MethodWriter#computeMaxStackAndLocal}, if the method contains JSR\n * instructions.\n */\n short subroutineId;\n /**\n * The input and output stack map frames of the basic block corresponding to this label. This\n * field is only used when the {@link MethodWriter#COMPUTE_ALL_FRAMES} or {@link\n * MethodWriter#COMPUTE_INSERTED_FRAMES} option is used.\n */\n Frame frame;\n /**\n * The successor of this label, in the order they are visited in {@link MethodVisitor#visitLabel}.\n * This linked list does not include labels used for debug info only. If the {@link\n * MethodWriter#COMPUTE_ALL_FRAMES} or {@link MethodWriter#COMPUTE_INSERTED_FRAMES} option is used\n * then it does not contain either successive labels that denote the same bytecode offset (in this\n * case only the first label appears in this list).\n */\n Label nextBasicBlock;\n /**\n * The outgoing edges of the basic block corresponding to this label, in the control flow graph of\n * its method. These edges are stored in a linked list of {@link Edge} objects, linked to each\n * other by their {@link Edge#nextEdge} field.\n */\n Edge outgoingEdges;\n /**\n * The next element in the list of labels to which this label belongs, or {@literal null} if it\n * does not belong to any list. All lists of labels must end with the {@link #EMPTY_LIST}\n * sentinel, in order to ensure that this field is null if and only if this label does not belong\n * to a list of labels. Note that there can be several lists of labels at the same time, but that\n * a label can belong to at most one list at a time (unless some lists share a common tail, but\n * this is not used in practice).\n *\n *

      List of labels are used in {@link MethodWriter#computeAllFrames} and {@link\n * MethodWriter#computeMaxStackAndLocal} to compute stack map frames and the maximum stack size,\n * respectively, as well as in {@link #markSubroutine} and {@link #addSubroutineRetSuccessors} to\n * compute the basic blocks belonging to subroutines and their outgoing edges. Outside of these\n * methods, this field should be null (this property is a precondition and a postcondition of\n * these methods).\n */\n Label nextListElement;\n // -----------------------------------------------------------------------------------------------\n // Constructor and accessors\n // -----------------------------------------------------------------------------------------------\n\n /** Constructs a new label. */\n public Label() {\n // Nothing to do.\n }\n\n /**\n * Returns the bytecode offset corresponding to this label. This offset is computed from the start\n * of the method's bytecode. This method is intended for {@link Attribute} sub classes, and is\n * normally not needed by class generators or adapters.\n *\n * @return the bytecode offset corresponding to this label.\n * @throws IllegalStateException if this label is not resolved yet.\n */\n public int getOffset() {\n if ((flags & FLAG_RESOLVED) == 0) {\n throw new IllegalStateException(\"Label offset position has not been resolved yet\");\n }\n return bytecodeOffset;\n }\n\n /**\n * Returns the \"canonical\" {@link Label} instance corresponding to this label's bytecode offset,\n * if known, otherwise the label itself. The canonical instance is the first label (in the order\n * of their visit by {@link MethodVisitor#visitLabel}) corresponding to this bytecode offset. It\n * cannot be known for labels which have not been visited yet.\n *\n *

      This method should only be used when the {@link MethodWriter#COMPUTE_ALL_FRAMES} option\n * is used.\n *\n * @return the label itself if {@link #frame} is null, otherwise the Label's frame owner. This\n * corresponds to the \"canonical\" label instance described above thanks to the way the label\n * frame is set in {@link MethodWriter#visitLabel}.\n */\n final Label getCanonicalInstance() {\n return frame == null ? this : frame.owner;\n }\n // -----------------------------------------------------------------------------------------------\n // Methods to manage line numbers\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Adds a source line number corresponding to this label.\n *\n * @param lineNumber a source line number (which should be strictly positive).\n */\n final void addLineNumber(final int lineNumber) {\n if (this.lineNumber == 0) {\n this.lineNumber = (short) lineNumber;\n } else {\n if (otherLineNumbers == null) {\n otherLineNumbers = new int[LINE_NUMBERS_CAPACITY_INCREMENT];\n }\n int otherLineNumberIndex = ++otherLineNumbers[0];\n if (otherLineNumberIndex >= otherLineNumbers.length) {\n int[] newLineNumbers = new int[otherLineNumbers.length + LINE_NUMBERS_CAPACITY_INCREMENT];\n System.arraycopy(otherLineNumbers, 0, newLineNumbers, 0, otherLineNumbers.length);\n otherLineNumbers = newLineNumbers;\n }\n otherLineNumbers[otherLineNumberIndex] = lineNumber;\n }\n }\n\n /**\n * Makes the given visitor visit this label and its source line numbers, if applicable.\n *\n * @param methodVisitor a method visitor.\n * @param visitLineNumbers whether to visit of the label's source line numbers, if any.\n */\n final void accept(final MethodVisitor methodVisitor, final boolean visitLineNumbers) {\n methodVisitor.visitLabel(this);\n if (visitLineNumbers && lineNumber != 0) {\n methodVisitor.visitLineNumber(lineNumber & 0xFFFF, this);\n if (otherLineNumbers != null) {\n for (int i = 1; i <= otherLineNumbers[0]; ++i) {\n methodVisitor.visitLineNumber(otherLineNumbers[i], this);\n }\n }\n }\n }\n // -----------------------------------------------------------------------------------------------\n // Methods to compute offsets and to manage forward references\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Puts a reference to this label in the bytecode of a method. If the bytecode offset of the label\n * is known, the relative bytecode offset between the label and the instruction referencing it is\n * computed and written directly. Otherwise, a null relative offset is written and a new forward\n * reference is declared for this label.\n *\n * @param code the bytecode of the method. This is where the reference is appended.\n * @param sourceInsnBytecodeOffset the bytecode offset of the instruction that contains the\n * reference to be appended.\n * @param wideReference whether the reference must be stored in 4 bytes (instead of 2 bytes).\n */\n final void put(final ByteVector code, final int sourceInsnBytecodeOffset, final boolean wideReference) {\n if ((flags & FLAG_RESOLVED) == 0) {\n if (wideReference) {\n addForwardReference(sourceInsnBytecodeOffset, FORWARD_REFERENCE_TYPE_WIDE, code.length);\n code.putInt(-1);\n } else {\n addForwardReference(sourceInsnBytecodeOffset, FORWARD_REFERENCE_TYPE_SHORT, code.length);\n code.putShort(-1);\n }\n } else {\n if (wideReference) {\n code.putInt(bytecodeOffset - sourceInsnBytecodeOffset);\n } else {\n code.putShort(bytecodeOffset - sourceInsnBytecodeOffset);\n }\n }\n }\n\n /**\n * Adds a forward reference to this label. This method must be called only for a true forward\n * reference, i.e. only if this label is not resolved yet. For backward references, the relative\n * bytecode offset of the reference can be, and must be, computed and stored directly.\n *\n * @param sourceInsnBytecodeOffset the bytecode offset of the instruction that contains the\n * reference stored at referenceHandle.\n * @param referenceType either {@link #FORWARD_REFERENCE_TYPE_SHORT} or {@link\n * #FORWARD_REFERENCE_TYPE_WIDE}.\n * @param referenceHandle the offset in the bytecode where the forward reference value must be\n * stored.\n */\n private void addForwardReference(final int sourceInsnBytecodeOffset, final int referenceType, final int referenceHandle) {\n if (forwardReferences == null) {\n forwardReferences = new int[FORWARD_REFERENCES_CAPACITY_INCREMENT];\n }\n int lastElementIndex = forwardReferences[0];\n if (lastElementIndex + 2 >= forwardReferences.length) {\n int[] newValues = new int[forwardReferences.length + FORWARD_REFERENCES_CAPACITY_INCREMENT];\n System.arraycopy(forwardReferences, 0, newValues, 0, forwardReferences.length);\n forwardReferences = newValues;\n }\n forwardReferences[++lastElementIndex] = sourceInsnBytecodeOffset;\n forwardReferences[++lastElementIndex] = referenceType | referenceHandle;\n forwardReferences[0] = lastElementIndex;\n }\n\n /**\n * Sets the bytecode offset of this label to the given value and resolves the forward references\n * to this label, if any. This method must be called when this label is added to the bytecode of\n * the method, i.e. when its bytecode offset becomes known. This method fills in the blanks that\n * where left in the bytecode by each forward reference previously added to this label.\n *\n * @param code the bytecode of the method.\n * @param bytecodeOffset the bytecode offset of this label.\n * @return {@literal true} if a blank that was left for this label was too small to store the\n * offset. In such a case the corresponding jump instruction is replaced with an equivalent\n * ASM specific instruction using an unsigned two bytes offset. These ASM specific\n * instructions are later replaced with standard bytecode instructions with wider offsets (4\n * bytes instead of 2), in ClassReader.\n */\n final boolean resolve(final byte[] code, final int bytecodeOffset) {\n this.flags |= FLAG_RESOLVED;\n this.bytecodeOffset = bytecodeOffset;\n if (forwardReferences == null) {\n return false;\n }\n boolean hasAsmInstructions = false;\n for (int i = forwardReferences[0]; i > 0; i -= 2) {\n final int sourceInsnBytecodeOffset = forwardReferences[i - 1];\n final int reference = forwardReferences[i];\n final int relativeOffset = bytecodeOffset - sourceInsnBytecodeOffset;\n int handle = reference & FORWARD_REFERENCE_HANDLE_MASK;\n if ((reference & FORWARD_REFERENCE_TYPE_MASK) == FORWARD_REFERENCE_TYPE_SHORT) {\n if (relativeOffset < Short.MIN_VALUE || relativeOffset > Short.MAX_VALUE) {\n // Change the opcode of the jump instruction, in order to be able to find it later in\n // ClassReader. These ASM specific opcodes are similar to jump instruction opcodes, except\n // that the 2 bytes offset is unsigned (and can therefore represent values from 0 to\n // 65535, which is sufficient since the size of a method is limited to 65535 bytes).\n int opcode = code[sourceInsnBytecodeOffset] & 0xFF;\n if (opcode < Opcodes.IFNULL) {\n // Change IFEQ ... JSR to ASM_IFEQ ... ASM_JSR.\n code[sourceInsnBytecodeOffset] = (byte) (opcode + Constants.ASM_OPCODE_DELTA);\n } else {\n // Change IFNULL and IFNONNULL to ASM_IFNULL and ASM_IFNONNULL.\n code[sourceInsnBytecodeOffset] = (byte) (opcode + Constants.ASM_IFNULL_OPCODE_DELTA);\n }\n hasAsmInstructions = true;\n }\n code[handle++] = (byte) (relativeOffset >>> 8);\n code[handle] = (byte) relativeOffset;\n } else {\n code[handle++] = (byte) (relativeOffset >>> 24);\n code[handle++] = (byte) (relativeOffset >>> 16);\n code[handle++] = (byte) (relativeOffset >>> 8);\n code[handle] = (byte) relativeOffset;\n }\n }\n return hasAsmInstructions;\n }\n // -----------------------------------------------------------------------------------------------\n // Methods related to subroutines\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Finds the basic blocks that belong to the subroutine starting with the basic block\n * corresponding to this label, and marks these blocks as belonging to this subroutine. This\n * method follows the control flow graph to find all the blocks that are reachable from the\n * current basic block WITHOUT following any jsr target.\n *\n *

      Note: a precondition and postcondition of this method is that all labels must have a null\n * {@link #nextListElement}.\n *\n * @param subroutineId the id of the subroutine starting with the basic block corresponding to\n * this label.\n */\n final void markSubroutine(final short subroutineId) {\n // Data flow algorithm: put this basic block in a list of blocks to process (which are blocks\n // belonging to subroutine subroutineId) and, while there are blocks to process, remove one from\n // the list, mark it as belonging to the subroutine, and add its successor basic blocks in the\n // control flow graph to the list of blocks to process (if not already done).\n Label listOfBlocksToProcess = this;\n listOfBlocksToProcess.nextListElement = EMPTY_LIST;\n while (listOfBlocksToProcess != EMPTY_LIST) {\n // Remove a basic block from the list of blocks to process.\n Label basicBlock = listOfBlocksToProcess;\n listOfBlocksToProcess = listOfBlocksToProcess.nextListElement;\n basicBlock.nextListElement = null;\n // If it is not already marked as belonging to a subroutine, mark it as belonging to\n // subroutineId and add its successors to the list of blocks to process (unless already done).\n if (basicBlock.subroutineId == 0) {\n basicBlock.subroutineId = subroutineId;\n listOfBlocksToProcess = basicBlock.pushSuccessors(listOfBlocksToProcess);\n }\n }\n }\n\n /**\n * Finds the basic blocks that end a subroutine starting with the basic block corresponding to\n * this label and, for each one of them, adds an outgoing edge to the basic block following the\n * given subroutine call. In other words, completes the control flow graph by adding the edges\n * corresponding to the return from this subroutine, when called from the given caller basic\n * block.\n *\n *

      Note: a precondition and postcondition of this method is that all labels must have a null\n * {@link #nextListElement}.\n *\n * @param subroutineCaller a basic block that ends with a jsr to the basic block corresponding to\n * this label. This label is supposed to correspond to the start of a subroutine.\n */\n final void addSubroutineRetSuccessors(final Label subroutineCaller) {\n // Data flow algorithm: put this basic block in a list blocks to process (which are blocks\n // belonging to a subroutine starting with this label) and, while there are blocks to process,\n // remove one from the list, put it in a list of blocks that have been processed, add a return\n // edge to the successor of subroutineCaller if applicable, and add its successor basic blocks\n // in the control flow graph to the list of blocks to process (if not already done).\n Label listOfProcessedBlocks = EMPTY_LIST;\n Label listOfBlocksToProcess = this;\n listOfBlocksToProcess.nextListElement = EMPTY_LIST;\n while (listOfBlocksToProcess != EMPTY_LIST) {\n // Move a basic block from the list of blocks to process to the list of processed blocks.\n Label basicBlock = listOfBlocksToProcess;\n listOfBlocksToProcess = basicBlock.nextListElement;\n basicBlock.nextListElement = listOfProcessedBlocks;\n listOfProcessedBlocks = basicBlock;\n // Add an edge from this block to the successor of the caller basic block, if this block is\n // the end of a subroutine and if this block and subroutineCaller do not belong to the same\n // subroutine.\n if ((basicBlock.flags & FLAG_SUBROUTINE_END) != 0 && basicBlock.subroutineId != subroutineCaller.subroutineId) {\n basicBlock.outgoingEdges = new Edge(basicBlock.outputStackSize,\n // By construction, the first outgoing edge of a basic block that ends with a jsr\n // instruction leads to the jsr continuation block, i.e. where execution continues\n // when ret is called (see {@link #FLAG_SUBROUTINE_CALLER}).\n subroutineCaller.outgoingEdges.successor, basicBlock.outgoingEdges);\n }\n // Add its successors to the list of blocks to process. Note that {@link #pushSuccessors} does\n // not push basic blocks which are already in a list. Here this means either in the list of\n // blocks to process, or in the list of already processed blocks. This second list is\n // important to make sure we don't reprocess an already processed block.\n listOfBlocksToProcess = basicBlock.pushSuccessors(listOfBlocksToProcess);\n }\n // Reset the {@link #nextListElement} of all the basic blocks that have been processed to null,\n // so that this method can be called again with a different subroutine or subroutine caller.\n while (listOfProcessedBlocks != EMPTY_LIST) {\n Label newListOfProcessedBlocks = listOfProcessedBlocks.nextListElement;\n listOfProcessedBlocks.nextListElement = null;\n listOfProcessedBlocks = newListOfProcessedBlocks;\n }\n }\n\n /**\n * Adds the successors of this label in the method's control flow graph (except those\n * corresponding to a jsr target, and those already in a list of labels) to the given list of\n * blocks to process, and returns the new list.\n *\n * @param listOfLabelsToProcess a list of basic blocks to process, linked together with their\n * {@link #nextListElement} field.\n * @return the new list of blocks to process.\n */\n private Label pushSuccessors(final Label listOfLabelsToProcess) {\n Label newListOfLabelsToProcess = listOfLabelsToProcess;\n Edge outgoingEdge = outgoingEdges;\n while (outgoingEdge != null) {\n // By construction, the second outgoing edge of a basic block that ends with a jsr instruction\n // leads to the jsr target (see {@link #FLAG_SUBROUTINE_CALLER}).\n boolean isJsrTarget = (flags & Label.FLAG_SUBROUTINE_CALLER) != 0 && outgoingEdge == outgoingEdges.nextEdge;\n if (!isJsrTarget && outgoingEdge.successor.nextListElement == null) {\n // Add this successor to the list of blocks to process, if it does not already belong to a\n // list of labels.\n outgoingEdge.successor.nextListElement = newListOfLabelsToProcess;\n newListOfLabelsToProcess = outgoingEdge.successor;\n }\n outgoingEdge = outgoingEdge.nextEdge;\n }\n return newListOfLabelsToProcess;\n }\n // -----------------------------------------------------------------------------------------------\n // Overridden Object methods\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns a string representation of this label.\n *\n * @return a string representation of this label.\n */\n @Override\n public String toString() {\n return \"L\" + System.identityHashCode(this);\n }\n}\n", "file_name": "Label.java", "human_label": "Add the number of lines. ", "level": "class_runnable", "lineno": "296", "name": "addLineNumber", "oracle_context": "{ \"apis\" : \"[arraycopy]\", \"classes\" : \"[int[], otherLineNumbers]\", \"vars\" : \"[length, otherLineNumbers, LINE_NUMBERS_CAPACITY_INCREMENT]\" }", "package": "net.hasor.utils.asm", "project": "hasor-master" }, { "_id": "6367675a1a6d9265ec018010", "all_context": "{ \"class_level\" : \"import java.util.Collection;\\nimport java.util.HashSet;\\nimport java.util.LinkedHashSet;\\nimport java.util.Map;\\nimport java.util.NoSuchElementException;\\nimport java.util.Set;\\nimport org.jgrapht.Graph;\\nimport org.jgrapht.GraphTests;\\nimport org.jgrapht.Graphs;\\nimport org.jgrapht.util.CollectionUtil;\\nBucketList bucketList;\\nV current;\\nBucket head;\\nMap bucketMap;\\nBucket next;\\nBucket prev;\\nSet vertices;\\nLexBreadthFirstIterator(Graph graph);\\nnext();\\nisCrossComponentTraversal();\\nsetCrossComponentTraversal(boolean crossComponentTraversal);\\nadvance();\\ngetUnvisitedNeighbours(V vertex);\\nBucketList(Collection vertices);\\ncontainsBucketWith(V vertex);\\npoll();\\nupdateBuckets(Set vertices);\\nBucket(Collection vertices);\\nBucket(V vertex);\\nremoveVertex(V vertex);\\nremoveSelf();\\ninsertBefore(Bucket bucket);\\naddVertex(V vertex);\\nisEmpty();\\nhasNext();\\n\", \"repo_level\" : \"public interface Graph { Set getAllEdges(V sourceVertex,V targetVertex);\\n E getEdge(V sourceVertex,V targetVertex);\\n Supplier getVertexSupplier();\\n Supplier getEdgeSupplier();\\n E addEdge(V sourceVertex,V targetVertex);\\n boolean addEdge(V sourceVertex,V targetVertex,E e);\\n V addVertex();\\n boolean addVertex(V v);\\n boolean containsEdge(V sourceVertex,V targetVertex);\\n boolean containsEdge(E e);\\n boolean containsVertex(V v);\\n Set edgeSet();\\n int degreeOf(V vertex);\\n Set edgesOf(V vertex);\\n int inDegreeOf(V vertex);\\n Set incomingEdgesOf(V vertex);\\n int outDegreeOf(V vertex);\\n Set outgoingEdgesOf(V vertex);\\n boolean removeAllEdges(Collection edges);\\n Set removeAllEdges(V sourceVertex,V targetVertex);\\n boolean removeAllVertices(Collection vertices);\\n E removeEdge(V sourceVertex,V targetVertex);\\n boolean removeEdge(E e);\\n boolean removeVertex(V v);\\n Set vertexSet();\\n V getEdgeSource(E e);\\n V getEdgeTarget(E e);\\n GraphType getType();\\n double getEdgeWeight(E e);\\n void setEdgeWeight(E e,double weight);\\ndefault void setEdgeWeight(V sourceVertex,V targetVertex,double weight);\\ndefault GraphIterables iterables();\\n }\\npublic interface Graphs {static E addEdge(Graph g,V sourceVertex,V targetVertex,double weight);\\nstatic E addEdgeWithVertices(Graph g,V sourceVertex,V targetVertex);\\nstatic boolean addEdgeWithVertices(Graph targetGraph,Graph sourceGraph,E edge);\\nstatic E addEdgeWithVertices(Graph g,V sourceVertex,V targetVertex,double weight);\\nstatic boolean addGraph(Graph destination,Graph source);\\nstatic void addGraphReversed(Graph destination,Graph source);\\nstatic boolean addAllEdges(Graph destination,Graph source,Collection edges);\\nstatic boolean addAllVertices(Graph destination,Collection vertices);\\nstatic List neighborListOf(Graph g,V vertex);\\nstatic Set neighborSetOf(Graph g,V vertex);\\nstatic List predecessorListOf(Graph g,V vertex);\\nstatic List successorListOf(Graph g,V vertex);\\nstatic Graph undirectedGraph(Graph g);\\nstatic boolean testIncidence(Graph g,E e,V v);\\nstatic V getOppositeVertex(Graph g,E e,V v);\\nstatic boolean removeVertexAndPreserveConnectivity(Graph graph,V vertex);\\nstatic boolean removeVerticesAndPreserveConnectivity(Graph graph,Predicate predicate);\\nstatic boolean removeVertexAndPreserveConnectivity(Graph graph,Iterable vertices);\\nstatic void addOutgoingEdges(Graph graph,V source,Iterable targets);\\nstatic void addIncomingEdges(Graph graph,V target,Iterable sources);\\nstatic boolean vertexHasSuccessors(Graph graph,V vertex);\\nstatic boolean vertexHasPredecessors(Graph graph,V vertex);\\nstatic VertexToIntegerMapping getVertexToIntegerMapping(Graph graph);\\n }\\npublic interface CollectionUtil {static HashMap newHashMapWithExpectedSize(int expectedSize);\\nstatic LinkedHashMap newLinkedHashMapWithExpectedSize(int expectedSize);\\nstatic HashSet newHashSetWithExpectedSize(int expectedSize);\\nstatic LinkedHashSet newLinkedHashSetWithExpectedSize(int expectedSize);\\nstatic E getElement(Iterable iterable,int index);\\n }\\n\" }", "class_name": "LexBreadthFirstIterator", "code": "void removeSelf(){\n if (next != null) {\n next.prev=prev;\n }\n if (prev != null) {\n prev.next=next;\n }\n}\n", "docstring": "/** \n * Removes this bucket from the data structure.\n */\n", "end_lineno": "356", "file_content": "/*\n * (C) Copyright 2018-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.traverse;\n\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.LinkedHashSet;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.jgrapht.Graph;\nimport org.jgrapht.GraphTests;\nimport org.jgrapht.Graphs;\nimport org.jgrapht.util.CollectionUtil;\n\n/**\n * A lexicographical breadth-first iterator for an undirected graph.\n *

      \n * Every vertex has an implicit label (they aren't used explicitly in order to reduce time and\n * memory complexity). When some vertex is returned by this iterator, its index is the number of\n * vertices in this graph minus number of already returned vertices. For a given vertex v its label\n * is a concatenation of indices of already returned vertices, that were also its neighbours, with\n * some separator between them. For example, 7#4#3 is a valid vertex label.\n *

      \n * Iterator chooses vertex with lexicographically largest label and returns it. It breaks ties\n * arbitrarily. For more information on lexicographical BFS see the following article: Corneil D.G.\n * (2004) \n * Lexicographic Breadth First Search – A Survey. In: Hromkovič J., Nagl M., Westfechtel\n * B. (eds) Graph-Theoretic Concepts in Computer Science. WG 2004. Lecture Notes in Computer\n * Science, vol 3353. Springer, Berlin, Heidelberg; and the following\n * paper:CS 762:\n * Graph-theoretic algorithms. Lecture notes of a graduate course. University of Waterloo.\n *

      \n * For this iterator to work correctly the graph must not be modified during iteration. Currently\n * there are no means to ensure that, nor to fail-fast. The results of such modifications are\n * undefined.\n *

      \n * Note: only vertex events are fired by this iterator.\n *\n * @param the graph vertex type.\n * @param the graph edge type.\n * @author Timofey Chudakov\n */\npublic class LexBreadthFirstIterator\n extends\n AbstractGraphIterator\n{\n\n /**\n * Reference to the {@code BucketList} that contains unvisited vertices.\n */\n private BucketList bucketList;\n\n /**\n * Contains current vertex of the {@code graph}.\n */\n private V current;\n\n /**\n * Creates new lexicographical breadth-first iterator for {@code graph}.\n *\n * @param graph the graph to be iterated.\n */\n public LexBreadthFirstIterator(Graph graph)\n {\n super(graph);\n GraphTests.requireUndirected(graph);\n bucketList = new BucketList(graph.vertexSet());\n }\n\n /**\n * Checks whether there exist unvisited vertices.\n *\n * @return true if there exist unvisited vertices.\n */\n @Override\n public boolean hasNext()\n {\n if (current != null) {\n return true;\n }\n current = advance();\n if (current != null && nListeners != 0) {\n fireVertexTraversed(createVertexTraversalEvent(current));\n }\n return current != null;\n }\n\n /**\n * Returns the next vertex in the ordering.\n *\n * @return the next vertex in the ordering.\n */\n @Override\n public V next()\n {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n V result = current;\n current = null;\n if (nListeners != 0) {\n fireVertexFinished(createVertexTraversalEvent(result));\n }\n return result;\n }\n\n /**\n * {@inheritDoc}\n *

      \n * Always returns true since this iterator doesn't care about connected components.\n */\n @Override\n public boolean isCrossComponentTraversal()\n {\n return true;\n }\n\n /**\n * {@inheritDoc}\n *

      \n * Trying to disable the cross components nature of this iterator will result into throwing a\n * {@link IllegalArgumentException}.\n */\n @Override\n public void setCrossComponentTraversal(boolean crossComponentTraversal)\n {\n if (!crossComponentTraversal) {\n throw new IllegalArgumentException(\"Iterator is always cross-component\");\n }\n }\n\n /**\n * Retrieves vertex from the {@code bucketList} and returns it.\n *\n * @return the vertex retrieved from the {@code bucketList}.\n */\n private V advance()\n {\n V vertex = bucketList.poll();\n if (vertex != null) {\n bucketList.updateBuckets(getUnvisitedNeighbours(vertex));\n }\n return vertex;\n }\n\n /**\n * Computes and returns neighbours of {@code vertex} which haven't been visited by this\n * iterator.\n *\n * @param vertex the vertex, whose neighbours are being explored.\n * @return neighbours of {@code vertex} which have yet to be visited by this iterator.\n */\n private Set getUnvisitedNeighbours(V vertex)\n {\n Set unmapped = new LinkedHashSet<>();\n Set edges = graph.edgesOf(vertex);\n for (E edge : edges) {\n V oppositeVertex = Graphs.getOppositeVertex(graph, edge, vertex);\n if (bucketList.containsBucketWith(oppositeVertex)) {\n unmapped.add(oppositeVertex);\n }\n }\n return unmapped;\n }\n\n /**\n * Data structure for performing lexicographical breadth-first search. Allows to add and\n * retrieve vertices from buckets, update their buckets after a new vertex has been added to the\n * LexBFS order. Labels aren't used explicitly, which results in time and space optimization.\n *\n * @author Timofey Chudakov\n */\n class BucketList\n {\n /**\n * Bucket with the vertices that have lexicographically largest label.\n */\n private Bucket head;\n /**\n * Map for mapping vertices to buckets they are currently in. Is used for finding the bucket\n * of the vertex in constant time.\n */\n private Map bucketMap;\n\n /**\n * Creates a {@code BucketList} with a single bucket and all specified {@code vertices} in\n * it.\n *\n * @param vertices the vertices of the graph, that should be stored in the {@code head}\n * bucket.\n */\n BucketList(Collection vertices)\n {\n head = new Bucket(vertices);\n bucketMap = CollectionUtil.newHashMapWithExpectedSize(vertices.size());\n for (V vertex : vertices) {\n bucketMap.put(vertex, head);\n }\n }\n\n /**\n * Checks whether there exists a bucket with the specified {@code vertex}.\n *\n * @param vertex the vertex whose presence in some {@code Bucket} in this {@code BucketList}\n * is checked.\n * @return true if there exists a bucket with {@code vertex} in it, otherwise\n * false.\n */\n boolean containsBucketWith(V vertex)\n {\n return bucketMap.containsKey(vertex);\n }\n\n /**\n * Retrieves element from the head bucket by invoking {@link Bucket#poll()} or null if this\n * {@code BucketList} is empty.\n *

      \n * Removes the head bucket if it becomes empty after the operation.\n *\n * @return vertex returned by {@link Bucket#poll()} invoked on head bucket or null if this\n * {@code BucketList} is empty.\n */\n V poll()\n {\n if (bucketMap.size() > 0) {\n V res = head.poll();\n bucketMap.remove(res);\n if (head.isEmpty()) {\n head = head.next;\n if (head != null) {\n head.prev = null;\n }\n }\n return res;\n } else {\n return null;\n }\n }\n\n /**\n * For every bucket B in this {@code BucketList}, which contains vertices from the set\n * {@code\n * vertices}, creates a new {@code Bucket} B' and moves vertices from B to B' according to\n * the following rule: $B' = B\\cap vertices$ and $B = B\\backslash B'$. For every such\n * {@code Bucket} B only one {@code Bucket} B' is created. If some bucket B becomes empty\n * after this operation, it is removed from the data structure.\n *\n * @param vertices the vertices, that should be moved to new buckets.\n */\n void updateBuckets(Set vertices)\n {\n Set visitedBuckets = new HashSet<>();\n for (V vertex : vertices) {\n Bucket bucket = bucketMap.get(vertex);\n if (visitedBuckets.contains(bucket)) {\n bucket.prev.addVertex(vertex);\n bucketMap.put(vertex, bucket.prev);\n } else {\n visitedBuckets.add(bucket);\n Bucket newBucket = new Bucket(vertex);\n newBucket.insertBefore(bucket);\n bucketMap.put(vertex, newBucket);\n if (head == bucket) {\n head = newBucket;\n }\n }\n bucket.removeVertex(vertex);\n if (bucket.isEmpty()) {\n visitedBuckets.remove(bucket);\n bucket.removeSelf();\n }\n }\n }\n\n /**\n * Plays the role of the container of vertices. All vertices stored in a bucket have\n * identical label. Labels aren't used explicitly.\n *

      \n * Encapsulates operations of addition and removal of vertices from the bucket and removal\n * of a bucket from the data structure.\n */\n private class Bucket\n {\n /**\n * Reference of the bucket with lexicographically smaller label.\n */\n private Bucket next;\n /**\n * Reference of the bucket with lexicographically larger label.\n */\n private Bucket prev;\n /**\n * Set of vertices currently stored in this bucket.\n */\n private Set vertices;\n\n /**\n * Creates a new bucket with all {@code vertices} stored in it.\n *\n * @param vertices vertices to store in this bucket.\n */\n Bucket(Collection vertices)\n {\n this.vertices = new LinkedHashSet<>(vertices);\n }\n\n /**\n * Creates a new Bucket with a single {@code vertex} in it.\n *\n * @param vertex the vertex to store in this bucket.\n */\n Bucket(V vertex)\n {\n this.vertices = new LinkedHashSet<>();\n vertices.add(vertex);\n }\n\n /**\n * Removes the {@code vertex} from this bucket.\n *\n * @param vertex the vertex to remove.\n */\n void removeVertex(V vertex)\n {\n vertices.remove(vertex);\n }\n\n /**\n * Removes this bucket from the data structure.\n */\n void removeSelf()\n {\n if (next != null) {\n next.prev = prev;\n }\n if (prev != null) {\n prev.next = next;\n }\n }\n\n /**\n * Inserts this bucket in the data structure before the {@code bucket}.\n *\n * @param bucket the bucket, that will be the next to this bucket.\n */\n void insertBefore(Bucket bucket)\n {\n this.next = bucket;\n if (bucket != null) {\n this.prev = bucket.prev;\n if (bucket.prev != null) {\n bucket.prev.next = this;\n }\n bucket.prev = this;\n } else {\n this.prev = null;\n }\n }\n\n /**\n * Adds the {@code vertex} to this bucket.\n *\n * @param vertex the vertex to add.\n */\n void addVertex(V vertex)\n {\n vertices.add(vertex);\n }\n\n /**\n * Retrieves one vertex from this bucket.\n *\n * @return vertex, that was removed from this bucket, null if the bucket was empty.\n */\n V poll()\n {\n if (vertices.isEmpty()) {\n return null;\n } else {\n V vertex = vertices.iterator().next();\n vertices.remove(vertex);\n return vertex;\n }\n }\n\n /**\n * Checks whether this bucket is empty.\n *\n * @return true if this bucket doesn't contain any elements, otherwise false.\n */\n boolean isEmpty()\n {\n return vertices.size() == 0;\n }\n }\n }\n}\n", "file_name": "LexBreadthFirstIterator.java", "human_label": "Remove the doubly linked list node that call the function.", "level": "class_runnable", "lineno": "345", "name": "removeSelf", "oracle_context": "{ \"apis\" : \"[next]\", \"classes\" : \"[next, prev]\", \"vars\" : \"[prev, next]\" }", "package": "org.jgrapht.traverse", "project": "jgrapht-master" }, { "_id": "636767dd1a6d9265ec0186f3", "all_context": "{ \"class_level\" : \"import java.util.ArrayList;\\nimport java.util.List;\\nimport lombok.Getter;\\nimport org.apache.skywalking.oap.server.library.util.CollectionUtils;\\nList indices;\\nString[] columns;\\nappendIndex(MultiColumnsIndex index);\\nMultiColumnsIndex(String mainColumn,String[] withColumns);\\n\", \"repo_level\" : \"public interface CollectionUtils {static boolean isEmpty(Map map);\\nstatic boolean isEmpty(List list);\\nstatic boolean isEmpty(Set set);\\nstatic boolean isNotEmpty(List list);\\nstatic boolean isNotEmpty(Set set);\\nstatic boolean isNotEmpty(Map map);\\nstatic boolean isNotEmpty(T[] array);\\nstatic boolean isEmpty(byte[] array);\\nstatic boolean isNotEmpty(byte[] array);\\n }\\n\" }", "class_name": "SQLDatabaseExtension$MultiColumnsIndex", "code": "public void overrideName(String oldName,String newName){\n for (int i=0; i < columns.length; i++) {\n if (columns[i].equals(oldName)) {\n columns[i]=newName;\n }\n }\n}\n", "docstring": "/** \n * Keep the same name replacement as {@link ColumnName#overrideName(String,String)}\n * @param oldName to be replaced.\n * @param newName to use in the storage level.\n */\n", "end_lineno": "68", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.core.storage.model;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport lombok.Getter;\nimport org.apache.skywalking.oap.server.library.util.CollectionUtils;\n\n/**\n * @since 9.0.0\n */\n@Getter\npublic class SQLDatabaseExtension {\n private final List indices = new ArrayList<>(5);\n\n public void appendIndex(MultiColumnsIndex index) {\n indices.add(index);\n }\n\n /**\n * The multiple columns index if the storage could support this mode. Many NO-SQL support one column index only, in that\n * case, this could be ignored in the implementation level.\n */\n @Getter\n public static class MultiColumnsIndex {\n private String[] columns;\n\n public MultiColumnsIndex(String mainColumn, final String[] withColumns) {\n if (CollectionUtils.isNotEmpty(withColumns)) {\n columns = new String[withColumns.length + 1];\n columns[0] = mainColumn;\n System.arraycopy(withColumns, 0, columns, 1, withColumns.length);\n } else {\n throw new IllegalArgumentException(\"ExtraQueryIndex required withColumns as a not empty list.\");\n }\n\n }\n\n /**\n * Keep the same name replacement as {@link ColumnName#overrideName(String, String)}\n *\n * @param oldName to be replaced.\n * @param newName to use in the storage level.\n */\n public void overrideName(String oldName, String newName) {\n for (int i = 0; i < columns.length; i++) {\n if (columns[i].equals(oldName)) {\n columns[i] = newName;\n }\n }\n }\n }\n}\n", "file_name": "SQLDatabaseExtension.java", "human_label": "Change the elements whose values are oldName to newName in column", "level": "self_contained", "lineno": "56", "name": "overrideName", "oracle_context": "{ \"apis\" : \"[equals]\", \"classes\" : \"[columns]\", \"vars\" : \"[length, columns]\" }", "package": "org.apache.skywalking.oap.server.core.storage.model", "project": "skywalking-master" }, { "_id": "636767631a6d9265ec018171", "all_context": "{ \"class_level\" : \"import org.jgrapht.alg.util.*;\\nimport java.util.*;\\nimport java.util.function.*;\\nListNodeImpl head;\\nint size;\\nint nextIndex;\\nListNodeImpl next;\\nListNodeImpl last;\\nint expectedModCount;\\nV value;\\nDoublyLinkedList list;\\nListNodeImpl next;\\nListNodeImpl prev;\\ntail();\\nsize();\\nclear();\\naddListNode(ListNodeImpl node);\\nmoveAllListNodes(DoublyLinkedList list);\\nremoveListNode(ListNodeImpl node);\\nlink(ListNodeImpl predecessor,ListNodeImpl successor);\\nlinkBefore(ListNodeImpl node,ListNodeImpl successor);\\nlinkLast(ListNodeImpl node);\\nlinkListIntoThisBefore(int index,DoublyLinkedList list);\\nunlink(ListNodeImpl node);\\naddNode(int index,ListNode node);\\naddNodeFirst(ListNode node);\\naddNodeLast(ListNode node);\\naddNodeBefore(ListNode node,ListNode successor);\\ngetFirstNode();\\ngetLastNode();\\ngetNode(int index);\\ngetNodeAt(int index);\\nindexOfNode(ListNode node);\\ncontainsNode(ListNode node);\\nremoveNode(ListNode node);\\nnodeOf(Object element);\\nlastNodeOf(Object element);\\nsearchNode(Supplier first,UnaryOperator next,Object element);\\naddElementFirst(E element);\\naddElementLast(E element);\\naddElementBeforeNode(ListNode successor,E element);\\nadd(int index,E element);\\nget(int index);\\nremove(int index);\\naddFirst(E e);\\naddLast(E e);\\nofferFirst(E e);\\nofferLast(E e);\\nremoveFirst();\\nremoveLast();\\npollFirst();\\npollLast();\\ngetFirst();\\ngetLast();\\npeekFirst();\\npeekLast();\\nremoveFirstOccurrence(Object o);\\nremoveLastOccurrence(Object o);\\noffer(E e);\\nremove();\\npoll();\\nelement();\\npeek();\\npush(E e);\\npop();\\ninvert();\\nmoveFrom(int index,DoublyLinkedList movedList);\\nappend(DoublyLinkedList movedList);\\nprepend(DoublyLinkedList movedList);\\ncircularIterator(E firstElement);\\nreverseCircularIterator(E firstElement);\\ndescendingIterator();\\niterator();\\nlistIterator();\\nlistIterator(int index);\\nlistIterator(E element);\\nnext();\\nnextNode();\\nprevious();\\npreviousNode();\\nListNodeIteratorImpl(int startIndex);\\nListNodeIteratorImpl(int startIndex,ListNodeImpl startNode);\\nhasNext();\\nhasPrevious();\\nnextIndex();\\npreviousIndex();\\nadd(E e);\\nset(E e);\\ncheckForComodification();\\nreverseIterator(ListNodeIterator listIterator);\\ngetValue();\\ngetNext();\\ngetPrev();\\nListNodeImpl(V value);\\ntoString();\\nisEmpty();\\n\", \"repo_level\" : \"\" }", "class_name": "DoublyLinkedList", "code": "private boolean unlink(ListNodeImpl node){\n ListNodeImpl prev=node.prev;\n ListNodeImpl next=node.next;\n if (removeListNode(node)) {\n if (size == 0) {\n head=null;\n }\n else {\n link(prev,next);\n if (head == node) {\n head=next;\n }\n }\n return true;\n }\n return false;\n}\n", "docstring": "/** \n * Remove the non null {@code node} from the list. \n */\n", "end_lineno": "259", "file_content": "/*\n * (C) Copyright 2018-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.util;\n\nimport org.jgrapht.alg.util.*;\n\nimport java.util.*;\nimport java.util.function.*;\n\n/**\n * {@code DoublyLinkedList} implements a doubly linked {@link List} data structure, that exposes its\n * {@link ListNode ListNodes} where the data is stored in.\n *

      \n * An element holding {@code ListNode} can be removed or added to a {@code DoublyLinkedList} in\n * constant time O(1). Other methods that operate on {@code ListNodes} directly also have constant\n * runtime. This is also the case for methods that operate on the first(head) and last(tail) node or\n * element. Random access methods have a runtime O(n) that is linearly dependent on the size of the\n * {@code DoublyLinkedList}.\n *

      \n *

      \n * A {@code DoublyLinkedList} supports {@code null} elements but does not support\n * {@code null ListNodes}. This class is not thread safe and needs to be synchronized externally if\n * modified by concurrent threads.\n *

      \n *

      \n * The iterators over this list have a fail-fast behavior meaning that they throw a\n * {@link ConcurrentModificationException} after they detect a structural modification of the list,\n * that they're not responsible for.\n *

      \n *

      \n * This class is similar to {@link LinkedList}. The general difference is that the {@code ListNodes}\n * of this {@code List} are accessible and can be removed or added directly. To ensure the integrity\n * of the {@code List} nodes of this List have a reference to the List they belong to. This\n * increases the memory occupied by this list implementation compared to {@code LinkedList} for the\n * same elements. Instances of {@code LinkedList.Node} have three references each (the element, next\n * and previous), instances of {@code DoublyLinkedList.ListNode} have four (the element, next,\n * previous and the list).\n *

      \n *\n * @param the list element type\n * @author Timofey Chudakov\n * @author Hannes Wellmann\n */\npublic class DoublyLinkedList\n extends\n AbstractSequentialList\n implements\n Deque\n{\n /** The first element of the list, {@code null} if this list is empty. */\n private ListNodeImpl head = null;\n private int size;\n\n private ListNodeImpl tail()\n {\n return head.prev;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean isEmpty()\n {\n return head == null;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int size()\n {\n return size;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void clear()\n {\n if (!isEmpty()) {\n ListNodeImpl node = head;\n do {\n ListNodeImpl next = node.next;\n boolean removed = removeListNode(node); // clears all links of removed node\n assert removed;\n node = next;\n } while (node != head);\n\n head = null;\n assert size == 0;\n }\n }\n\n // internal modification methods\n\n /**\n * Adds the given {@link ListNode} to this {@code List}.\n *

      \n * Sets the {@code list} reference of {@code node} to this list, increases this lists\n * {@code size} and {@code modcount} by one.\n *

      \n * \n * @param node the node to add to this list\n * @throws IllegalArgumentException if {@code node} is already contained in this or another\n * {@code DoublyLinkedList}\n */\n private void addListNode(ListNodeImpl node)\n { // call this before any modification of this list is done\n if (node.list != null) {\n String list = (node.list == this) ? \"this\" : \"other\";\n throw new IllegalArgumentException(\n \"Node <\" + node + \"> already contained in \" + list + \" list\");\n }\n node.list = this;\n size++;\n modCount++;\n }\n\n /**\n * Atomically moves all {@link ListNode ListNodes} from {@code list} to this list as if each\n * node was removed with {@link #removeListNode(ListNodeImpl)} from {@code list} and\n * subsequently added to this list by {@link #addListNode(ListNodeImpl)}.\n */\n private void moveAllListNodes(DoublyLinkedList list)\n { // call this before any modification of this list is done\n\n for (ListNodeIteratorImpl it = list.new ListNodeIteratorImpl(0); it.hasNext();) {\n ListNodeImpl node = it.nextNode();\n assert node.list == list;\n node.list = this;\n }\n size += list.size;\n list.size = 0;\n modCount++;\n list.modCount++;\n }\n\n /**\n * Removes the given {@link ListNode} from this {@code List}, if it is contained in this\n * {@code List}.\n *

      \n * If {@code node} is contained in this list, sets the {@code list}, {@code next} and\n * {@code prev} reference of {@code node} to {@code null} decreases this list's {@code size} and\n * increases the {@code modcount} by one.\n *

      \n * \n * @param node the node to remove from this list\n * @return true if {@code node} was removed from this list, else false\n */\n private boolean removeListNode(ListNodeImpl node)\n { // call this before any modification of this list is done\n if (node.list == this) {\n\n node.list = null;\n node.next = null;\n node.prev = null;\n\n size--;\n modCount++;\n return true;\n }\n return false;\n }\n\n /**\n * Establishes the links between the given {@link ListNodeImpl nodes} in such a way that the\n * {@code predecessor} is linked before the {@code successor}.\n * \n * @param predecessor the first node linked before the other\n * @param successor the second node linked after the other\n */\n private void link(ListNodeImpl predecessor, ListNodeImpl successor)\n {\n predecessor.next = successor;\n successor.prev = predecessor;\n }\n\n /** Insert non null {@code node} before non null {@code successor} into the list. */\n private void linkBefore(ListNodeImpl node, ListNodeImpl successor)\n {\n addListNode(node);\n link(successor.prev, node);\n link(node, successor);\n }\n\n /** Insert non null {@code node} as last node into the list. */\n private void linkLast(ListNodeImpl node)\n {\n if (isEmpty()) { // node will be the first and only one\n addListNode(node);\n link(node, node); // self link\n head = node;\n } else {\n linkBefore(node, head);\n }\n }\n\n /** Insert non null {@code list} before node at {@code index} into the list. */\n private void linkListIntoThisBefore(int index, DoublyLinkedList list)\n {\n int previousSize = size;\n moveAllListNodes(list);\n\n // link list's node into this list\n if (previousSize == 0) {\n head = list.head; // head and tail already linked together\n } else {\n ListNodeImpl refNode = (index == previousSize) ? head : getNodeAt(index);\n\n ListNodeImpl listTail = list.tail();\n link(refNode.prev, list.head); // changes list.tail()\n link(listTail, refNode);\n\n if (index == 0) {\n head = list.head;\n }\n }\n // clear list but do not call list.clear(), since their nodes are still used\n list.head = null;\n }\n\n /** Remove the non null {@code node} from the list. */\n private boolean unlink(ListNodeImpl node)\n {\n ListNodeImpl prev = node.prev;\n ListNodeImpl next = node.next;\n if (removeListNode(node)) { // clears prev and next of node\n if (size == 0) {\n head = null;\n } else {\n // list is circular, don't have to worry about null values\n link(prev, next);\n\n if (head == node) {\n head = next;\n }\n }\n return true;\n }\n return false;\n }\n\n // ----------------------------------------------------------------------------\n // public modification and access methods\n\n // ListNode methods:\n // Base methods to access, add and remove nodes to/from this list.\n // Used by all public methods if possible\n\n /**\n * Inserts the specified {@link ListNode node} at the specified position in this list.\n *

      \n * This method has a linear runtime complexity O(n) that depends linearly on the distance of the\n * index to the nearest end. Adding {@code node} as first or last takes only constant time O(1).\n *

      \n * \n * @param index index at which the specified {@code node} is to be inserted\n * @param node the node to add\n * @throws IndexOutOfBoundsException if the index is out of range\n * ({@code index < 0 || index > size()})\n * @throws IllegalArgumentException if {@code node} is already part of this or another\n * {@code DoublyLinkedList}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public void addNode(int index, ListNode node)\n {\n ListNodeImpl nodeImpl = (ListNodeImpl) node;\n if (index == size) { // also true if this is empty\n linkLast(nodeImpl);\n } else {\n ListNodeImpl successor = index == 0 ? head : getNodeAt(index);\n linkBefore(nodeImpl, successor);\n if (head == successor) {\n head = nodeImpl;\n }\n }\n }\n\n /**\n * Inserts the specified {@link ListNode node} at the front of this list.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n * \n * @param node the node to add\n * @throws IllegalArgumentException if {@code node} is already part of this or another\n * {@code DoublyLinkedList}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public void addNodeFirst(ListNode node)\n {\n addNode(0, node);\n }\n\n /**\n * Inserts the specified {@link ListNode node} at the end of this list.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n * \n * @param node the node to add\n * @throws IllegalArgumentException if {@code node} is already part of this or another\n * {@code DoublyLinkedList}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public void addNodeLast(ListNode node)\n {\n addNode(size, node);\n }\n\n /**\n * Inserts the specified {@link ListNode node} before the specified {@code successor} in this\n * list.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n * \n * @param node the node to add\n * @param successor {@code ListNode} before which the {@code node} is inserted\n * @throws IllegalArgumentException if {@code node} is already contained in this or another\n * {@code DoublyLinkedList} or {@code successor} is not contained in this list\n * @throws NullPointerException if {@code successor} or {@code node} is {@code null}\n */\n public void addNodeBefore(ListNode node, ListNode successor)\n {\n ListNodeImpl successorImpl = (ListNodeImpl) successor;\n ListNodeImpl nodeImpl = (ListNodeImpl) node;\n\n if (successorImpl.list != this) {\n throw new IllegalArgumentException(\"Node <\" + successorImpl + \"> not in this list\");\n }\n linkBefore(nodeImpl, successorImpl);\n if (head == successorImpl) {\n head = nodeImpl;\n }\n }\n\n /**\n * Returns the first {@link ListNode node} of this list.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n * \n * @return the first {@code ListNode} of this list\n * @throws NoSuchElementException if this list is empty\n */\n public ListNode getFirstNode()\n {\n if (isEmpty()) {\n throw new NoSuchElementException();\n }\n return head;\n }\n\n /**\n * Returns the last {@link ListNode node} of this list.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n * \n * @return the last {@code ListNode} of this list\n * @throws NoSuchElementException if this list is empty\n */\n public ListNode getLastNode()\n {\n if (isEmpty()) {\n throw new NoSuchElementException();\n }\n return tail();\n }\n\n /**\n * Returns the {@link ListNode node} at the specified position in this list.\n *

      \n * This method has linear runtime complexity O(n).\n *

      \n * \n * @param index index of the {@code ListNode} to return\n * @return the {@code ListNode} at the specified position in this list\n * @throws IndexOutOfBoundsException if the index is out of range\n * ({@code index < 0 || index >= size()})\n */\n public ListNode getNode(int index)\n {\n return getNodeAt(index);\n }\n\n /**\n * Returns the {@link ListNodeImpl node} at the specified position in this list.\n * \n * @param index index of the {@code ListNodeImpl} to return\n * @return the {@code ListNode} at the specified position in this list\n * @throws IndexOutOfBoundsException if the index is out of range\n * ({@code index < 0 || index >= size()})\n */\n private ListNodeImpl getNodeAt(int index)\n {\n if (index < 0 || size <= index) {\n throw new IndexOutOfBoundsException(\"Index: \" + index);\n }\n ListNodeImpl node;\n if (index < size / 2) {\n node = head;\n for (int i = 0; i < index; i++) {\n node = node.next;\n }\n } else {\n node = tail();\n for (int i = size - 1; index < i; i--) {\n node = node.prev;\n }\n }\n return node;\n }\n\n /**\n * Returns the index of the specified {@link ListNode node} in this list, or -1 if this list\n * does not contain the {@code node}.\n *

      \n * More formally, returns the index {@code i} such that {@code node == getNode(i)}, or -1 if\n * there is no such index. Because a {@code ListNode} is contained in at most one list exactly\n * once, the returned index (if not -1) is the only occurrence of that {@code node}.\n *

      \n *

      \n * This method has linear runtime complexity O(n) to find {@code node} but returns in constant\n * time O(1) if {@code node} is not {@link #containsNode(ListNode) contained} in this list.\n *

      \n * \n * @param node the node to search for\n * @return the index of the specified {@code node} in this list, or -1 if this list does not\n * contain {@code node}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public int indexOfNode(ListNode node)\n {\n if (!containsNode(node)) {\n return -1;\n }\n ListNodeImpl current = head;\n for (int i = 0; i < size; i++) {\n if (current == node) {\n return i;\n }\n current = current.next;\n }\n // should never happen:\n throw new IllegalStateException(\"Node contained in list not found: \" + node);\n }\n\n /**\n * Returns true if this {@code DoublyLinkedList} contains the specified {@link ListNode}.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n * \n * @param node the node whose presence in this {@code DoublyLinkedList} is to be tested\n * @return true if this {@code DoublyLinkedList} contains the {@link ListNode}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public boolean containsNode(ListNode node)\n {\n return ((ListNodeImpl) node).list == this;\n }\n\n /**\n * Removes the {@link ListNode node} from this list. Returns true if {@code node} was in this\n * list and is now removed. If {@code node} is not contained in this list, the list is left\n * unchanged.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n *\n * @param node the node to remove from this list\n * @return true if node was removed from this list\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public boolean removeNode(ListNode node)\n {\n return unlink((ListNodeImpl) node);\n }\n\n /**\n * Returns the first {@link ListNode node} holding the specified {@code element} in this list.\n * More formally, returns the first {@code ListNode} such that\n * {@code Objects.equals(element, node.getValue())}, or {@code null} if there is no such node.\n *

      \n * This method has linear runtime complexity O(n).\n *

      \n * \n * @param element the element whose {@code ListNode} is to return\n * @return the first {@code ListNode} holding the {@code element} or null if no node was found\n */\n public ListNode nodeOf(Object element)\n {\n return searchNode(() -> head, n -> n.next, element).getFirst();\n }\n\n /**\n * Returns the last {@link ListNode node} holding the specified {@code element} in this list.\n * More formally, returns the last {@code ListNode} such that\n * {@code Objects.equals(element, node.getValue())}, or {@code null} if there is no such node.\n *

      \n * This method has linear runtime complexity O(n).\n *

      \n * \n * @param element the element whose {@code ListNode} is to return\n * @return the last {@code ListNode} holding the {@code element} or null if no node was found\n */\n public ListNode lastNodeOf(Object element)\n {\n return searchNode(this::tail, n -> n.prev, element).getFirst();\n }\n\n /**\n * Returns a {@link Pair} of the first encountered {@link ListNode} in this list, whose\n * {@code value} is equal to the given {@code element}, and its index. Or if this list does not\n * contain such node a Pair of {@code null} and {@code -1};\n *

      \n * The search starts at the node supplied by {@code first} and advances in the direction induced\n * by the specified {@code next} operator.\n *

      \n * \n * @param first supplier of the first node to check if this list is not empty\n * @param next {@code Function} to get from the current node the next node to check\n * @param element the element for that the first node with equal value is searched.\n * @return a {@link Pair} of the first encountered {@code ListNode} holding a {@code value}\n * equal to {@code element} and its index, or if no such node was found a\n * {@code Pair.of(null, -1)}\n */\n private Pair, Integer> searchNode(\n Supplier> first, UnaryOperator> next, Object element)\n {\n if (!isEmpty()) {\n int index = 0;\n ListNodeImpl firstNode = first.get();\n ListNodeImpl node = firstNode;\n do {\n if (Objects.equals(node.value, element)) {\n return Pair.of(node, index);\n }\n index++;\n node = next.apply(node);\n } while (node != firstNode);\n }\n return Pair.of(null, -1);\n }\n\n /**\n * Inserts the specified element at the front of this list. Returns the {@link ListNode}\n * allocated to store the {@code value}. The returned {@code ListNode} is the new head of the\n * list.\n *

      \n * This method is equivalent to {@link #addFirst(Object)} but returns the allocated\n * {@code ListNode}.\n *

      \n * \n * @param element the element to add\n * @return the {@code ListNode} allocated to store the {@code value}\n */\n public ListNode addElementFirst(E element)\n {\n ListNode node = new ListNodeImpl<>(element);\n addNode(0, node);\n return node;\n }\n\n /**\n * Inserts the specified element at the end of this list. Returns the {@link ListNode} allocated\n * to store the {@code value}. The returned {@code ListNode} is the new tail of the list.\n *

      \n * This method is equivalent to {@link #addLast(Object)} but returns the allocated\n * {@code ListNode}.\n *

      \n * \n * @param element the element to add\n * @return the {@code ListNode} allocated to store the {@code value}\n */\n public ListNode addElementLast(E element)\n {\n ListNode node = new ListNodeImpl<>(element);\n addNode(size, node);\n return node;\n }\n\n /**\n * Inserts the specified element before the specified {@link ListNode successor} in this list.\n * Returns the {@code ListNode} allocated to store the {@code value}.\n *\n * @param successor {@code ListNode} before which the node holding {@code value} is inserted\n * @param element the element to add\n * @return the {@code ListNode} allocated to store the {@code value}\n * @throws IllegalArgumentException if {@code successor} is not contained in this list\n * @throws NullPointerException if {@code successor} is {@code null}\n */\n public ListNode addElementBeforeNode(ListNode successor, E element)\n {\n ListNode node = new ListNodeImpl<>(element);\n addNodeBefore(node, successor);\n return node;\n }\n\n // List methods (shortcut for most commonly used methods to avoid iterator creation)\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void add(int index, E element)\n {\n if (index == size) { // also true if this is empty\n addElementLast(element);\n } else {\n addElementBeforeNode(getNode(index), element);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E get(int index)\n {\n return getNodeAt(index).value;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E remove(int index)\n {\n ListNode node = getNode(index);\n removeNode(node);\n return node.getValue();\n }\n\n // Deque methods\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void addFirst(E e)\n {\n addElementFirst(e);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void addLast(E e)\n {\n addElementLast(e);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean offerFirst(E e)\n {\n addElementFirst(e);\n return true;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean offerLast(E e)\n {\n addElementLast(e);\n return true;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E removeFirst()\n {\n if (isEmpty()) {\n throw new NoSuchElementException();\n }\n\n ListNode node = head;\n removeNode(node); // changes head\n return node.getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E removeLast()\n {\n if (isEmpty()) {\n throw new NoSuchElementException();\n }\n\n ListNode node = tail();\n removeNode(node); // changes tail\n return node.getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E pollFirst()\n {\n if (isEmpty()) {\n return null;\n }\n ListNode node = head;\n removeNode(node); // changes head\n return node.getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E pollLast()\n {\n if (isEmpty()) {\n return null;\n }\n ListNode node = tail();\n removeNode(node); // changes tail()\n return node.getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E getFirst()\n {\n return getFirstNode().getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E getLast()\n {\n return getLastNode().getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E peekFirst()\n {\n return isEmpty() ? null : getFirst();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E peekLast()\n {\n return isEmpty() ? null : getLast();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean removeFirstOccurrence(Object o)\n {\n ListNode node = nodeOf(o);\n if (node != null) {\n removeNode(node);\n return true;\n }\n return false;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean removeLastOccurrence(Object o)\n {\n ListNode node = lastNodeOf(o);\n if (node != null) {\n removeNode(node);\n return true;\n }\n return false;\n }\n\n // Queue methods\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean offer(E e)\n {\n return offerLast(e);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E remove()\n {\n return removeFirst();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E poll()\n {\n return pollFirst();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E element()\n {\n return getFirst();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E peek()\n {\n return peekFirst();\n }\n\n // Stack methods\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void push(E e)\n {\n addFirst(e);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E pop()\n {\n return removeFirst();\n }\n\n // special bulk methods\n\n /**\n * Inverts the list. For instance, calling this method on the list $(a,b,c,\\dots,x,y,z)$ will\n * result in the list $(z,y,x,\\dots,c,b,a)$. This method does only pointer manipulation, meaning\n * that all the list nodes allocated for the previously added elements are valid after this\n * method finishes.\n */\n public void invert()\n {\n if (size < 2) {\n return;\n }\n ListNodeImpl newHead = tail();\n ListNodeImpl current = head;\n do {\n ListNodeImpl next = current.next;\n\n current.next = current.prev;\n current.prev = next;\n\n current = next;\n } while (current != head);\n head = newHead;\n ++modCount;\n }\n\n /**\n * Moves all {@link ListNode ListNodes} of the given {@code sourceList} to this list and inserts\n * them all before the node previously at the given position. All the {@code nodes} of\n * {@code movedList} are moved to this list. When this method terminates this list contains all\n * nodes of {@code movedList} and {@code movedList} is empty.\n *\n * @param index index of the first element of {@code list} in this {@code list} after it was\n * added\n * @param movedList the {@code DoublyLinkedList} to move to this one\n * @throws NullPointerException if {@code movedList} is {@code null}\n */\n public void moveFrom(int index, DoublyLinkedList movedList)\n {\n linkListIntoThisBefore(index, movedList);\n }\n\n /**\n * Appends the {@code movedList} to the end of this list. All the elements from\n * {@code movedList} are transferred to this list, i.e. the {@code list} is empty after calling\n * this method.\n *\n * @param movedList the {@code DoublyLinkedList} to append to this one\n * @throws NullPointerException if {@code movedList} is {@code null}\n */\n public void append(DoublyLinkedList movedList)\n {\n moveFrom(size, movedList);\n }\n\n /**\n * Prepends the {@code movedList} to the beginning of this list. All the elements from\n * {@code movedList} are transferred to this list, i.e. the {@code movedList} is empty after\n * calling this method.\n *\n * @param movedList the {@code DoublyLinkedList} to prepend to this one\n * @throws NullPointerException if {@code movedList} is {@code null}\n */\n public void prepend(DoublyLinkedList movedList)\n {\n moveFrom(0, movedList);\n }\n\n // ----------------------------------------------------------------------------\n // (List)Iterators\n\n /**\n * Returns a {@link NodeIterator} that starts at the first {@link ListNode} of this list that is\n * equal to the specified {@code firstElement}, iterates in forward direction over the end of\n * this list until the first node.\n *

      \n * The first call to {@link NodeIterator#nextNode()} returns the first {@code node} that holds a\n * value such that {@code Objects.equals(node.getValue, firstElement)} returns {@code true}. The\n * returned {@code NodeIterator} iterates in forward direction returning the respective next\n * element in subsequent calls to {@code next(Node)}. The returned iterator ignores the actual\n * bounds of this {@code DoublyLinkedList} and iterates until the node before the first one is\n * reached. Its {@link NodeIterator#hasNext() hasNext()} returns {@code false} if the next node\n * would be the first one.\n *

      \n * \n * @param firstElement the element equal to the first {@code next()}\n * @return a circular {@code NodeIterator} iterating forward from {@code firstElement}\n */\n public NodeIterator circularIterator(E firstElement)\n {\n ListNodeImpl startNode = (ListNodeImpl) nodeOf(firstElement);\n if (startNode == null) {\n throw new NoSuchElementException();\n }\n return new ListNodeIteratorImpl(0, startNode);\n }\n\n /**\n * Returns a {@link NodeIterator} that starts at the first {@link ListNode} of this list that is\n * equal to the specified {@code firstElement}, iterates in reverse direction over the end of\n * this list until the first node.\n *

      \n * The first call to {@link NodeIterator#nextNode()} returns the first {@code node} that holds a\n * value such that {@code Objects.equals(node.getValue, firstElement)} returns {@code true}. The\n * returned {@code NodeIterator} iterates in reverse direction returning the respective previous\n * element in subsequent calls to {@code next(Node)}. The returned iterator ignores the actual\n * bounds of this {@code DoublyLinkedList} and iterates until the node before the first one is\n * reached. Its {@link NodeIterator#hasNext() hasNext()} returns {@code false} if the next node\n * would be the first one.\n *

      \n * \n * @param firstElement the element equal to the first {@code next()}\n * @return a circular {@code NodeIterator} iterating backwards from {@code firstElement}\n */\n public NodeIterator reverseCircularIterator(E firstElement)\n {\n ListNodeImpl startNode = (ListNodeImpl) nodeOf(firstElement);\n if (startNode == null) {\n throw new NoSuchElementException();\n }\n return reverseIterator(new ListNodeIteratorImpl(size, startNode.next));\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public NodeIterator descendingIterator()\n {\n return reverseIterator(listIterator(size));\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public NodeIterator iterator()\n {\n return listIterator();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeIterator listIterator()\n {\n return listIterator(0);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeIterator listIterator(int index)\n {\n return new ListNodeIteratorImpl(index);\n }\n\n /**\n * Returns a {@link ListNodeIterator} over the elements in this list (in proper sequence)\n * starting with the first {@link ListNode} whose value is equal to the specified\n * {@code element}.\n *\n * @param element the first element to be returned from the list iterator (by a call to the\n * {@code next} method)\n * @return a list iterator over the elements in this list (in proper sequence)\n * @throws NoSuchElementException if {@code element} is not in the list\n */\n public ListNodeIterator listIterator(E element)\n {\n Pair, Integer> startPair = searchNode(() -> head, n -> n.next, element);\n ListNodeImpl startNode = startPair.getFirst();\n int startIndex = startPair.getSecond();\n if (startNode == null) {\n throw new NoSuchElementException();\n }\n return new ListNodeIteratorImpl(startIndex, startNode);\n }\n\n /**\n * An extension of the {@link Iterator} interface for {@link DoublyLinkedList DoublyLinkedLists}\n * exposing their {@link ListNode ListNodes}.\n *\n * @param the list element type\n */\n public interface NodeIterator\n extends\n Iterator\n {\n /**\n * {@inheritDoc}\n */\n @Override\n default E next()\n {\n return nextNode().getValue();\n }\n\n /**\n * Returns the next {@link ListNode} in the list and advances the cursor position.\n *\n * @return the next {@code ListNode}\n * @see ListIterator#next()\n */\n ListNode nextNode();\n\n }\n\n /**\n * An extension of the {@link ListIterator} interface for {@link DoublyLinkedList\n * DoublyLinkedLists} exposing their {@link ListNode ListNodes}.\n *\n * @param the list element type\n */\n public interface ListNodeIterator\n extends\n ListIterator,\n NodeIterator\n {\n /**\n * {@inheritDoc}\n */\n @Override\n default E next()\n {\n return nextNode().getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n default E previous()\n {\n return previousNode().getValue();\n }\n\n /**\n * Returns the previous {@link ListNode} in the list and moves the cursor position\n * backwards.\n *\n * @return the previous {@code ListNode}\n * @see ListIterator#previous()\n */\n ListNode previousNode();\n\n }\n\n /**\n * An implementation of the {@link DoublyLinkedList.ListNodeIterator} interface.\n */\n private class ListNodeIteratorImpl\n implements\n ListNodeIterator\n {\n /** Index in this list of the ListNode returned next. */\n private int nextIndex;\n /** ListNode this iterator will return next. Null if this list is empty. */\n private ListNodeImpl next;\n /** ListNode this iterator returned last. */\n private ListNodeImpl last = null;\n\n /**\n * The number of modifications the list have had at the moment when this iterator was\n * created\n */\n private int expectedModCount = modCount;\n\n private ListNodeIteratorImpl(int startIndex)\n {\n this.nextIndex = startIndex;\n if (startIndex == size) {\n this.next = isEmpty() ? null : head;\n } else {\n this.next = getNodeAt(startIndex);\n }\n }\n\n private ListNodeIteratorImpl(int startIndex, ListNodeImpl startNode)\n {\n this.nextIndex = startIndex;\n this.next = startNode;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean hasNext()\n {\n return nextIndex < size;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean hasPrevious()\n {\n return nextIndex > 0;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int nextIndex()\n {\n return nextIndex;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int previousIndex()\n {\n return nextIndex - 1;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeImpl nextNode()\n {\n checkForComodification();\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n\n last = next;\n next = next.next;\n nextIndex++;\n return last;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNode previousNode()\n {\n checkForComodification();\n if (!hasPrevious()) {\n throw new NoSuchElementException();\n }\n\n last = next = next.prev;\n nextIndex--;\n return last;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void add(E e)\n {\n checkForComodification();\n\n if (nextIndex == size) {\n addElementLast(e); // sets head to new node of e if was empty\n if (size == 1) { // was empty\n next = head; // jump over head threshold, so cursor is at the end\n }\n } else {\n addElementBeforeNode(next, e);\n }\n last = null;\n nextIndex++;\n expectedModCount++;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void set(E e)\n {\n if (last == null) {\n throw new IllegalStateException();\n }\n checkForComodification();\n // replace node returned last with a new node holding e\n\n ListNode nextNode = last.next;\n boolean wasLast = last == tail();\n removeNode(last);\n if (wasLast) { // or the sole node\n last = (ListNodeImpl) addElementLast(e);\n } else {\n last = (ListNodeImpl) addElementBeforeNode(nextNode, e);\n }\n expectedModCount += 2; // because of unlink and add\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void remove()\n {\n if (last == null) {\n throw new IllegalStateException();\n }\n checkForComodification();\n\n ListNodeImpl lastsNext = last.next;\n removeNode(last);\n if (next == last) { // previousNode() called before\n // removed element after cursor (which would have been next)\n next = lastsNext;\n } else { // nextNode() called before\n // removed element before cursor (next is unaffected but the index decreases)\n nextIndex--;\n }\n last = null;\n expectedModCount++;\n }\n\n /**\n * Verifies that the list structure hasn't been changed since the iteration started\n */\n private void checkForComodification()\n {\n if (expectedModCount != modCount) {\n throw new ConcurrentModificationException();\n }\n }\n }\n\n /**\n * Returns a {@link NodeIterator} that iterates in reverse order, assuming the cursor of the\n * specified {@link ListNodeIterator} is behind the tail of the list.\n */\n private static NodeIterator reverseIterator(ListNodeIterator listIterator)\n {\n return new NodeIterator()\n {\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean hasNext()\n {\n return listIterator.hasPrevious();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNode nextNode()\n {\n return listIterator.previousNode();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void remove()\n {\n listIterator.remove();\n }\n };\n }\n\n /**\n * Container for the elements stored in a {@link DoublyLinkedList}.\n *

      \n * A {@link ListNode} is either contained exactly once in exactly one {@code DoublyLinkedList}\n * or contained in no {@code DoublyLinkedList}.\n *

      \n * \n * @param the type of the element stored in this node\n */\n public interface ListNode\n {\n /**\n * Returns the immutable value this {@code ListNode} contains.\n *\n * @return the value this list node contains\n */\n V getValue();\n\n /**\n * Returns the next node in the list structure with respect to this node\n *\n * @return the next node in the list structure with respect to this node\n */\n ListNode getNext();\n\n /**\n * Returns the previous node in the list structure with respect to this node\n *\n * @return the previous node in the list structure with respect to this node\n */\n ListNode getPrev();\n }\n\n /**\n * The default {@link ListNode} implementation that enables checks and enforcement of a single\n * container list policy.\n */\n private static class ListNodeImpl\n implements\n ListNode\n {\n private final V value;\n private DoublyLinkedList list = null;\n private ListNodeImpl next = null;\n private ListNodeImpl prev = null;\n\n /**\n * Creates new list node\n *\n * @param value the value this list node stores\n */\n ListNodeImpl(V value)\n {\n this.value = value;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n if (list == null) {\n return \" - \" + value + \" - \"; // not in a list\n } else {\n return prev.value + \" -> \" + value + \" -> \" + next.value;\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public V getValue()\n {\n return value;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeImpl getNext()\n {\n return next;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeImpl getPrev()\n {\n return prev;\n }\n }\n}\n", "file_name": "DoublyLinkedList.java", "human_label": "Remove the doubly circular linked list node.If success return true,otherwise return false.", "level": "class_runnable", "lineno": "240", "name": "unlink", "oracle_context": "{ \"apis\" : \"[removeListNode, link, ListNodeImpl, size]\", \"classes\" : \"[ListNodeImpl]\", \"vars\" : \"[size, head]\" }", "package": "org.jgrapht.util", "project": "jgrapht-master" }, { "_id": "636767de1a6d9265ec018726", "all_context": "{ \"class_level\" : \"import lombok.Data;\\nimport lombok.Getter;\\nimport org.apache.commons.io.FileUtils;\\nimport org.apache.skywalking.oap.server.core.CoreModule;\\nimport org.apache.skywalking.oap.server.core.profiling.trace.ProfileTaskQueryService;\\nimport org.apache.skywalking.oap.server.core.query.TraceQueryService;\\nimport org.apache.skywalking.oap.server.core.query.type.BasicTrace;\\nimport org.apache.skywalking.oap.server.core.query.type.Span;\\nimport org.apache.skywalking.oap.server.core.query.type.Trace;\\nimport org.apache.skywalking.oap.server.core.storage.StorageModule;\\nimport org.apache.skywalking.oap.server.core.storage.profiling.trace.IProfileThreadSnapshotQueryDAO;\\nimport org.apache.skywalking.oap.server.library.module.ModuleManager;\\nimport org.apache.skywalking.oap.server.library.util.CollectionUtils;\\nimport org.yaml.snakeyaml.Yaml;\\nimport java.io.File;\\nimport java.io.FileInputStream;\\nimport java.io.IOException;\\nimport java.util.ArrayList;\\nimport java.util.List;\\nimport java.util.Objects;\\nimport java.util.stream.Collectors;\\nint SEQUENCE_RANGE_BATCH_SIZE;\\nExporterConfig config;\\nString segmentId;\\nlong segmentStartTime;\\nlong segmentEndTime;\\nint duration;\\nList profiledSegmentSpans;\\nint minSequence;\\nint maxSequence;\\nint min;\\nint max;\\nwriteFile();\\nparseFormFile(File file);\\nbuildSequenceRanges();\\nSequenceRange(int min,int max);\\nbuild(ExporterConfig config,ModuleManager manager);\\n\", \"repo_level\" : \"public interface CoreModule {public Class[] services();\\n }\\npublic interface ProfileTaskQueryService {public List getTaskList(String serviceId,String endpointName);\\npublic List getProfileTaskLogs(String taskID);\\npublic List getTaskTraces(String taskId);\\npublic ProfileAnalyzation getProfileAnalyze(String segmentId,List timeRanges);\\npublic ProfiledSegment getProfiledSegment(String segmentId);\\n }\\npublic interface TraceQueryService {public TraceBrief queryBasicTraces(String serviceId,String serviceInstanceId,String endpointId,String traceId,int minTraceDuration,int maxTraceDuration,TraceState traceState,QueryOrder queryOrder,Pagination paging,Duration duration,List tags);\\npublic Trace queryTrace(String traceId);\\n }\\npublic interface BasicTrace { }\\npublic interface Span { }\\npublic interface Trace { }\\npublic interface StorageModule {public Class[] services();\\n }\\npublic interface IProfileThreadSnapshotQueryDAO { List queryProfiledSegments(String taskId);\\n int queryMinSequence(String segmentId,long start,long end);\\n int queryMaxSequence(String segmentId,long start,long end);\\n List queryRecords(String segmentId,int minSequence,int maxSequence);\\n SegmentRecord getProfiledSegment(String segmentId);\\n }\\npublic interface ModuleManager {public void init(ApplicationConfiguration applicationConfiguration);\\npublic boolean has(String moduleName);\\npublic ModuleProviderHolder find(String moduleName);\\n }\\npublic interface CollectionUtils {static boolean isEmpty(Map map);\\nstatic boolean isEmpty(List list);\\nstatic boolean isEmpty(Set set);\\nstatic boolean isNotEmpty(List list);\\nstatic boolean isNotEmpty(Set set);\\nstatic boolean isNotEmpty(Map map);\\nstatic boolean isNotEmpty(T[] array);\\nstatic boolean isEmpty(byte[] array);\\nstatic boolean isNotEmpty(byte[] array);\\n }\\n\" }", "class_name": "ProfiledBasicInfo", "code": "public List buildSequenceRanges(){\n ArrayList ranges=new ArrayList<>();\n do {\n int batchMax=Math.min(minSequence + SEQUENCE_RANGE_BATCH_SIZE,maxSequence);\n ranges.add(new SequenceRange(minSequence,batchMax));\n minSequence=batchMax;\n }\n while (minSequence < maxSequence);\n return ranges;\n}\n", "docstring": "/** \n * build current profiles segment snapshot search sequence ranges\n */\n", "end_lineno": "141", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.tool.profile.exporter;\n\nimport lombok.Data;\nimport lombok.Getter;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.skywalking.oap.server.core.CoreModule;\nimport org.apache.skywalking.oap.server.core.profiling.trace.ProfileTaskQueryService;\nimport org.apache.skywalking.oap.server.core.query.TraceQueryService;\nimport org.apache.skywalking.oap.server.core.query.type.BasicTrace;\nimport org.apache.skywalking.oap.server.core.query.type.Span;\nimport org.apache.skywalking.oap.server.core.query.type.Trace;\nimport org.apache.skywalking.oap.server.core.storage.StorageModule;\nimport org.apache.skywalking.oap.server.core.storage.profiling.trace.IProfileThreadSnapshotQueryDAO;\nimport org.apache.skywalking.oap.server.library.module.ModuleManager;\nimport org.apache.skywalking.oap.server.library.util.CollectionUtils;\nimport org.yaml.snakeyaml.Yaml;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.stream.Collectors;\n\n@Data\npublic class ProfiledBasicInfo {\n\n public static final int SEQUENCE_RANGE_BATCH_SIZE = 500;\n\n private ExporterConfig config;\n\n // profiled segment\n private String segmentId;\n private long segmentStartTime;\n private long segmentEndTime;\n private int duration;\n\n // spans\n private List profiledSegmentSpans;\n\n // snapshot sequence\n private int minSequence;\n private int maxSequence;\n\n /**\n * reading data from storage and build data\n */\n public static ProfiledBasicInfo build(ExporterConfig config, ModuleManager manager) throws IOException {\n ProfiledBasicInfo data = new ProfiledBasicInfo();\n data.setConfig(config);\n\n ProfileTaskQueryService taskQueryService = manager.find(CoreModule.NAME).provider().getService(ProfileTaskQueryService.class);\n TraceQueryService traceQueryService = manager.find(CoreModule.NAME).provider().getService(TraceQueryService.class);\n IProfileThreadSnapshotQueryDAO threadSnapshotQueryDAO = manager.find(StorageModule.NAME).provider().getService(IProfileThreadSnapshotQueryDAO.class);\n\n // query and found profiled segment\n List taskTraces = taskQueryService.getTaskTraces(config.getTaskId());\n BasicTrace profiledTrace = taskTraces.stream().filter(t -> t.getTraceIds().contains(config.getTraceId())).findFirst().orElse(null);\n if (profiledTrace == null) {\n throw new IllegalArgumentException(\"Cannot fount profiled segment in current task: \" + config.getTaskId()\n + \", segment id: \" + config.getTraceId() + \", current task total profiled trace count is \" + taskTraces.size());\n }\n\n // setting segment basic info\n String segmentId = profiledTrace.getSegmentId();\n long startTime = Long.parseLong(profiledTrace.getStart());\n long endTime = startTime + profiledTrace.getDuration();\n data.setSegmentId(segmentId);\n data.setSegmentStartTime(startTime);\n data.setSegmentEndTime(endTime);\n data.setDuration(profiledTrace.getDuration());\n\n // query spans\n Trace trace = traceQueryService.queryTrace(config.getTraceId());\n List profiledSegmentSpans = trace.getSpans().stream().filter(s -> Objects.equals(s.getSegmentId(), segmentId)).collect(Collectors.toList());\n if (CollectionUtils.isEmpty(profiledSegmentSpans)) {\n throw new IllegalArgumentException(\"Current segment cannot found any span\");\n }\n data.setProfiledSegmentSpans(profiledSegmentSpans);\n\n // query snapshots sequences\n int minSequence = threadSnapshotQueryDAO.queryMinSequence(segmentId, startTime, endTime);\n int maxSequence = threadSnapshotQueryDAO.queryMaxSequence(segmentId, startTime, endTime);\n data.setMinSequence(minSequence);\n data.setMaxSequence(maxSequence);\n\n return data;\n }\n\n /**\n * serialize data to file\n */\n public File writeFile() throws IOException {\n String serialData = new Yaml().dump(this);\n File file = new File(config.getAnalyzeResultDist() + File.separator + \"basic.yml\");\n FileUtils.write(file, serialData, \"UTF-8\");\n return file;\n }\n\n /**\n * deserialize data from file\n */\n public static ProfiledBasicInfo parseFormFile(File file) throws IOException {\n try (FileInputStream fileInputStream = new FileInputStream(file)) {\n return new Yaml().loadAs(fileInputStream, ProfiledBasicInfo.class);\n }\n }\n\n /**\n * build current profiles segment snapshot search sequence ranges\n */\n public List buildSequenceRanges() {\n ArrayList ranges = new ArrayList<>();\n do {\n int batchMax = Math.min(minSequence + SEQUENCE_RANGE_BATCH_SIZE, maxSequence);\n ranges.add(new SequenceRange(minSequence, batchMax));\n minSequence = batchMax;\n }\n while (minSequence < maxSequence);\n\n return ranges;\n }\n\n @Getter\n public static class SequenceRange {\n private int min;\n private int max;\n\n public SequenceRange(int min, int max) {\n this.min = min;\n this.max = max;\n }\n }\n\n}\n", "file_name": "ProfiledBasicInfo.java", "human_label": "Return a list whose nodes are sequences,and the sequences'lower bound are all minSequence,and the length increases sequentially with SEQUENCE_RANGE_BATCH_SIZE but the upper bound is maxSequence.", "level": "class_runnable", "lineno": "128", "name": "buildSequenceRanges", "oracle_context": "{ \"apis\" : \"[min, add, SequenceRange]\", \"classes\" : \"[ArrayList]\", \"vars\" : \"[min, minSequence, SEQUENCE_RANGE_BATCH_SIZE, maxSequence]\" }", "package": "org.apache.skywalking.oap.server.tool.profile.exporter", "project": "skywalking-master" }, { "_id": "6367667c1a6d9265ec0173f7", "all_context": "{ \"class_level\" : \"import org.atmosphere.util.FakeHttpSession;\\nimport org.atmosphere.util.QueryStringDecoder;\\nimport org.atmosphere.util.ReaderInputStream;\\nimport org.slf4j.Logger;\\nimport org.slf4j.LoggerFactory;\\nimport javax.servlet.AsyncContext;\\nimport javax.servlet.AsyncListener;\\nimport javax.servlet.DispatcherType;\\nimport javax.servlet.RequestDispatcher;\\nimport javax.servlet.ServletContext;\\nimport javax.servlet.ServletException;\\nimport javax.servlet.ServletInputStream;\\nimport javax.servlet.ServletRequest;\\nimport javax.servlet.ServletResponse;\\nimport javax.servlet.http.Cookie;\\nimport javax.servlet.http.HttpServletRequest;\\nimport javax.servlet.http.HttpServletRequestWrapper;\\nimport javax.servlet.http.HttpServletResponse;\\nimport javax.servlet.http.HttpSession;\\nimport javax.servlet.http.Part;\\nimport java.io.BufferedReader;\\nimport java.io.ByteArrayInputStream;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport java.io.InputStreamReader;\\nimport java.io.Reader;\\nimport java.io.StringReader;\\nimport java.io.UnsupportedEncodingException;\\nimport java.net.InetSocketAddress;\\nimport java.nio.charset.StandardCharsets;\\nimport java.security.Principal;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Collections;\\nimport java.util.Enumeration;\\nimport java.util.HashMap;\\nimport java.util.HashSet;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Map;\\nimport java.util.Objects;\\nimport java.util.Set;\\nimport java.util.concurrent.Callable;\\nimport java.util.concurrent.atomic.AtomicBoolean;\\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE;\\nLogger logger;\\nServletInputStream bis;\\nBufferedReader br;\\nBuilder b;\\nAtomicBoolean destroyed;\\nboolean queryComputed;\\nboolean cookieComputed;\\nBufferedReader voidReader;\\nServletInputStream voidStream;\\nAtomicBoolean streamSet;\\nAtomicBoolean readerSet;\\nString uuid;\\nboolean noopsAsyncContextStarted;\\nByteArrayInputStream bis;\\nBody NULL_BODY;\\nHttpServletRequest request;\\nString pathInfo;\\nString encoding;\\nString methodType;\\nString contentType;\\nboolean noContentType;\\nLong contentLength;\\nMap headers;\\nMap queryStrings;\\nString servletPath;\\nString requestURI;\\nString requestURL;\\nInputStream inputStream;\\nReader reader;\\nString remoteAddr;\\nString remoteHost;\\nint remotePort;\\nString localAddr;\\nString localName;\\nint localPort;\\nboolean dispatchRequestAsynchronously;\\nboolean destroyable;\\nSet cookies;\\nSet locales;\\nPrincipal principal;\\nString authType;\\nString contextPath;\\nString serverName;\\nint serverPort;\\nHttpSession webSocketFakeSession;\\nString queryString;\\nboolean isSecure;\\nLazyComputation lazyRemote;\\nLazyComputation lazyLocal;\\nBody body;\\nLocalAttributes localAttributes;\\nString data;\\nbyte[] dataBytes;\\nint offset;\\nint length;\\nboolean isEmpty;\\nInputStream innerStream;\\nboolean throwExceptionOnCloned;\\nHttpSession fake;\\nEnumeration EMPTY_ENUM_STRING;\\nEnumeration EMPTY_ENUM_LOCALE;\\nList EMPTY_ENUM_PART;\\nMap EMPTY_MAP_STRING;\\nString[] EMPTY_ARRAY;\\nStringBuffer EMPTY_STRING_BUFFER;\\nCookie[] EMPTY_COOKIE;\\nCallable callable;\\nInetSocketAddress address;\\nAsyncContext context;\\nCompletionAware callback;\\nServletRequest request;\\nServletResponse response;\\nlong timeout;\\nAtmosphereRequestImpl(Builder b);\\ngetVoidReader();\\nconfigureStream();\\nconfigureReader();\\ndestroyed();\\ndestroyable(boolean destroyable);\\ngetPathInfo();\\ngetPathTranslated();\\ngetQueryString();\\ntoQs();\\ngetRemoteUser();\\ngetRequestedSessionId();\\ngetMethod();\\ngetPart(String name);\\ngetParts();\\ngetContentType();\\ngetDispatcherType();\\ngetServletPath();\\ngetRequestURI();\\ngetRequestURL();\\ngetHeaders(String name);\\ngetIntHeader(String name);\\ngetHeaderNames();\\nauthenticate(HttpServletResponse response);\\ngetAuthType();\\ngetContextPath();\\ngetCookies();\\ngetDateHeader(String name);\\ngetHeader(String s);\\nwrappedRequest();\\ngetHeader(String s,boolean checkCase);\\ngetParameter(String s);\\ngetParameterMap();\\ngetParameterNames();\\ngetParameterValues(String s);\\ngetProtocol();\\ngetInputStream();\\ngetReader();\\ngetRealPath(String path);\\nheaders(Map headers);\\nheader(String name,String value);\\nqueryString(String qs);\\nheadersMap();\\nqueryStringsMap();\\nmethod(String m);\\ncontentType(String m);\\nbody(String body);\\nbody(byte[] bytes);\\nbody(InputStream body);\\nbody(Reader body);\\nbody();\\nservletPath(String servletPath);\\ncontextPath(String contextPath);\\nrequestURI(String requestURI);\\nByteInputStream(byte[] data,int offset,int length);\\nread();\\nsetAttribute(String s,Object o);\\nsetCharacterEncoding(String env);\\nstartAsync();\\nstartAsync(ServletRequest request,ServletResponse response);\\ngetAsyncContext();\\ngetAttribute(String s);\\nremoveAttribute(String name);\\nattributes();\\ngetSession();\\ngetSession(boolean create);\\ngetUserPrincipal();\\nisRequestedSessionIdFromCookie();\\nisRequestedSessionIdFromUrl();\\nisRequestedSessionIdFromURL();\\nisRequestedSessionIdValid();\\nisUserInRole(String role);\\nlogin(String username,String password);\\nlogout();\\ngetRemoteAddr();\\ngetRemoteHost();\\ngetRemotePort();\\ngetRequestDispatcher(String path);\\ngetScheme();\\ngetServerName();\\ngetServerPort();\\ngetServletContext();\\nisAsyncStarted();\\nisAsyncSupported();\\nisSecure();\\ngetLocalName();\\ngetLocalPort();\\ngetLocalAddr();\\nisNotNoOps();\\ngetLocale();\\nresource();\\ngetLocales();\\ndispatchRequestAsynchronously();\\nisDestroyable();\\npathInfo(String pathInfo);\\ngetAttributeNames();\\nattributeWithoutException(HttpServletRequest request,String attribute);\\nlocalAttributes();\\ngetCharacterEncoding();\\ngetContentLength();\\nuuid();\\ndestroy();\\ndestroy(boolean force);\\nsetRequest(ServletRequest request);\\nBuilder();\\ncookies(Set cookies);\\ndispatchRequestAsynchronously(boolean dispatchRequestAsynchronously);\\nremoteAddr(String remoteAddr);\\nremoteHost(String remoteHost);\\nremotePort(int remotePort);\\nlocalAddr(String localAddr);\\nlocalName(String localName);\\nlocalPort(int localPort);\\nremoteInetSocketAddress(Callable remoteAddr);\\nlocalInetSocketAddress(Callable localAddr);\\nattributes(Map attributes);\\nrequest(HttpServletRequest request);\\nrequestURL(String requestURL);\\nqueryString(String queryString);\\nbody(byte[] dataBytes);\\nbody(byte[] dataBytes,int offset,int length);\\nencoding(String encoding);\\nmethod(String methodType);\\ncontentType(String contentType);\\ncontentLength(Long contentLength);\\nbody(String data);\\ninputStream(InputStream inputStream);\\nreader(Reader reader);\\nbuild();\\nqueryStrings(Map queryStrings);\\nserverName(String serverName);\\nserverPort(int serverPort);\\nsession(HttpSession session);\\nprincipal(Principal principal);\\nauthType(String authType);\\nisSSecure(boolean isSecure);\\nlocale(Locale locale);\\nuserPrincipal(Principal userPrincipal);\\nBody(String data,byte[] dataBytes,int offset,int length);\\nhasBytes();\\nasString();\\nasBytes();\\nbyteOffset();\\nbyteLength();\\nisEmpty();\\nIS(InputStream innerStream);\\nread(byte[] bytes);\\nread(byte[] bytes,int i,int i1);\\nskip(long l);\\navailable();\\nclose();\\nmark(int i);\\nreset();\\nmarkSupported();\\nnewInstance();\\nwrap(HttpServletRequest request);\\ncloneRequest(HttpServletRequest request,boolean loadInMemory,boolean copySession,boolean isDestroyable,boolean createSession);\\nNoOpsRequest();\\nNoOpsRequest(boolean throwExceptionOnCloned);\\ngetHeader(String name);\\ninvalidate();\\ngetAttribute(String name);\\ngetParameter(String name);\\ngetParameterValues(String name);\\nsetAttribute(String name,Object o);\\nLazyComputation(Callable callable);\\naddress();\\ngetPort();\\ngetHostAddress();\\ngetHostName();\\nisCompletionAware();\\nCompletionAwareAsyncContext(AsyncContext context,CompletionAware callback);\\naddListener(AsyncListener listener);\\naddListener(AsyncListener listener,ServletRequest request,ServletResponse response);\\ncomplete();\\ncreateListener(Class clazz);\\ndispatch();\\ndispatch(ServletContext servletContext,String path);\\ndispatch(String path);\\ngetRequest();\\ngetResponse();\\ngetTimeout();\\nhasOriginalRequestAndResponse();\\nsetTimeout(long timeoutMilliseconds);\\nstart(Runnable run);\\nNoOpsAsyncContext(ServletRequest request,ServletResponse response);\\nsetTimeout(long timeout);\\nload(HttpServletRequest request,Builder b);\\ntoString();\\nrequestURL();\\nhasString();\\n\", \"repo_level\" : \"public interface FakeHttpSession {public void destroy();\\npublic long getCreationTime();\\npublic String getId();\\npublic long getLastAccessedTime();\\npublic ServletContext getServletContext();\\npublic void setMaxInactiveInterval(int interval);\\npublic int getMaxInactiveInterval();\\npublic HttpSessionContext getSessionContext();\\npublic Object getAttribute(String name);\\npublic Object getValue(String name);\\npublic Enumeration getAttributeNames();\\npublic String[] getValueNames();\\npublic void setAttribute(String name,Object value);\\npublic void putValue(String name,Object value);\\npublic void removeAttribute(String name);\\npublic void removeValue(String name);\\npublic FakeHttpSession copyAttributes(HttpSession httpSession);\\npublic void invalidate();\\npublic boolean isNew();\\n }\\npublic interface QueryStringDecoder {public String getPath();\\npublic Map> getParameters();\\nstatic String decodeComponent(String s);\\nstatic String decodeComponent(String s,Charset charset);\\n }\\npublic interface ReaderInputStream {public int read(byte[] b,int off,int len);\\npublic int read(byte[] b);\\npublic int read();\\npublic void close();\\n }\\n\" }", "class_name": "AtmosphereRequestImpl", "code": "public boolean hasBytes(){\n return dataBytes != null;\n}\n", "docstring": "/** \n * True is the body is a byte array\n * @return True is the body is a byte array\n */\n", "end_lineno": "1299", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\npackage org.atmosphere.cpr;\n\nimport org.atmosphere.util.FakeHttpSession;\nimport org.atmosphere.util.QueryStringDecoder;\nimport org.atmosphere.util.ReaderInputStream;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.servlet.AsyncContext;\nimport javax.servlet.AsyncListener;\nimport javax.servlet.DispatcherType;\nimport javax.servlet.RequestDispatcher;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletInputStream;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.ServletResponse;\nimport javax.servlet.http.Cookie;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletRequestWrapper;\nimport javax.servlet.http.HttpServletResponse;\nimport javax.servlet.http.HttpSession;\nimport javax.servlet.http.Part;\n\nimport java.io.BufferedReader;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.Reader;\nimport java.io.StringReader;\nimport java.io.UnsupportedEncodingException;\nimport java.net.InetSocketAddress;\nimport java.nio.charset.StandardCharsets;\nimport java.security.Principal;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE;\n\n/**\n * An Atmosphere request representation. An {@link AtmosphereRequest} is a two-way communication channel between the\n * client and the server. If the {@link AtmosphereRequestImpl#isDestroyable()} is set to false, or if its\n * associated {@link AtmosphereResource} has been suspended, this object can be re-used at any moment between requests.\n * You can use its associated {@link AtmosphereResponse} to write bytes at any moment, making this object bi-directional.\n *
      \n *\n * @author Jeanfrancois Arcand\n */\npublic class AtmosphereRequestImpl extends HttpServletRequestWrapper implements AtmosphereRequest {\n\n private final static Logger logger = LoggerFactory.getLogger(AtmosphereRequestImpl.class);\n private ServletInputStream bis;\n private BufferedReader br;\n private final Builder b;\n private final AtomicBoolean destroyed = new AtomicBoolean(false);\n private boolean queryComputed;\n private boolean cookieComputed;\n private volatile BufferedReader voidReader;\n private final ServletInputStream voidStream = new IS(new ByteArrayInputStream(new byte[0]));\n private final AtomicBoolean streamSet = new AtomicBoolean();\n private final AtomicBoolean readerSet = new AtomicBoolean();\n private String uuid;\n private boolean noopsAsyncContextStarted;\n\n private AtmosphereRequestImpl(Builder b) {\n super(b.request == null ? new NoOpsRequest() : b.request);\n if (b.request == null) b.request(new NoOpsRequest());\n\n this.b = b;\n this.uuid = resource() != null ? resource().uuid() : \"0\";\n }\n\n private BufferedReader getVoidReader() {\n if (voidReader == null) {\n voidReader = new BufferedReader(new StringReader(\"\"), 5);\n }\n return voidReader;\n }\n\n private void configureStream() {\n if (bis == null && !streamSet.getAndSet(true)) {\n if (b.inputStream != null) {\n bis = new IS(b.inputStream);\n } else if (b.reader == null) {\n if (b.body.dataBytes != null) {\n bis = new ByteInputStream(b.body.dataBytes, b.body.offset, b.body.length);\n } else if (b.body.data != null) {\n byte[] bytes = b.body.data.getBytes(StandardCharsets.UTF_8);\n bis = new ByteInputStream(bytes, 0, bytes.length);\n }\n } else {\n bis = new IS(new ReaderInputStream(b.reader));\n }\n }\n }\n\n private void configureReader() {\n if (br == null && !readerSet.getAndSet(false)) {\n if (b.reader != null) {\n br = new BufferedReader(b.reader);\n } else if (b.inputStream == null) {\n try {\n if (b.body.dataBytes != null) {\n br = new BufferedReader(new StringReader(new String(b.body.dataBytes, b.body.offset, b.body.length, b.encoding)));\n } else if (b.body.data != null) {\n br = new BufferedReader(new StringReader(b.body.data));\n }\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n } else {\n br = new BufferedReader(new InputStreamReader(b.inputStream));\n }\n }\n }\n\n @Override\n public boolean destroyed() {\n return destroyed.get();\n }\n\n @Override\n public AtmosphereRequest destroyable(boolean destroyable) {\n b.destroyable = destroyable;\n return this;\n }\n\n @Override\n public String getPathInfo() {\n return !Objects.equals(b.pathInfo, \"\") ? b.pathInfo : isNotNoOps() ? b.request.getPathInfo() : \"\";\n }\n\n @Override\n public String getPathTranslated() {\n return b.request.getPathTranslated();\n }\n\n @Override\n public String getQueryString() {\n return !Objects.equals(b.queryString, \"\") ? b.queryString : isNotNoOps() ? b.request.getQueryString() : toQs();\n }\n\n private String toQs() {\n StringBuilder q = new StringBuilder();\n for (Map.Entry e : b.queryStrings.entrySet()) {\n for (String k : e.getValue()) {\n q.append(e.getKey()).append(\"=\").append(k).append(\"&\");\n }\n }\n if (q.length() > 0) q.deleteCharAt(q.length() - 1);\n return q.toString();\n }\n\n @Override\n public String getRemoteUser() {\n return b.principal != null ? b.principal.getName() : b.request.getRemoteUser();\n }\n\n @Override\n public String getRequestedSessionId() {\n return b.request.getRequestedSessionId();\n }\n\n @Override\n public String getMethod() {\n return b.methodType != null ? b.methodType : b.request.getMethod();\n }\n\n @Override\n public Part getPart(String name) throws IOException, ServletException {\n return b.request.getPart(name);\n }\n\n @Override\n public Collection getParts() throws IOException, ServletException {\n return b.request.getParts();\n }\n\n @Override\n public String getContentType() {\n return b.contentType != null || b.noContentType ? b.contentType : b.request.getContentType();\n }\n\n @Override\n public DispatcherType getDispatcherType() {\n return b.request.getDispatcherType();\n }\n\n @Override\n public String getServletPath() {\n return !Objects.equals(b.servletPath, \"\") ? b.servletPath : (isNotNoOps() ? b.request.getServletPath() : \"\");\n }\n\n @Override\n public String getRequestURI() {\n return b.requestURI != null ? b.requestURI : (isNotNoOps() ? b.request.getRequestURI() : \"\");\n }\n\n @Override\n public StringBuffer getRequestURL() {\n return b.requestURL != null ? new StringBuffer(b.requestURL) : (isNotNoOps() ? b.request.getRequestURL() : new StringBuffer());\n }\n\n @Override\n public Enumeration getHeaders(String name) {\n\n ArrayList list = new ArrayList<>();\n // Never override the parent Request\n if (!name.equalsIgnoreCase(\"content-type\")) {\n Enumeration e = b.request.getHeaders(name);\n while (e.hasMoreElements())\n list.add(e.nextElement());\n }\n\n if (name.equalsIgnoreCase(\"content-type\")) {\n String s = getContentType();\n if (s != null) {\n list.add(s);\n }\n } else {\n if (b.headers.get(name) != null) {\n list.add(b.headers.get(name));\n }\n\n if (isNotNoOps()) {\n if (list.isEmpty() && name.startsWith(X_ATMOSPHERE)) {\n if (attributeWithoutException(b.request, name) != null) {\n list.add(attributeWithoutException(b.request, name));\n }\n }\n }\n }\n return Collections.enumeration(list);\n }\n\n @Override\n public int getIntHeader(String name) {\n return b.request.getIntHeader(name);\n }\n\n @Override\n public Enumeration getHeaderNames() {\n Set list = new HashSet<>();\n list.addAll(b.headers.keySet());\n\n list.addAll(Collections.list(b.request.getHeaderNames()));\n if (b.request != null) {\n Enumeration e = b.request.getAttributeNames();\n while (e.hasMoreElements()) {\n String name = e.nextElement();\n if (name.startsWith(X_ATMOSPHERE)) {\n list.add(name);\n }\n }\n }\n\n if (b.contentType != null) {\n list.add(\"Content-Type\");\n }\n return Collections.enumeration(list);\n }\n\n @Override\n public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {\n return b.request.authenticate(response);\n }\n\n @Override\n public String getAuthType() {\n return b.authType != null ? b.authType : b.request.getAuthType();\n }\n\n @Override\n public String getContextPath() {\n String c = \"/\";\n try {\n c = isNotNoOps() && b.request.getContextPath() != null ? b.request.getContextPath() : b.contextPath != null ? b.contextPath : \"\";\n } catch (NullPointerException ex) {\n // https://github.com/Atmosphere/atmosphere/issues/1804\n logger.warn(\"Unexpected getContextPath exception. Forcing `/`\", ex);\n }\n return c;\n }\n\n @Override\n public Cookie[] getCookies() {\n if (!cookieComputed) {\n if (b.cookies == null)\n return new Cookie[0];\n cookieComputed = true;\n Cookie[] c = b.request.getCookies();\n if (c != null && c.length > 0) {\n b.cookies.addAll(Arrays.asList(c));\n }\n }\n return b.cookies.toArray(new Cookie[]{});\n }\n\n @Override\n public long getDateHeader(String name) {\n return b.request.getDateHeader(name);\n }\n\n @Override\n public String getHeader(String s) {\n return getHeader(s, true);\n }\n\n @Override\n public HttpServletRequest wrappedRequest() {\n return b.request;\n }\n\n @Override\n public String getHeader(String s, boolean checkCase) {\n\n if (\"content-type\".equalsIgnoreCase(s)) {\n return getContentType();\n }\n\n String name = b.request.getHeader(s);\n if (name == null) {\n if (b.headers.get(s) != null) {\n return b.headers.get(s);\n }\n\n if (s.startsWith(X_ATMOSPHERE) && isNotNoOps()) {\n // Craziness with Struts 2 who wraps String attribute as BigDecimal\n // https://github.com/Atmosphere/atmosphere/issues/1367\n Object o = attributeWithoutException(b.request, s);\n if (o == null || String.class.isAssignableFrom(o.getClass())) {\n name = (String) o;\n } else {\n try {\n if (HttpServletRequestWrapper.class.isAssignableFrom(b.request.getClass())) {\n HttpServletRequest hsr = b.request;\n while (hsr instanceof HttpServletRequestWrapper) {\n hsr = (HttpServletRequest) ((HttpServletRequestWrapper) hsr).getRequest();\n o = attributeWithoutException(hsr, s);\n if (o == null || String.class.isAssignableFrom(o.getClass())) {\n name = (String) o;\n break;\n }\n }\n }\n } catch (Exception ex) {\n logger.warn(\"\", ex);\n }\n }\n }\n }\n\n if (name == null && checkCase) {\n return getHeader(s.toLowerCase(), false);\n }\n\n if (name == null && \"connection\".equalsIgnoreCase(s)) {\n return \"keep-alive\";\n }\n\n return name;\n }\n\n @Override\n public String getParameter(String s) {\n String name = isNotNoOps() ? b.request.getParameter(s) : null;\n if (name == null) {\n if (b.queryStrings.get(s) != null) {\n return b.queryStrings.get(s)[0];\n }\n }\n return name;\n }\n\n @Override\n public Map getParameterMap() {\n if (!queryComputed) {\n queryComputed = true;\n Map m = (isNotNoOps() ? b.request.getParameterMap() : Collections.emptyMap());\n for (String e : m.keySet()) {\n b.queryStrings.put(e, getParameterValues(e));\n }\n }\n return Collections.unmodifiableMap(b.queryStrings);\n }\n\n @Override\n public Enumeration getParameterNames() {\n return Collections.enumeration(getParameterMap().keySet());\n }\n\n @Override\n public String[] getParameterValues(String s) {\n String[] list = b.request.getParameterValues(s);\n if (list != null && b.queryStrings.get(s) != null) {\n String[] newList = b.queryStrings.get(s);\n if (!Arrays.deepEquals(list, newList)) {\n String[] s1 = new String[list.length + newList.length];\n System.arraycopy(list, 0, s1, 0, list.length);\n System.arraycopy(newList, 0, s1, list.length, newList.length);\n return s1;\n } else {\n return list;\n }\n } else {\n return list == null ? b.queryStrings.get(s) : list;\n }\n }\n\n @Override\n public String getProtocol() {\n return b.request.getProtocol();\n }\n\n @Override\n public ServletInputStream getInputStream() throws IOException {\n if (b.body.isEmpty()) {\n configureStream();\n return bis == null ? (isNotNoOps() ? b.request.getInputStream() : voidStream) : bis;\n } else if (b.body.hasString()) {\n bis = new IS(new ByteArrayInputStream(b.body.asString().getBytes()));\n } else if (b.body.hasBytes()) {\n bis = new IS(new ByteArrayInputStream(b.body.asBytes(), b.body.offset, b.body.byteLength()));\n }\n return bis;\n }\n\n @Override\n public BufferedReader getReader() throws IOException {\n if (b.body.isEmpty()) {\n configureReader();\n return br == null ? (isNotNoOps() ? b.request.getReader() : getVoidReader()) : br;\n } else if (b.body.hasString()) {\n br = new BufferedReader(new StringReader(body().asString()));\n } else if (b.body.hasBytes()) {\n br = new BufferedReader(new StringReader(new String(body().asBytes(), body().byteOffset(), body().length)));\n }\n return br;\n }\n\n @Override\n public String getRealPath(String path) {\n return b.request.getRealPath(path);\n }\n\n @Override\n public AtmosphereRequest headers(Map headers) {\n b.headers.putAll(headers);\n return this;\n }\n\n @Override\n public AtmosphereRequest header(String name, String value) {\n b.headers.put(name, value);\n return this;\n }\n\n @Override\n public AtmosphereRequest queryString(String qs) {\n\n if (qs == null) return this;\n\n if (!qs.isEmpty()) {\n QueryStringDecoder decoder = new QueryStringDecoder(getRequestURI() + \"?\" + qs);\n Map> m = decoder.getParameters();\n Map newM = new HashMap<>();\n for (Map.Entry> q : m.entrySet()) {\n newM.put(q.getKey(), q.getValue().toArray(new String[0]));\n }\n b.queryStrings(newM);\n }\n b.queryString = qs;\n return this;\n }\n\n @Override\n public Map headersMap() {\n return b.headers;\n }\n\n @Override\n public Map queryStringsMap() {\n return b.queryStrings;\n }\n\n @Override\n public AtmosphereRequest method(String m) {\n b.method(m);\n return this;\n }\n\n @Override\n public AtmosphereRequest contentType(String m) {\n b.contentType(m);\n return this;\n }\n\n @Override\n public AtmosphereRequest body(String body) {\n b.body = new Body(body, null, 0, 0);\n return this;\n }\n\n @Override\n public AtmosphereRequest body(byte[] bytes) {\n b.body = new Body(null, bytes, 0, bytes.length);\n return this;\n }\n\n @Override\n public AtmosphereRequest body(InputStream body) {\n bis = new IS(body);\n br = new BufferedReader(new InputStreamReader(body));\n return this;\n }\n\n @Override\n public AtmosphereRequest body(Reader body) {\n bis = new IS(new ReaderInputStream(body));\n br = new BufferedReader(body);\n return this;\n }\n\n @Override\n public Body body() {\n return b.body;\n }\n\n @Override\n public AtmosphereRequest servletPath(String servletPath) {\n b.servletPath = servletPath;\n return this;\n }\n\n @Override\n public AtmosphereRequest contextPath(String contextPath) {\n b.contextPath = contextPath;\n return this;\n }\n\n @Override\n public AtmosphereRequest requestURI(String requestURI) {\n b.requestURI = requestURI;\n return this;\n }\n\n private final static class ByteInputStream extends ServletInputStream {\n\n private final ByteArrayInputStream bis;\n\n public ByteInputStream(byte[] data, int offset, int length) {\n this.bis = new ByteArrayInputStream(data, offset, length);\n }\n\n @Override\n public int read() throws IOException {\n return bis.read();\n }\n }\n\n @Override\n public void setAttribute(String s, Object o) {\n if (o == null) {\n removeAttribute(s);\n return;\n }\n b.localAttributes.put(s, o);\n if (isNotNoOps() && !destroyed.get()) {\n try {\n synchronized (b.request) {\n b.request.setAttribute(s, o);\n }\n } catch (NullPointerException ex) {\n // https://github.com/Atmosphere/atmosphere/issues/1806\n logger.trace(\"\", ex);\n }\n }\n }\n\n @Override\n public void setCharacterEncoding(String env) throws UnsupportedEncodingException {\n b.request.setCharacterEncoding(env);\n }\n\n @Override\n public AsyncContext startAsync() {\n AsyncContext ac;\n if (AtmosphereResource.TRANSPORT.WEBSOCKET == resource().transport()) {\n noopsAsyncContextStarted = true;\n ac = new NoOpsAsyncContext(getRequest(), resource().getResponse().getResponse());\n } else {\n ac = b.request.startAsync();\n }\n return isCompletionAware()\n ? new CompletionAwareAsyncContext(ac, (CompletionAware) resource().getResponse()) : ac;\n }\n\n @Override\n public AsyncContext startAsync(ServletRequest request, ServletResponse response) {\n AsyncContext ac;\n if (AtmosphereResource.TRANSPORT.WEBSOCKET == resource().transport()) {\n noopsAsyncContextStarted = true;\n ac = new NoOpsAsyncContext(request, response);\n } else {\n ac = b.request.startAsync(request, response);\n }\n return isCompletionAware()\n ? new CompletionAwareAsyncContext(ac, (CompletionAware) resource().getResponse()) : ac;\n }\n\n @Override\n public AsyncContext getAsyncContext() {\n AsyncContext ac;\n if (AtmosphereResource.TRANSPORT.WEBSOCKET == resource().transport()) {\n noopsAsyncContextStarted = true;\n ac = new NoOpsAsyncContext(getRequest(), resource().getResponse().getResponse());\n } else {\n ac = b.request.getAsyncContext();\n }\n return isCompletionAware()\n ? new CompletionAwareAsyncContext(ac, (CompletionAware) resource().getResponse()) : ac;\n }\n\n @Override\n public Object getAttribute(String s) {\n return b.localAttributes.get(s) != null ? b.localAttributes.get(s) : (isNotNoOps() ? attributeWithoutException(b.request, s) : null);\n }\n\n @Override\n public void removeAttribute(String name) {\n\n b.localAttributes.remove(name);\n if (isNotNoOps() && !destroyed.get()) {\n synchronized (b.request) {\n b.request.removeAttribute(name);\n }\n }\n }\n\n @Override\n public LocalAttributes attributes() {\n return b.localAttributes;\n }\n\n @Override\n public HttpSession getSession() {\n return getSession(true);\n }\n\n @Override\n public HttpSession getSession(boolean create) {\n if (b.webSocketFakeSession != null) {\n return b.webSocketFakeSession;\n }\n\n if (resource() != null) {\n // UGLY, but we need to prevent looping here.\n HttpSession session = ((AtmosphereResourceImpl) resource()).session;\n try {\n if (session != null) {\n // check if session is valid (isNew() will throw if not)\n session.isNew();\n return session;\n }\n } catch (IllegalStateException e) {\n // session has been invalidated\n }\n }\n\n try {\n return b.request.getSession(create);\n } catch (java.lang.IllegalStateException ex) {\n // JettyAsyncSupportListenerAdapter\n if (ex.getMessage() != null && ex.getMessage().equals(\"No SessionManager\")) {\n return null;\n }\n throw ex;\n } catch (NullPointerException ex) {\n // GLASSFISH http://java.net/jira/browse/GLASSFISH-18856\n try {\n return b.request.getSession(create);\n } catch (Exception e) {\n logger.trace(\"\", ex);\n return null;\n }\n } catch (RuntimeException ex) {\n // https://github.com/Atmosphere/atmosphere/issues/1974\n logger.trace(\"\", ex);\n if (ex.getMessage() != null && ex.getMessage().contains(\"SESN0007E\")) {\n return null;\n }\n throw ex;\n }\n }\n\n @Override\n public Principal getUserPrincipal() {\n return b.principal != null ? b.principal : b.request.getUserPrincipal();\n }\n\n @Override\n public boolean isRequestedSessionIdFromCookie() {\n return b.request.isRequestedSessionIdFromCookie();\n }\n\n @Override\n public boolean isRequestedSessionIdFromUrl() {\n return b.request.isRequestedSessionIdFromUrl();\n }\n\n @Override\n public boolean isRequestedSessionIdFromURL() {\n return b.request.isRequestedSessionIdFromURL();\n }\n\n @Override\n public boolean isRequestedSessionIdValid() {\n return b.request.isRequestedSessionIdValid();\n }\n\n @Override\n public boolean isUserInRole(String role) {\n return b.request.isUserInRole(role);\n }\n\n @Override\n public void login(String username, String password) throws ServletException {\n b.request.login(username, password);\n }\n\n @Override\n public void logout() throws ServletException {\n b.request.logout();\n }\n\n @Override\n public String getRemoteAddr() {\n return isNotNoOps() ? b.request.getRemoteAddr() : b.lazyRemote != null ? b.lazyRemote.getHostAddress() : b.remoteAddr;\n }\n\n @Override\n public String getRemoteHost() {\n return isNotNoOps() ? b.request.getRemoteHost() : b.lazyRemote != null ? b.lazyRemote.getHostName() : b.remoteHost;\n }\n\n @Override\n public int getRemotePort() {\n return isNotNoOps() ? b.request.getRemotePort() : b.lazyRemote != null ? b.lazyRemote.getPort() : b.remotePort;\n }\n\n @Override\n public RequestDispatcher getRequestDispatcher(String path) {\n return b.request.getRequestDispatcher(path);\n }\n\n @Override\n public String getScheme() {\n return b.request.getScheme();\n }\n\n @Override\n public String getServerName() {\n return !b.serverName.equals(\"\") ? b.serverName : b.request.getServerName();\n }\n\n @Override\n public int getServerPort() {\n return b.serverPort != 0 ? b.serverPort : b.request.getServerPort();\n }\n\n @Override\n public ServletContext getServletContext() {\n return b.request.getServletContext();\n }\n\n @Override\n public boolean isAsyncStarted() {\n if (resource() != null && AtmosphereResource.TRANSPORT.WEBSOCKET == resource().transport()) {\n return noopsAsyncContextStarted;\n }\n try {\n return b.request.isAsyncStarted();\n } catch (Throwable ex) {\n logger.trace(\"\", ex);\n return false;\n }\n }\n\n @Override\n public boolean isAsyncSupported() {\n try {\n return b.request.isAsyncSupported();\n } catch (Throwable ex) {\n // Servlet 2.5 incompatible API.\n logger.trace(\"\", ex);\n return false;\n }\n }\n\n @Override\n public boolean isSecure() {\n return isNotNoOps() ? b.request.isSecure() : b.isSecure;\n }\n\n @Override\n public String getLocalName() {\n return isNotNoOps() ? b.request.getLocalName() : b.lazyLocal != null ? b.lazyLocal.getHostName() : b.localName;\n }\n\n @Override\n public int getLocalPort() {\n return isNotNoOps() ? b.request.getLocalPort() : b.lazyLocal != null ? b.lazyLocal.getPort() : b.localPort;\n }\n\n @Override\n public String getLocalAddr() {\n return isNotNoOps() ? b.request.getLocalAddr() : b.lazyLocal != null ? b.lazyLocal.getHostAddress() : b.localAddr;\n }\n\n private boolean isNotNoOps() {\n return !NoOpsRequest.class.isAssignableFrom(b.request.getClass());\n }\n\n @Override\n public Locale getLocale() {\n return isNotNoOps() ? b.request.getLocale() : b.locales.iterator().hasNext() ? b.locales.iterator().next() : Locale.getDefault();\n }\n\n @Override\n public AtmosphereResource resource() {\n try {\n Object o = getAttribute(FrameworkConfig.ATMOSPHERE_RESOURCE);\n if (!(o instanceof AtmosphereResource)) {\n // WebSphere is in trouble.\n return null;\n }\n return (AtmosphereResource) getAttribute(FrameworkConfig.ATMOSPHERE_RESOURCE);\n } catch (Exception ex) {\n logger.warn(\"\", ex);\n return null;\n }\n }\n\n @Override\n public Enumeration getLocales() {\n return isNotNoOps() ? b.request.getLocales() : Collections.enumeration(b.locales);\n }\n\n @Override\n public boolean dispatchRequestAsynchronously() {\n return b.dispatchRequestAsynchronously;\n }\n\n @Override\n public boolean isDestroyable() {\n return b.destroyable;\n }\n\n @Override\n public AtmosphereRequest pathInfo(String pathInfo) {\n b.pathInfo = pathInfo;\n return this;\n }\n\n @Override\n public Enumeration getAttributeNames() {\n Set l = new HashSet<>(b.localAttributes.unmodifiableMap().keySet());\n\n if (isNotNoOps()) {\n synchronized (b.request) {\n l.addAll(Collections.list(b.request.getAttributeNames()));\n }\n }\n return Collections.enumeration(l);\n }\n\n private static Object attributeWithoutException(HttpServletRequest request, String attribute) {\n try {\n return request.getAttribute(attribute);\n } catch (NullPointerException ex) {\n // https://github.com/Atmosphere/atmosphere/issues/1732\n logger.trace(\"Unexpected NPE\", ex);\n return \"\";\n }\n }\n\n @Override\n public LocalAttributes localAttributes() {\n return b.localAttributes;\n }\n\n @Override\n public String getCharacterEncoding() {\n return b.request.getCharacterEncoding() == null ? b.encoding : b.request.getCharacterEncoding();\n }\n\n @Override\n public int getContentLength() {\n if (b.contentLength == null) {\n return b.request.getContentLength();\n } else {\n return b.contentLength.intValue();\n }\n }\n\n @Override\n public String uuid() {\n if (Objects.equals(uuid, \"0\")) {\n this.uuid = resource() != null ? resource().uuid() : \"0\";\n }\n return uuid;\n }\n\n @Override\n public void destroy() {\n destroy(b.destroyable);\n }\n\n @Override\n public void destroy(boolean force) {\n if (!force) return;\n destroyed.set(true);\n b.localAttributes.clear();\n if (bis != null) {\n try {\n bis.close();\n } catch (IOException e) {\n }\n }\n\n if (br != null) {\n try {\n br.close();\n } catch (IOException e) {\n }\n }\n\n b.headers.clear();\n b.queryStrings.clear();\n }\n\n @Override\n public void setRequest(ServletRequest request) {\n super.setRequest(request);\n if (HttpServletRequest.class.isAssignableFrom(request.getClass())) {\n b.request = (HttpServletRequest) request;\n }\n }\n\n public final static class Builder implements AtmosphereRequest.Builder {\n private final static Body NULL_BODY = new Body(null, null, 0, 0);\n private HttpServletRequest request;\n private String pathInfo = \"\";\n private String encoding = \"UTF-8\";\n private String methodType;\n private String contentType;\n private boolean noContentType;\n private Long contentLength;\n private Map headers = Collections.synchronizedMap(new HashMap<>());\n private Map queryStrings = Collections.synchronizedMap(new HashMap<>());\n private String servletPath = \"\";\n private String requestURI;\n private String requestURL;\n private InputStream inputStream;\n private Reader reader;\n private String remoteAddr = \"\";\n private String remoteHost = \"\";\n private int remotePort;\n private String localAddr = \"\";\n private String localName = \"\";\n private int localPort;\n private boolean dispatchRequestAsynchronously;\n private boolean destroyable = true;\n private Set cookies = Collections.synchronizedSet(new HashSet<>());\n private final Set locales = Collections.synchronizedSet(new HashSet<>());\n private Principal principal;\n private String authType;\n private String contextPath = \"\";\n private String serverName = \"\";\n private int serverPort;\n private HttpSession webSocketFakeSession;\n private String queryString = \"\";\n private boolean isSecure;\n // Callable to lazily execute.\n private LazyComputation lazyRemote;\n private LazyComputation lazyLocal;\n public Body body;\n private LocalAttributes localAttributes = new LocalAttributes();\n\n public Builder() {\n }\n\n @Override\n public Builder destroyable(boolean destroyable) {\n this.destroyable = destroyable;\n return this;\n }\n\n @Override\n public Builder headers(Map headers) {\n this.headers = Collections.synchronizedMap(headers);\n return this;\n }\n\n @Override\n public Builder cookies(Set cookies) {\n this.cookies = cookies;\n return this;\n }\n\n @Override\n public Builder dispatchRequestAsynchronously(boolean dispatchRequestAsynchronously) {\n this.dispatchRequestAsynchronously = dispatchRequestAsynchronously;\n return this;\n }\n\n @Override\n public Builder remoteAddr(String remoteAddr) {\n this.remoteAddr = remoteAddr;\n return this;\n }\n\n @Override\n public Builder remoteHost(String remoteHost) {\n this.remoteHost = remoteHost;\n return this;\n }\n\n @Override\n public Builder remotePort(int remotePort) {\n this.remotePort = remotePort;\n return this;\n }\n\n @Override\n public Builder localAddr(String localAddr) {\n this.localAddr = localAddr;\n return this;\n }\n\n @Override\n public Builder localName(String localName) {\n this.localName = localName;\n return this;\n }\n\n @Override\n public Builder localPort(int localPort) {\n this.localPort = localPort;\n return this;\n }\n\n @Override\n public Builder remoteInetSocketAddress(Callable remoteAddr) {\n this.lazyRemote = new LazyComputation(remoteAddr);\n return this;\n }\n\n @Override\n public Builder localInetSocketAddress(Callable localAddr) {\n this.lazyLocal = new LazyComputation(localAddr);\n return this;\n }\n\n @Override\n public Builder attributes(Map attributes) {\n localAttributes = new LocalAttributes(attributes);\n return this;\n }\n\n @Override\n public Builder request(HttpServletRequest request) {\n this.request = request;\n return this;\n }\n\n @Override\n public Builder servletPath(String servletPath) {\n this.servletPath = servletPath;\n return this;\n }\n\n @Override\n public Builder requestURI(String requestURI) {\n this.requestURI = requestURI;\n return this;\n }\n\n @Override\n public Builder requestURL(String requestURL) {\n this.requestURL = requestURL;\n return this;\n }\n\n @Override\n public Builder pathInfo(String pathInfo) {\n this.pathInfo = pathInfo;\n return this;\n }\n\n @Override\n public Builder queryString(String queryString) {\n this.queryString = queryString;\n return this;\n }\n\n @Override\n public Builder body(byte[] dataBytes) {\n return body(dataBytes, 0, dataBytes.length);\n }\n\n @Override\n public Builder body(byte[] dataBytes, int offset, int length) {\n this.body = new Body(null, dataBytes, offset, length);\n return this;\n }\n\n @Override\n public Builder encoding(String encoding) {\n this.encoding = encoding;\n return this;\n }\n\n @Override\n public Builder method(String methodType) {\n this.methodType = methodType;\n return this;\n }\n\n @Override\n public Builder contentType(String contentType) {\n this.contentType = contentType;\n if (contentType == null) {\n noContentType = true;\n }\n return this;\n }\n\n @Override\n public Builder contentLength(Long contentLength) {\n this.contentLength = contentLength;\n return this;\n }\n\n @Override\n public Builder body(String data) {\n this.body = new Body(data, null, 0, 0);\n return this;\n }\n\n @Override\n public Builder inputStream(InputStream inputStream) {\n this.inputStream = inputStream;\n return this;\n }\n\n @Override\n public Builder reader(Reader reader) {\n this.reader = reader;\n return this;\n }\n\n @Override\n public AtmosphereRequest build() {\n if (body == null) {\n body = NULL_BODY;\n }\n return new AtmosphereRequestImpl(this);\n }\n\n @Override\n public Builder queryStrings(Map queryStrings) {\n this.queryStrings = Collections.synchronizedMap(queryStrings);\n return this;\n }\n\n @Override\n public Builder contextPath(String contextPath) {\n this.contextPath = contextPath == null ? \"\" : contextPath;\n return this;\n }\n\n @Override\n public Builder serverName(String serverName) {\n this.serverName = serverName;\n return this;\n }\n\n @Override\n public Builder serverPort(int serverPort) {\n this.serverPort = serverPort;\n return this;\n }\n\n @Override\n public Builder session(HttpSession session) {\n if (request == null) {\n request = new NoOpsRequest();\n }\n\n if (NoOpsRequest.class.isAssignableFrom(request.getClass())) {\n ((NoOpsRequest) request).fake = session;\n } else {\n webSocketFakeSession = session;\n }\n return this;\n }\n\n @Override\n public Builder principal(Principal principal) {\n this.principal = principal;\n return this;\n }\n\n @Override\n public Builder authType(String authType) {\n this.authType = authType;\n return this;\n }\n\n @Override\n public Builder isSSecure(boolean isSecure) {\n this.isSecure = isSecure;\n return this;\n }\n\n @Override\n public Builder locale(Locale locale) {\n locales.add(locale);\n return this;\n }\n\n @Override\n public Builder userPrincipal(Principal userPrincipal) {\n this.principal = userPrincipal;\n return this;\n }\n }\n\n public final static class Body {\n private final String data;\n private final byte[] dataBytes;\n private final int offset;\n private final int length;\n private final boolean isEmpty;\n\n public Body(String data, byte[] dataBytes, int offset, int length) {\n this.data = data;\n this.dataBytes = dataBytes;\n this.offset = offset;\n this.length = length;\n isEmpty = data == null && dataBytes == null;\n }\n\n /**\n * True is the body is a String\n *\n * @return True is the body is a String\n */\n public boolean hasString() {\n return data != null;\n }\n\n /**\n * True is the body is a byte array\n *\n * @return True is the body is a byte array\n */\n public boolean hasBytes() {\n return dataBytes != null;\n }\n\n /**\n * Return the request body as a String. If the body was a byte array, this method will return null.\n *\n * @return the request body as a String. If the body was a byte array, this method will return null.\n */\n public String asString() {\n return data;\n }\n\n /**\n * Return the request body as a byte array. If the body was String, this method will return null.\n *\n * @return the request body as a byte array. If the body was String, this method will return null.\n */\n public byte[] asBytes() {\n return dataBytes;\n }\n\n /**\n * The {@link #asBytes()} offset\n *\n * @return The {@link #asBytes()} offset\n */\n public int byteOffset() {\n return offset;\n }\n\n /**\n * The {@link #asBytes()} length\n *\n * @return The {@link #asBytes()} length\n */\n public int byteLength() {\n return length;\n }\n\n /**\n * True if this object is empty\n *\n * @return True if this object is empty\n */\n public boolean isEmpty() {\n return isEmpty;\n }\n }\n\n private final static class IS extends ServletInputStream {\n\n private final InputStream innerStream;\n\n public IS(InputStream innerStream) {\n super();\n this.innerStream = innerStream;\n }\n\n public int read() throws java.io.IOException {\n return innerStream.read();\n }\n\n public int read(byte[] bytes) throws java.io.IOException {\n return innerStream.read(bytes);\n }\n\n public int read(byte[] bytes, int i, int i1) throws java.io.IOException {\n return innerStream.read(bytes, i, i1);\n }\n\n\n public long skip(long l) throws java.io.IOException {\n return innerStream.skip(l);\n }\n\n public int available() throws java.io.IOException {\n return innerStream.available();\n }\n\n public void close() throws java.io.IOException {\n innerStream.close();\n }\n\n public synchronized void mark(int i) {\n innerStream.mark(i);\n }\n\n public synchronized void reset() throws java.io.IOException {\n innerStream.reset();\n }\n\n public boolean markSupported() {\n return innerStream.markSupported();\n }\n }\n\n /**\n * Create an instance of this class without an associated {@link HttpServletRequest}.\n *\n * @return an instance of this class without an associated {@link HttpServletRequest}\n */\n public static AtmosphereRequest newInstance() {\n return new Builder().build();\n }\n\n /**\n * Wrap an {@link HttpServletRequest}.\n *\n * @param request {@link HttpServletRequest}\n * @return an {@link AtmosphereRequest}\n */\n public static AtmosphereRequest wrap(HttpServletRequest request) {\n // Do not rewrap.\n if (AtmosphereRequestImpl.class.isAssignableFrom(request.getClass())) {\n return (AtmosphereRequestImpl) request;\n }\n\n Builder b = new Builder();\n Enumeration e = request.getAttributeNames();\n String s;\n while (e.hasMoreElements()) {\n s = e.nextElement();\n b.localAttributes.put(s, attributeWithoutException(request, s));\n }\n return b.request(request).build();\n }\n\n\n /**\n * Copy the HttpServletRequest content inside an AtmosphereRequest. By default the returned AtmosphereRequest\n * is not destroyable.\n *\n * @param request {@link HttpServletRequest}\n * @return an {@link AtmosphereRequest}\n */\n public static AtmosphereRequest cloneRequest(HttpServletRequest request, boolean loadInMemory, boolean copySession, boolean isDestroyable, boolean createSession) {\n Builder b;\n HttpServletRequest r;\n\n Cookie[] cs = request.getCookies();\n Set hs = Collections.synchronizedSet(new HashSet<>());\n if (cs != null) {\n Collections.addAll(hs, cs);\n }\n\n boolean isWrapped = false;\n if (AtmosphereRequestImpl.class.isAssignableFrom(request.getClass())) {\n b = ((AtmosphereRequestImpl) request).b;\n isWrapped = true;\n } else {\n b = new Builder();\n b.request(request);\n }\n\n HttpSession session = request.getSession(false);\n if (copySession) {\n session = request.getSession(createSession);\n if (session != null) {\n session = new FakeHttpSession(session);\n } else {\n session = new FakeHttpSession(\"\", null, System.currentTimeMillis(), -1);\n }\n }\n\n b.servletPath(request.getServletPath())\n .pathInfo(request.getPathInfo())\n .contextPath(request.getContextPath())\n .requestURI(request.getRequestURI())\n .requestURL(request.getRequestURL().toString())\n .method(request.getMethod())\n .serverName(request.getServerName())\n .serverPort(request.getServerPort())\n .remoteAddr(request.getRemoteAddr())\n .remoteHost(request.getRemoteHost())\n .remotePort(request.getRemotePort())\n .destroyable(isDestroyable)\n .cookies(hs)\n .session(session)\n .principal(request.getUserPrincipal())\n .authType(request.getAuthType())\n .isSSecure(request.isSecure());\n\n if (loadInMemory) {\n String s = (String) attributeWithoutException(request, FrameworkConfig.THROW_EXCEPTION_ON_CLONED_REQUEST);\n boolean throwException = Boolean.parseBoolean(s);\n r = new NoOpsRequest(throwException);\n if (isWrapped) {\n load(b.request, b);\n } else {\n load(request, b);\n }\n b.request(r);\n }\n\n return isWrapped ? (AtmosphereRequestImpl) request : b.build();\n }\n\n public final static class NoOpsRequest implements HttpServletRequest {\n\n private final boolean throwExceptionOnCloned;\n public HttpSession fake;\n private final static Enumeration EMPTY_ENUM_STRING = Collections.enumeration(Collections.emptyList());\n private final static Enumeration EMPTY_ENUM_LOCALE = Collections.enumeration(Collections.emptyList());\n private final static List EMPTY_ENUM_PART = Collections.emptyList();\n private final static Map EMPTY_MAP_STRING = Collections.emptyMap();\n private final static String[] EMPTY_ARRAY = new String[0];\n private final StringBuffer EMPTY_STRING_BUFFER = new StringBuffer();\n private final static Cookie[] EMPTY_COOKIE = new Cookie[0];\n private volatile BufferedReader voidReader;\n private final ServletInputStream voidStream = new AtmosphereRequestImpl.IS(new ByteArrayInputStream(new byte[0]));\n\n public NoOpsRequest() {\n this.throwExceptionOnCloned = false;\n }\n\n public NoOpsRequest(boolean throwExceptionOnCloned) {\n this.throwExceptionOnCloned = throwExceptionOnCloned;\n }\n\n private BufferedReader getVoidReader() {\n if (voidReader == null) {\n voidReader = new BufferedReader(new StringReader(\"\"));\n }\n return voidReader;\n }\n\n @Override\n public boolean authenticate(HttpServletResponse response) {\n return false;\n }\n\n @Override\n public String getAuthType() {\n return null;\n }\n\n @Override\n public String getContextPath() {\n return \"\";\n }\n\n @Override\n public Cookie[] getCookies() {\n return EMPTY_COOKIE;\n }\n\n @Override\n public long getDateHeader(String name) {\n return 0;\n }\n\n @Override\n public String getHeader(String name) {\n return null;\n }\n\n @Override\n public Enumeration getHeaderNames() {\n return EMPTY_ENUM_STRING;\n }\n\n @Override\n public Enumeration getHeaders(String name) {\n return EMPTY_ENUM_STRING;\n }\n\n @Override\n public int getIntHeader(String name) {\n return 0;\n }\n\n @Override\n public String getMethod() {\n return \"GET\";\n }\n\n @Override\n public Part getPart(String name) throws IOException, ServletException {\n return null;\n }\n\n @Override\n public Collection getParts() throws IOException, ServletException {\n return EMPTY_ENUM_PART;\n }\n\n @Override\n public String getPathInfo() {\n return \"\";\n }\n\n @Override\n public String getPathTranslated() {\n return \"\";\n }\n\n @Override\n public String getQueryString() {\n return \"\";\n }\n\n @Override\n public String getRemoteUser() {\n return \"\";\n }\n\n @Override\n public String getRequestedSessionId() {\n return \"\";\n }\n\n @Override\n public String getRequestURI() {\n return \"/\";\n }\n\n @Override\n public StringBuffer getRequestURL() {\n return EMPTY_STRING_BUFFER;\n }\n\n @Override\n public String getServletPath() {\n return \"\";\n }\n\n @Override\n public HttpSession getSession() {\n return fake;\n }\n\n @Override\n public HttpSession getSession(boolean create) {\n if (create && fake == null) {\n fake = new FakeHttpSession(\"\", null, System.currentTimeMillis(), -1) {\n @Override\n public void invalidate() {\n fake = null;\n super.invalidate();\n }\n };\n }\n return fake;\n }\n\n @Override\n public Principal getUserPrincipal() {\n return null;\n }\n\n @Override\n public boolean isRequestedSessionIdFromCookie() {\n return false;\n }\n\n @Override\n public boolean isRequestedSessionIdFromUrl() {\n return false;\n }\n\n @Override\n public boolean isRequestedSessionIdFromURL() {\n return false;\n }\n\n @Override\n public boolean isRequestedSessionIdValid() {\n return false;\n }\n\n @Override\n public boolean isUserInRole(String role) {\n if (this.throwExceptionOnCloned) {\n throw new UnsupportedOperationException();\n }\n return false;\n }\n\n @Override\n public void login(String username, String password) throws ServletException {\n if (this.throwExceptionOnCloned) {\n throw new ServletException();\n }\n }\n\n @Override\n public void logout() throws ServletException {\n if (this.throwExceptionOnCloned) {\n throw new ServletException();\n }\n }\n\n @Override\n public AsyncContext getAsyncContext() {\n return null;\n }\n\n @Override\n public Object getAttribute(String name) {\n return null;\n }\n\n @Override\n public Enumeration getAttributeNames() {\n return EMPTY_ENUM_STRING;\n }\n\n @Override\n public String getCharacterEncoding() {\n return null;\n }\n\n @Override\n public int getContentLength() {\n return 0;\n }\n\n @Override\n public String getContentType() {\n return \"text/plain\";\n }\n\n @Override\n public DispatcherType getDispatcherType() {\n return DispatcherType.REQUEST;\n }\n\n @Override\n public ServletInputStream getInputStream() throws IOException {\n return voidStream;\n }\n\n @Override\n public Locale getLocale() {\n return null;\n }\n\n @Override\n public Enumeration getLocales() {\n return EMPTY_ENUM_LOCALE;\n }\n\n @Override\n public String getLocalName() {\n return null;\n }\n\n @Override\n public int getLocalPort() {\n return 0;\n }\n\n @Override\n public String getLocalAddr() {\n return \"\";\n }\n\n @Override\n public String getParameter(String name) {\n return \"\";\n }\n\n @Override\n public Map getParameterMap() {\n return EMPTY_MAP_STRING;\n }\n\n @Override\n public Enumeration getParameterNames() {\n return EMPTY_ENUM_STRING;\n }\n\n @Override\n public String[] getParameterValues(String name) {\n return EMPTY_ARRAY;\n }\n\n @Override\n public String getProtocol() {\n return \"HTTP/1.1\";\n }\n\n @Override\n public BufferedReader getReader() throws IOException {\n return getVoidReader();\n }\n\n @Override\n public String getRealPath(String path) {\n return path;\n }\n\n @Override\n public String getRemoteAddr() {\n return \"\";\n }\n\n @Override\n public String getRemoteHost() {\n return \"\";\n }\n\n @Override\n public int getRemotePort() {\n return 0;\n }\n\n @Override\n public RequestDispatcher getRequestDispatcher(String path) {\n return null;\n }\n\n @Override\n public String getScheme() {\n return \"ws\";\n }\n\n @Override\n public String getServerName() {\n return \"\";\n }\n\n @Override\n public int getServerPort() {\n return 0;\n }\n\n @Override\n public ServletContext getServletContext() {\n return null;\n }\n\n @Override\n public boolean isAsyncStarted() {\n return false;\n }\n\n @Override\n public boolean isAsyncSupported() {\n return true;\n }\n\n @Override\n public boolean isSecure() {\n return false;\n }\n\n @Override\n public void removeAttribute(String name) {\n\n }\n\n @Override\n public void setAttribute(String name, Object o) {\n\n }\n\n @Override\n public void setCharacterEncoding(String env) throws UnsupportedEncodingException {\n }\n\n @Override\n public AsyncContext startAsync() {\n return null;\n }\n\n @Override\n public AsyncContext startAsync(ServletRequest request, ServletResponse response) {\n return null;\n }\n }\n\n public static final class LazyComputation {\n\n private final Callable callable;\n private InetSocketAddress address;\n\n public LazyComputation(Callable callable) {\n this.callable = callable;\n }\n\n public InetSocketAddress address() {\n if (address == null) {\n try {\n address = callable.call();\n } catch (Exception e) {\n logger.warn(\"\", e);\n }\n\n // Falback\n if (address == null) {\n address = new InetSocketAddress(8080);\n }\n }\n return address;\n }\n\n public int getPort() {\n return address().getPort();\n }\n\n public String getHostAddress() {\n return address().getAddress().getHostAddress();\n }\n\n public String getHostName() {\n return address().getHostName();\n }\n\n }\n\n private boolean isCompletionAware() {\n return Boolean.parseBoolean(resource().getAtmosphereConfig()\n .getInitParameter(ApplicationConfig.RESPONSE_COMPLETION_AWARE));\n }\n\n private class CompletionAwareAsyncContext implements AsyncContext {\n private AsyncContext context;\n private CompletionAware callback;\n\n public CompletionAwareAsyncContext(AsyncContext context, CompletionAware callback) {\n this.context = context;\n this.callback = callback;\n }\n\n public void addListener(AsyncListener listener) throws IllegalStateException {\n context.addListener(listener);\n }\n\n public void addListener(AsyncListener listener, ServletRequest request, ServletResponse response) throws IllegalStateException {\n context.addListener(listener, request, response);\n }\n\n public void complete() {\n context.complete();\n callback.onComplete();\n }\n\n public T createListener(Class clazz) throws ServletException {\n return context.createListener(clazz);\n }\n\n public void dispatch() throws IllegalStateException {\n context.dispatch();\n }\n\n public void dispatch(ServletContext servletContext, String path) throws IllegalStateException {\n context.dispatch(servletContext, path);\n }\n\n public void dispatch(String path) throws IllegalStateException {\n context.dispatch(path);\n }\n\n public ServletRequest getRequest() {\n return context.getRequest();\n }\n\n public ServletResponse getResponse() {\n return context.getResponse();\n }\n\n public long getTimeout() {\n return context.getTimeout();\n }\n\n public boolean hasOriginalRequestAndResponse() {\n return context.hasOriginalRequestAndResponse();\n }\n\n public void setTimeout(long timeoutMilliseconds) throws IllegalStateException {\n context.setTimeout(timeoutMilliseconds);\n }\n\n public void start(Runnable run) {\n context.start(run);\n }\n\n }\n\n private class NoOpsAsyncContext implements AsyncContext {\n private final ServletRequest request;\n private final ServletResponse response;\n private long timeout;\n\n public NoOpsAsyncContext(ServletRequest request, ServletResponse response) {\n this.request = request;\n this.response = response;\n this.timeout = -1;\n }\n\n @Override\n public void addListener(AsyncListener listener) throws IllegalStateException {\n }\n\n @Override\n public void addListener(AsyncListener listener, ServletRequest request, ServletResponse response) throws IllegalStateException {\n }\n\n @Override\n public void complete() {\n }\n\n @Override\n public T createListener(Class clazz) throws ServletException {\n throw new ServletException(\"Not supported\");\n }\n\n @Override\n public void dispatch() throws IllegalStateException {\n }\n\n @Override\n public void dispatch(ServletContext servletContext, String path) throws IllegalStateException {\n }\n\n @Override\n public void dispatch(String path) throws IllegalStateException {\n }\n\n @Override\n public ServletRequest getRequest() {\n return request;\n }\n\n @Override\n public ServletResponse getResponse() {\n return response;\n }\n\n @Override\n public long getTimeout() {\n return timeout;\n }\n\n @Override\n public boolean hasOriginalRequestAndResponse() {\n return false;\n }\n\n @Override\n public void setTimeout(long timeout) throws IllegalStateException {\n this.timeout = timeout;\n }\n\n @Override\n public void start(Runnable run) {\n throw new RuntimeException(\"Not supported\");\n }\n }\n\n private static void load(HttpServletRequest request, Builder b) {\n Enumeration e = request.getHeaderNames();\n String s;\n while (e.hasMoreElements()) {\n s = e.nextElement();\n b.headers.put(s, request.getHeader(s));\n }\n synchronized (b.request) {\n e = request.getAttributeNames();\n }\n while (e.hasMoreElements()) {\n s = e.nextElement();\n b.localAttributes.put(s, attributeWithoutException(request, s));\n }\n\n e = request.getParameterNames();\n while (e.hasMoreElements()) {\n s = e.nextElement();\n b.queryStrings.put(s, request.getParameterValues(s));\n }\n b.queryString = request.getQueryString();\n\n Enumeration l = request.getLocales();\n while (l.hasMoreElements()) {\n b.locale(l.nextElement());\n }\n }\n\n @Override\n public String toString() {\n try {\n return \"AtmosphereRequest{\" +\n \" method=\" + getMethod() +\n \" contextPath=\" + getContextPath() +\n \" servletPath=\" + getServletPath() +\n \" pathInfo=\" + getPathInfo() +\n \" requestURI=\" + getRequestURI() +\n \" requestURL=\" + getRequestURL() +\n \" AtmosphereResource UUID=\" + (resource() != null ? resource().uuid() : \"\") +\n \" destroyable=\" + b.destroyable +\n '}';\n } catch (Exception e) {\n // Jetty error\n return \"AtmosphereRequest{\" +\n \" contextPath=\" + getContextPath() +\n \" servletPath=\" + getServletPath() +\n \" pathInfo=\" + getPathInfo() +\n \" requestURI=\" + getRequestURI() +\n \" destroyable=\" + b.destroyable +\n '}';\n\n }\n }\n\n @Override\n public String requestURL() {\n return b.requestURL;\n }\n}\n", "file_name": "AtmosphereRequestImpl.java", "human_label": "If dataBytes is equal to null,return false,otherwise return true.", "level": "class_runnable", "lineno": "1292", "name": "hasBytes", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[dataBytes]\" }", "package": "org.atmosphere.cpr", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "6367676c1a6d9265ec018220", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static String stripFilenameExtension(String path){\n if (path == null) {\n return null;\n }\n int extIndex=path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex=path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0,extIndex);\n}\n", "docstring": "/** \n * Strip the filename extension from the given path, e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,or null if none\n */\n", "end_lineno": "570", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *
      \n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
      \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
      \n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
      \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

      The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

      This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

      The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

      The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

      Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

      Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

      The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

      The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

      A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

      A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Return the path without the extension.", "level": "class_runnable", "lineno": "550", "name": "stripFilenameExtension", "oracle_context": "{ \"apis\" : \"[lastIndexOf, substring]\", \"classes\" : \"[]\", \"vars\" : \"[EXTENSION_SEPARATOR, FOLDER_SEPARATOR]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636766fe1a6d9265ec017838", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static char[] toPrimitive(final Character[] array){\n if (array == null) {\n return null;\n }\n else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result=new char[array.length];\n for (int i=0; i < array.length; i++) {\n result[i]=array[i].charValue();\n }\n return result;\n}\n", "docstring": "/** \n *

      Converts an array of object Characters to primitives.

      This method returns null for a null input array.

      \n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n", "end_lineno": "2532", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

      Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

      \n *\n *

      This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

      \n *\n *

      #ThreadSafe#

      \n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

      ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

      \n *\n *

      This constructor is public to permit tools that require a JavaBean instance\n * to operate.

      \n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

      \n *\n *

      This method can be used to initialize:

      \n *
      \n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

      Shallow clones an array returning a typecast result and handling\n * null.

      \n *\n *

      The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

      Produces a new array containing the elements between\n * the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n *

      The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

      \n *\n *
      \n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new long array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new int array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new short array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new char array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new byte array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new double array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new float array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new boolean array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

      Any multi-dimensional aspects of the arrays are ignored.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

      \n *\n *

      If the input array is null, 0 is returned.

      \n *\n *
      \n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
      \n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

      Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

      \n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      There is no special handling for multi-dimensional arrays.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given object in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

      Finds the index of the given object in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given object within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given object in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the object is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

      \n *\n *

      The method returns false if a null array\n * is passed in.

      \n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Characters to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Character to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive chars to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Longs to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Long to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive longs to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Integers to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Integer to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive ints to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Shorts to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Short to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive shorts to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Bytes to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Bytes to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive bytes to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Doubles to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Doubles to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive doubles to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Floats to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Floats to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive floats to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Booleans to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Booleans to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive booleans to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

      Checks if an array of Objects is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive longs is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive ints is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive shorts is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive chars is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive bytes is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive doubles is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive floats is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive booleans is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

      Checks if an array of Objects is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive longs is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive ints is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive shorts is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive chars is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive bytes is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive doubles is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive floats is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive booleans is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

      \n *\n *
      \n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
      \n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Return a string which is consist of the values of elements in the given array.If array is equal to null,return null,or return ArrayUtils.EMPTY_CHAR_ARRAY if the size of array is equal to zero.", "level": "self_contained", "lineno": "2512", "name": "toPrimitive", "oracle_context": "{ \"apis\" : \"[charValue, ArrayUtils]\", \"classes\" : \"[char[], ArrayUtils]\", \"vars\" : \"[length, EMPTY_CHAR_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636766fa1a6d9265ec01779c", "all_context": "{ \"class_level\" : \"import net.hasor.web.upload.util.MimeUtility;\\nimport java.io.UnsupportedEncodingException;\\nimport java.util.HashMap;\\nimport java.util.Locale;\\nimport java.util.Map;\\nchar[] chars;\\nint pos;\\nint len;\\nint i1;\\nint i2;\\nboolean lowerCaseNames;\\nParameterParser();\\ngetToken(boolean quoted);\\nisOneOf(char ch,char[] charray);\\nparseToken(char[] terminators);\\nparseQuotedToken(char[] terminators);\\nisLowerCaseNames();\\nsetLowerCaseNames(boolean b);\\nparse(String str,char[] separators);\\nparse(String str,char separator);\\nparse(char[] charArray,char separator);\\nparse(char[] charArray,int offset,int length,char separator);\\nhasChar();\\n\", \"repo_level\" : \"public interface MimeUtility {static String decodeText(String text);\\n }\\n\" }", "class_name": "ParameterParser", "code": "private String parseToken(final char[] terminators){\n char ch;\n i1=pos;\n i2=pos;\n while (hasChar()) {\n ch=chars[pos];\n if (isOneOf(ch,terminators)) {\n break;\n }\n i2++;\n pos++;\n }\n return getToken(false);\n}\n", "docstring": "/** \n * Parses out a token until any of the given terminators is encountered.\n * @param terminators the array of terminating characters. Any of these characters when encountered signify the end of the token\n * @return the token\n */\n", "end_lineno": "131", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.web.upload;\nimport net.hasor.web.upload.util.MimeUtility;\n\nimport java.io.UnsupportedEncodingException;\nimport java.util.HashMap;\nimport java.util.Locale;\nimport java.util.Map;\n\n/**\n * A simple parser intended to parse sequences of name/value pairs.\n *\n * Parameter values are expected to be enclosed in quotes if they\n * contain unsafe characters, such as '=' characters or separators.\n * Parameter values are optional and can be omitted.\n *\n *

      \n * param1 = value; param2 = \"anything goes; really\"; param3\n *

      \n *\n * @version $Id: ParameterParser.java 1565253 2014-02-06 13:48:16Z ggregory $\n */\nclass ParameterParser {\n /** String to be parsed. */\n private char[] chars = null;\n /** Current position in the string. */\n private int pos = 0;\n /** Maximum position in the string. */\n private int len = 0;\n /** Start of a token. */\n private int i1 = 0;\n /** End of a token. */\n private int i2 = 0;\n /** Whether names stored in the map should be converted to lower case. */\n private boolean lowerCaseNames = false;\n\n /** Default ParameterParser constructor. */\n public ParameterParser() {\n super();\n }\n\n /**\n * Are there any characters left to parse?\n * @return true if there are unparsed characters,\n * false otherwise.\n */\n private boolean hasChar() {\n return this.pos < this.len;\n }\n\n /**\n * A helper method to process the parsed token. This method removes\n * leading and trailing blanks as well as enclosing quotation marks,\n * when necessary.\n * @param quoted true if quotation marks are expected,\n * false otherwise.\n * @return the token\n */\n private String getToken(boolean quoted) {\n // Trim leading white spaces\n while ((i1 < i2) && (Character.isWhitespace(chars[i1]))) {\n i1++;\n }\n // Trim trailing white spaces\n while ((i2 > i1) && (Character.isWhitespace(chars[i2 - 1]))) {\n i2--;\n }\n // Strip away quotation marks if necessary\n if (quoted && ((i2 - i1) >= 2) && (chars[i1] == '\"') && (chars[i2 - 1] == '\"')) {\n i1++;\n i2--;\n }\n String result = null;\n if (i2 > i1) {\n result = new String(chars, i1, i2 - i1);\n }\n return result;\n }\n\n /**\n * Tests if the given character is present in the array of characters.\n * @param ch the character to test for presense in the array of characters\n * @param charray the array of characters to test against\n * @return true if the character is present in the array of\n * characters, false otherwise.\n */\n private boolean isOneOf(char ch, final char[] charray) {\n boolean result = false;\n for (char element : charray) {\n if (ch == element) {\n result = true;\n break;\n }\n }\n return result;\n }\n\n /**\n * Parses out a token until any of the given terminators is encountered.\n * @param terminators the array of terminating characters. Any of these characters when encountered signify the end of the token\n * @return the token\n */\n private String parseToken(final char[] terminators) {\n char ch;\n i1 = pos;\n i2 = pos;\n while (hasChar()) {\n ch = chars[pos];\n if (isOneOf(ch, terminators)) {\n break;\n }\n i2++;\n pos++;\n }\n return getToken(false);\n }\n\n /**\n * Parses out a token until any of the given terminators is encountered outside the quotation marks.\n * @param terminators the array of terminating characters. Any of these characters when encountered outside the quotation marks signify the end of the token\n * @return the token\n */\n private String parseQuotedToken(final char[] terminators) {\n char ch;\n i1 = pos;\n i2 = pos;\n boolean quoted = false;\n boolean charEscaped = false;\n while (hasChar()) {\n ch = chars[pos];\n if (!quoted && isOneOf(ch, terminators)) {\n break;\n }\n if (!charEscaped && ch == '\"') {\n quoted = !quoted;\n }\n charEscaped = (!charEscaped && ch == '\\\\');\n i2++;\n pos++;\n }\n return getToken(true);\n }\n\n /**\n * @return true if parameter names are to be converted to lower case when name/value pairs are parsed. Otherwise returns false\n */\n public boolean isLowerCaseNames() {\n return this.lowerCaseNames;\n }\n\n /**\n * Sets the flag if parameter names are to be converted to lower case when name/value pairs are parsed.\n * @param b true if parameter names are to be converted to lower case when name/value pairs are parsed.\n * false otherwise.\n */\n public void setLowerCaseNames(boolean b) {\n this.lowerCaseNames = b;\n }\n\n /**\n * Extracts a map of name/value pairs from the given string. Names are\n * expected to be unique. Multiple separators may be specified and\n * the earliest found in the input string is used.\n * @param str the string that contains a sequence of name/value pairs\n * @param separators the name/value pairs separators\n * @return a map of name/value pairs\n */\n public Map parse(final String str, char[] separators) {\n if (separators == null || separators.length == 0) {\n return new HashMap<>();\n }\n char separator = separators[0];\n if (str != null) {\n int idx = str.length();\n for (char separator2 : separators) {\n int tmp = str.indexOf(separator2);\n if (tmp != -1 && tmp < idx) {\n idx = tmp;\n separator = separator2;\n }\n }\n }\n return parse(str, separator);\n }\n\n /**\n * Extracts a map of name/value pairs from the given string. Names are expected to be unique.\n * @param str the string that contains a sequence of name/value pairs\n * @param separator the name/value pairs separator\n * @return a map of name/value pairs\n */\n public Map parse(final String str, char separator) {\n if (str == null) {\n return new HashMap<>();\n }\n return parse(str.toCharArray(), separator);\n }\n\n /**\n * Extracts a map of name/value pairs from the given array of characters. Names are expected to be unique.\n * @param charArray the array of characters that contains a sequence of name/value pairs\n * @param separator the name/value pairs separator\n * @return a map of name/value pairs\n */\n public Map parse(final char[] charArray, char separator) {\n if (charArray == null) {\n return new HashMap<>();\n }\n return parse(charArray, 0, charArray.length, separator);\n }\n\n /**\n * Extracts a map of name/value pairs from the given array of characters. Names are expected to be unique.\n *\n * @param charArray the array of characters that contains a sequence of\n * name/value pairs\n * @param offset - the initial offset.\n * @param length - the length.\n * @param separator the name/value pairs separator\n * @return a map of name/value pairs\n */\n public Map parse(final char[] charArray, int offset, int length, char separator) {\n if (charArray == null) {\n return new HashMap<>();\n }\n HashMap params = new HashMap<>();\n this.chars = charArray;\n this.pos = offset;\n this.len = length;\n String paramName = null;\n String paramValue = null;\n while (hasChar()) {\n paramName = parseToken(new char[] { '=', separator });\n paramValue = null;\n if (hasChar() && (charArray[pos] == '=')) {\n pos++; // skip '='\n paramValue = parseQuotedToken(new char[] { separator });\n if (paramValue != null) {\n try {\n paramValue = MimeUtility.decodeText(paramValue);\n } catch (UnsupportedEncodingException e) {\n // let's keep the original value in this case\n }\n }\n }\n if (hasChar() && (charArray[pos] == separator)) {\n pos++; // skip separator\n }\n if ((paramName != null) && (paramName.length() > 0)) {\n if (this.lowerCaseNames) {\n paramName = paramName.toLowerCase(Locale.ENGLISH);\n }\n params.put(paramName, paramValue);\n }\n }\n return params;\n }\n}", "file_name": "ParameterParser.java", "human_label": "Parses out a token until any of the given terminators is encountered and then return the token.", "level": "class_runnable", "lineno": "113", "name": "parseToken", "oracle_context": "{ \"apis\" : \"[hasChar, isOneOf, getToken]\", \"classes\" : \"[]\", \"vars\" : \"[i1, pos, i2, chars]\" }", "package": "net.hasor.web.upload", "project": "hasor-master" }, { "_id": "636767691a6d9265ec0181a7", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static String trimLeadingCharacter(String str,char leadingCharacter){\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb=new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n}\n", "docstring": "/** \n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n", "end_lineno": "270", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *
      \n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
      \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
      \n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
      \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

      The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

      This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

      The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

      The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

      Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

      Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

      The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

      The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

      A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

      A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Trim all the characters which are equal to the given character and appear at the beginning of the given string,and return the trimmed string.", "level": "class_runnable", "lineno": "255", "name": "trimLeadingCharacter", "oracle_context": "{ \"apis\" : \"[hasLength, length, charAt, deleteCharAt, toString]\", \"classes\" : \"[StringBuilder]\", \"vars\" : \"[]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636767041a6d9265ec01790f", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static Integer[] toObject(final int[] array){\n if (array == null) {\n return null;\n }\n else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result=new Integer[array.length];\n for (int i=0; i < array.length; i++) {\n result[i]=new Integer(array[i]);\n }\n return result;\n}\n", "docstring": "/** \n *

      Converts an array of primitive ints to objects.

      This method returns null for a null input array.

      \n * @param array an int array\n * @return an Integer array, null if null array input\n */\n", "end_lineno": "2712", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

      Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

      \n *\n *

      This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

      \n *\n *

      #ThreadSafe#

      \n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

      ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

      \n *\n *

      This constructor is public to permit tools that require a JavaBean instance\n * to operate.

      \n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

      \n *\n *

      This method can be used to initialize:

      \n *
      \n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

      Shallow clones an array returning a typecast result and handling\n * null.

      \n *\n *

      The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

      Produces a new array containing the elements between\n * the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n *

      The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

      \n *\n *
      \n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new long array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new int array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new short array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new char array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new byte array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new double array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new float array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new boolean array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

      Any multi-dimensional aspects of the arrays are ignored.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

      \n *\n *

      If the input array is null, 0 is returned.

      \n *\n *
      \n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
      \n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

      Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

      \n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      There is no special handling for multi-dimensional arrays.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given object in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

      Finds the index of the given object in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given object within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given object in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the object is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

      \n *\n *

      The method returns false if a null array\n * is passed in.

      \n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Characters to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Character to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive chars to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Longs to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Long to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive longs to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Integers to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Integer to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive ints to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Shorts to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Short to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive shorts to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Bytes to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Bytes to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive bytes to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Doubles to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Doubles to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive doubles to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Floats to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Floats to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive floats to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Booleans to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Booleans to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive booleans to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

      Checks if an array of Objects is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive longs is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive ints is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive shorts is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive chars is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive bytes is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive doubles is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive floats is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive booleans is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

      Checks if an array of Objects is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive longs is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive ints is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive shorts is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive chars is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive bytes is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive doubles is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive floats is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive booleans is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

      \n *\n *
      \n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
      \n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Return an array of Integer objects which are converted from an array of primitive ints.", "level": "class_runnable", "lineno": "2693", "name": "toObject", "oracle_context": "{ \"apis\" : \"[ArrayUtils]\", \"classes\" : \"[Integer[], ArrayUtils]\", \"vars\" : \"[length, EMPTY_INTEGER_OBJECT_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636766fa1a6d9265ec0177a4", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static Double[] toObject(final double[] array){\n if (array == null) {\n return null;\n }\n else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result=new Double[array.length];\n for (int i=0; i < array.length; i++) {\n result[i]=new Double(array[i]);\n }\n return result;\n}\n", "docstring": "/** \n *

      Converts an array of primitive doubles to objects.

      This method returns null for a null input array.

      \n * @param array a double array\n * @return a Double array, null if null array input\n */\n", "end_lineno": "2916", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

      Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

      \n *\n *

      This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

      \n *\n *

      #ThreadSafe#

      \n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

      ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

      \n *\n *

      This constructor is public to permit tools that require a JavaBean instance\n * to operate.

      \n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

      \n *\n *

      This method can be used to initialize:

      \n *
      \n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

      Shallow clones an array returning a typecast result and handling\n * null.

      \n *\n *

      The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

      Clones an array returning a typecast result and handling\n * null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

      Defensive programming technique to change a null\n * reference to an empty one.

      \n *\n *

      This method returns an empty array for a null input array.

      \n *\n *

      As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

      \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

      Produces a new array containing the elements between\n * the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n *

      The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

      \n *\n *
      \n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new long array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new int array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new short array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new char array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new byte array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new double array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new float array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

      Produces a new boolean array containing the elements\n * between the start and end indices.

      \n *\n *

      The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

      \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

      Any multi-dimensional aspects of the arrays are ignored.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

      Checks whether two arrays are the same length, treating\n * null arrays as length 0.

      \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

      \n *\n *

      If the input array is null, 0 is returned.

      \n *\n *
      \n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
      \n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

      Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

      \n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      There is no special handling for multi-dimensional arrays.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

      Reverses the order of the given array.

      \n *\n *

      This method does nothing for a null input array.

      \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given object in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

      Finds the index of the given object in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given object within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given object in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the object is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

      \n *\n *

      The method returns false if a null array\n * is passed in.

      \n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the index of the given value in the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

      Finds the index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

      \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Finds the last index of the given value within the array.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

      \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

      Finds the last index of the given value in the array starting at the given index.

      \n *\n *

      This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

      \n *\n *

      A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

      \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the value is in the given array.

      \n *\n *

      The method returns false if a null array is passed in.

      \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Characters to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Character to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive chars to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Longs to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Long to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive longs to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Integers to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Integer to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive ints to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Shorts to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Short to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive shorts to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Bytes to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Bytes to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive bytes to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Doubles to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Doubles to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive doubles to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Floats to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Floats to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive floats to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

      Converts an array of object Booleans to primitives.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of object Booleans to primitives handling null.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

      Converts an array of primitive booleans to objects.

      \n *\n *

      This method returns null for a null input array.

      \n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

      Checks if an array of Objects is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive longs is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive ints is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive shorts is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive chars is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive bytes is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive doubles is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive floats is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

      Checks if an array of primitive booleans is empty or null.

      \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

      Checks if an array of Objects is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive longs is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive ints is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive shorts is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive chars is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive bytes is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive doubles is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive floats is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Checks if an array of primitive booleans is not empty or not null.

      \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

      Adds all the elements of the given arrays into a new array.

      \n *

      The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

      \n *\n *
      \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
      \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

      \n *\n *
      \n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
      \n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

      Copies the given array and adds the given element at the end of the new array.

      \n *\n *

      The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
      \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

      Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

      \n *\n *
      \n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
      \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n *
      \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

      Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *
      \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
      \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

      Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

      \n *\n *

      This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

      \n *\n *

      If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

      \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Return an array of Double objects which are converted from an array of primitive doubles.", "level": "class_runnable", "lineno": "2897", "name": "toObject", "oracle_context": "{ \"apis\" : \"[ArrayUtils]\", \"classes\" : \"[Double[], ArrayUtils]\", \"vars\" : \"[length, EMPTY_DOUBLE_OBJECT_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636767461a6d9265ec017d0e", "all_context": "{ \"class_level\" : \"import org.jgrapht.alg.util.Pair;\\nimport java.util.*;\\nimport java.util.function.Function;\\nRandom rng;\\nList> lowerBounds;\\nList> upperBounds;\\nDistributor();\\nDistributor(long seed);\\nDistributor(Random rng);\\naddLowerBound(Function lowerBound);\\ncomputeLowerBounds(List keys);\\ncomputeUpperBounds(List keys);\\ncomputeSuffixSum(List bounds);\\ngetDistribution(List keys,int valueNum);\\naddUpperBound(Function upperBound);\\n\", \"repo_level\" : \"public interface Pair {public A getFirst();\\npublic B getSecond();\\npublic void setFirst(A f);\\npublic void setSecond(B s);\\npublic boolean hasElement(E e);\\npublic String toString();\\npublic boolean equals(Object o);\\npublic int hashCode();\\nstatic Pair of(A a,B b);\\n }\\n\" }", "class_name": "Distributor", "code": "private Pair,Long> computeSuffixSum(List bounds){\n List suffixSum=new ArrayList<>(Collections.nCopies(bounds.size(),0));\n long sum=0;\n for (int i=bounds.size() - 1; i >= 0; i--) {\n suffixSum.set(i,(int)Math.min(Integer.MAX_VALUE,sum));\n sum+=bounds.get(i);\n }\n return Pair.of(suffixSum,sum);\n}\n", "docstring": "/** \n * Computes a suffix sum of the {@code bounds}. Returns computed suffix sum and the sum of all elements in the {@code bounds list}.\n * @param bounds list of integers.\n * @return computed pair of suffix sum list and a sum of all elements.\n */\n", "end_lineno": "159", "file_content": "/*\n * (C) Copyright 2020-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.generate.netgen;\n\nimport org.jgrapht.alg.util.Pair;\n\nimport java.util.*;\nimport java.util.function.Function;\n\n/**\n * Distributes value units among keys given lower and upper bound constraints.\n *

      \n * Let's define a set of elements $\\{k_1, k_2, \\dots, k_n\\}$. For every element a set of lower\n * bounds $\\{l_1, l_2, \\dots, l_t\\}$ and upper bounds $\\{u_1, u_2, \\dots, u_p\\}$ is specified. The\n * problem is to randomly distribute a number of abstract value units $V$ among keys such that the\n * lower bound and upper bound constraints are satisfied. This class solves this problem.\n *\n * @param the element type.\n * @author Timofey Chudakov\n * @see NetworkGenerator\n */\npublic class Distributor\n{\n /**\n * Random number generator used by this distributor.\n */\n private final Random rng;\n /**\n * Lower bounds.\n */\n private final List> lowerBounds;\n /**\n * Upper bounds.\n */\n private final List> upperBounds;\n\n /**\n * Creates a Distributor using random seed.\n */\n public Distributor()\n {\n this(System.nanoTime());\n }\n\n /**\n * Creates a distributor using the specified {@code seed}.\n *\n * @param seed the seed for the random number generator.\n */\n public Distributor(long seed)\n {\n this(new Random(seed));\n }\n\n /**\n * Creates a distributor which uses the random number generatow {@code rng}.\n *\n * @param rng a random number generator to use.\n */\n public Distributor(Random rng)\n {\n this.rng = rng;\n this.lowerBounds = new ArrayList<>();\n this.upperBounds = new ArrayList<>();\n }\n\n /**\n * Adds an upper bounding function. This function must be defined for all keys.\n *\n * @param upperBound an upper bound function.\n */\n public void addUpperBound(Function upperBound)\n {\n this.upperBounds.add(upperBound);\n }\n\n /**\n * Adds a lower bound function. This function must be defined for all keys.\n *\n * @param lowerBound a lower bound function.\n */\n public void addLowerBound(Function lowerBound)\n {\n this.lowerBounds.add(lowerBound);\n }\n\n /**\n * Finds a maximum lower bound for every key.\n *\n * @param keys list of keys.\n * @return the computed key lower bounds.\n */\n private List computeLowerBounds(List keys)\n {\n List keyLowerBounds = new ArrayList<>(keys.size());\n for (K key : keys) {\n int lowerBound = 0;\n for (Function lowerBoundFunction : lowerBounds) {\n lowerBound = Math.max(lowerBound, lowerBoundFunction.apply(key));\n }\n keyLowerBounds.add(lowerBound);\n }\n\n return keyLowerBounds;\n }\n\n /**\n * Finds a minimum lower bound for every key.\n *\n * @param keys a list of keys.\n * @return the computed key upper bound.\n */\n private List computeUpperBounds(List keys)\n {\n List keyUpperBounds = new ArrayList<>(keys.size());\n for (K key : keys) {\n int upperBound = Integer.MAX_VALUE;\n for (Function upperBoundFunction : upperBounds) {\n upperBound = Math.min(upperBound, upperBoundFunction.apply(key));\n }\n keyUpperBounds.add(upperBound);\n }\n\n return keyUpperBounds;\n }\n\n /**\n * Computes a suffix sum of the {@code bounds}. Returns computed suffix sum and the sum of all\n * elements in the {@code bounds list}.\n *\n * @param bounds list of integers.\n * @return computed pair of suffix sum list and a sum of all elements.\n */\n private Pair, Long> computeSuffixSum(List bounds)\n {\n List suffixSum = new ArrayList<>(Collections.nCopies(bounds.size(), 0));\n long sum = 0;\n for (int i = bounds.size() - 1; i >= 0; i--) {\n suffixSum.set(i, (int) Math.min(Integer.MAX_VALUE, sum));\n sum += bounds.get(i);\n }\n\n return Pair.of(suffixSum, sum);\n }\n\n /**\n * Computes and returns a value distribution for the list of keys. The resulting distribution\n * will satisfy the (possibly empty) sets of lower and upper bound constraints. Distributed\n * values will be in the same order as the keys in the key list.\n *\n * @param keys the list of keys.\n * @param valueNum the number of abstract value units to distribute.\n * @return the computed value distribution.\n */\n public List getDistribution(List keys, final int valueNum)\n {\n List keyLowerBounds = computeLowerBounds(keys);\n List keyUpperBounds = computeUpperBounds(keys);\n\n Pair, Long> lbSufSumP = computeSuffixSum(keyLowerBounds);\n Pair, Long> ubSufSumP = computeSuffixSum(keyUpperBounds);\n\n List lbSufSum = lbSufSumP.getFirst();\n List ubSufSum = ubSufSumP.getFirst();\n\n long lbSum = lbSufSumP.getSecond();\n long ubSum = ubSufSumP.getSecond();\n\n if (lbSum > valueNum) {\n throw new IllegalArgumentException(\n \"Can't distribute values among keys: the sum of lower bounds is greater than the number of values\");\n } else if (ubSum < valueNum) {\n throw new IllegalArgumentException(\n \"Can't distribute values among keys: the sum of upper bounds is smaller than the number of values\");\n }\n\n int remainingValues = valueNum;\n List resultingDistribution = new ArrayList<>();\n for (int i = 0; i < keyLowerBounds.size(); i++) {\n int lowerBound = keyLowerBounds.get(i);\n int upperBound = keyUpperBounds.get(i);\n\n int valueNumUpperBound = remainingValues - lbSufSum.get(i);\n int valueNumLowerBound = remainingValues - ubSufSum.get(i);\n\n lowerBound = Math.max(lowerBound, valueNumLowerBound);\n upperBound = Math.min(upperBound, valueNumUpperBound);\n\n if (lowerBound > upperBound) {\n throw new IllegalArgumentException(\n \"Infeasible bound specified for the key: \" + keys.get(i));\n }\n\n int allocatedValues = rng.nextInt(upperBound - lowerBound + 1) + lowerBound;\n resultingDistribution.add(allocatedValues);\n remainingValues -= allocatedValues;\n }\n\n return resultingDistribution;\n }\n\n}\n", "file_name": "Distributor.java", "human_label": "Return a pair of the list of suffix sum and the sum of all elements of bounds.", "level": "project_runnable", "lineno": "142", "name": "computeSuffixSum", "oracle_context": "{ \"apis\" : \"[nCopies, size, set, min, get, of]\", \"classes\" : \"[List, Integer]\", \"vars\" : \"[MAX_VALUE]\" }", "package": "org.jgrapht.generate.netgen", "project": "jgrapht-master" }, { "_id": "636767491a6d9265ec017d90", "all_context": "{ \"class_level\" : \"ArrayUtil();\\nreverse(int[] arr,int from,int to);\\nswap(V[] arr,int i,int j);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtil", "code": "public static final void reverse(V[] arr,int from,int to){\n for (int i=from, j=to; i < j; ++i, --j) {\n swap(arr,i,j);\n }\n}\n", "docstring": "/** \n * Reverses the order of the elements in the specified range within the given array.\n * @param < V > the type of elements in the array\n * @param arr the array\n * @param from the index of the first element (inclusive) inside the range to reverse\n * @param to the index of the last element (inclusive) inside the range to reverse\n */\n", "end_lineno": "45", "file_content": "/*\n * (C) Copyright 2021-2021, by Hannes Wellmann and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.util;\n\n/**\n * Utility class to simplify handling of arrays.\n *\n * @author Hannes Wellmann\n *\n */\npublic class ArrayUtil\n{\n private ArrayUtil()\n { // static use only\n }\n\n /**\n * Reverses the order of the elements in the specified range within the given array.\n *\n * @param the type of elements in the array\n * @param arr the array\n * @param from the index of the first element (inclusive) inside the range to reverse\n * @param to the index of the last element (inclusive) inside the range to reverse\n */\n public static final void reverse(V[] arr, int from, int to)\n {\n for (int i = from, j = to; i < j; ++i, --j) {\n swap(arr, i, j);\n }\n }\n\n /**\n * Reverses the order of the elements in the specified range within the given array.\n *\n * @param arr the array\n * @param from the index of the first element (inclusive) inside the range to reverse\n * @param to the index of the last element (inclusive) inside the range to reverse\n */\n public static final void reverse(int[] arr, int from, int to)\n {\n for (int i = from, j = to; i < j; ++i, --j) {\n int tmp = arr[j];\n arr[j] = arr[i];\n arr[i] = tmp;\n }\n }\n\n /**\n * Swaps the two elements at the specified indices in the given array.\n *\n * @param the type of elements in the array\n * @param arr the array\n * @param i the index of the first element\n * @param j the index of the second element\n */\n public static final void swap(V[] arr, int i, int j)\n {\n V tmp = arr[j];\n arr[j] = arr[i];\n arr[i] = tmp;\n }\n}\n", "file_name": "ArrayUtil.java", "human_label": "Reverse the order of the given elements in the specified range.", "level": "class_runnable", "lineno": "32", "name": "reverse", "oracle_context": "{ \"apis\" : \"[swap]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "org.jgrapht.util", "project": "jgrapht-master" }, { "_id": "6367674a1a6d9265ec017da9", "all_context": "{ \"class_level\" : \"import org.jgrapht.alg.util.*;\\nimport java.util.*;\\nimport java.util.function.*;\\nListNodeImpl head;\\nint size;\\nint nextIndex;\\nListNodeImpl next;\\nListNodeImpl last;\\nint expectedModCount;\\nV value;\\nDoublyLinkedList list;\\nListNodeImpl next;\\nListNodeImpl prev;\\ntail();\\nsize();\\nclear();\\naddListNode(ListNodeImpl node);\\nmoveAllListNodes(DoublyLinkedList list);\\nremoveListNode(ListNodeImpl node);\\nlink(ListNodeImpl predecessor,ListNodeImpl successor);\\nlinkBefore(ListNodeImpl node,ListNodeImpl successor);\\nlinkLast(ListNodeImpl node);\\nlinkListIntoThisBefore(int index,DoublyLinkedList list);\\nunlink(ListNodeImpl node);\\naddNode(int index,ListNode node);\\naddNodeFirst(ListNode node);\\naddNodeLast(ListNode node);\\naddNodeBefore(ListNode node,ListNode successor);\\ngetFirstNode();\\ngetLastNode();\\ngetNode(int index);\\ngetNodeAt(int index);\\nindexOfNode(ListNode node);\\ncontainsNode(ListNode node);\\nremoveNode(ListNode node);\\nnodeOf(Object element);\\nlastNodeOf(Object element);\\nsearchNode(Supplier first,UnaryOperator next,Object element);\\naddElementFirst(E element);\\naddElementLast(E element);\\naddElementBeforeNode(ListNode successor,E element);\\nadd(int index,E element);\\nget(int index);\\nremove(int index);\\naddFirst(E e);\\naddLast(E e);\\nofferFirst(E e);\\nofferLast(E e);\\nremoveFirst();\\nremoveLast();\\npollFirst();\\npollLast();\\ngetFirst();\\ngetLast();\\npeekFirst();\\npeekLast();\\nremoveFirstOccurrence(Object o);\\nremoveLastOccurrence(Object o);\\noffer(E e);\\nremove();\\npoll();\\nelement();\\npeek();\\npush(E e);\\npop();\\ninvert();\\nmoveFrom(int index,DoublyLinkedList movedList);\\nappend(DoublyLinkedList movedList);\\nprepend(DoublyLinkedList movedList);\\ncircularIterator(E firstElement);\\nreverseCircularIterator(E firstElement);\\ndescendingIterator();\\niterator();\\nlistIterator();\\nlistIterator(int index);\\nlistIterator(E element);\\nnext();\\nnextNode();\\nprevious();\\npreviousNode();\\nListNodeIteratorImpl(int startIndex);\\nListNodeIteratorImpl(int startIndex,ListNodeImpl startNode);\\nhasNext();\\nhasPrevious();\\nnextIndex();\\npreviousIndex();\\nadd(E e);\\nset(E e);\\ncheckForComodification();\\nreverseIterator(ListNodeIterator listIterator);\\ngetValue();\\ngetNext();\\ngetPrev();\\nListNodeImpl(V value);\\ntoString();\\nisEmpty();\\n\", \"repo_level\" : \"\" }", "class_name": "DoublyLinkedList", "code": "private void moveAllListNodes(DoublyLinkedList list){\n for (ListNodeIteratorImpl it=list.new ListNodeIteratorImpl(0); it.hasNext(); ) {\n ListNodeImpl node=it.nextNode();\n assert node.list == list;\n node.list=this;\n }\n size+=list.size;\n list.size=0;\n modCount++;\n list.modCount++;\n}\n", "docstring": "/** \n * Atomically moves all {@link ListNode ListNodes} from {@code list} to this list as if eachnode was removed with {@link #removeListNode(ListNodeImpl)} from {@code list} andsubsequently added to this list by {@link #addListNode(ListNodeImpl)}.\n */\n", "end_lineno": "154", "file_content": "/*\n * (C) Copyright 2018-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.util;\n\nimport org.jgrapht.alg.util.*;\n\nimport java.util.*;\nimport java.util.function.*;\n\n/**\n * {@code DoublyLinkedList} implements a doubly linked {@link List} data structure, that exposes its\n * {@link ListNode ListNodes} where the data is stored in.\n *

      \n * An element holding {@code ListNode} can be removed or added to a {@code DoublyLinkedList} in\n * constant time O(1). Other methods that operate on {@code ListNodes} directly also have constant\n * runtime. This is also the case for methods that operate on the first(head) and last(tail) node or\n * element. Random access methods have a runtime O(n) that is linearly dependent on the size of the\n * {@code DoublyLinkedList}.\n *

      \n *

      \n * A {@code DoublyLinkedList} supports {@code null} elements but does not support\n * {@code null ListNodes}. This class is not thread safe and needs to be synchronized externally if\n * modified by concurrent threads.\n *

      \n *

      \n * The iterators over this list have a fail-fast behavior meaning that they throw a\n * {@link ConcurrentModificationException} after they detect a structural modification of the list,\n * that they're not responsible for.\n *

      \n *

      \n * This class is similar to {@link LinkedList}. The general difference is that the {@code ListNodes}\n * of this {@code List} are accessible and can be removed or added directly. To ensure the integrity\n * of the {@code List} nodes of this List have a reference to the List they belong to. This\n * increases the memory occupied by this list implementation compared to {@code LinkedList} for the\n * same elements. Instances of {@code LinkedList.Node} have three references each (the element, next\n * and previous), instances of {@code DoublyLinkedList.ListNode} have four (the element, next,\n * previous and the list).\n *

      \n *\n * @param the list element type\n * @author Timofey Chudakov\n * @author Hannes Wellmann\n */\npublic class DoublyLinkedList\n extends\n AbstractSequentialList\n implements\n Deque\n{\n /** The first element of the list, {@code null} if this list is empty. */\n private ListNodeImpl head = null;\n private int size;\n\n private ListNodeImpl tail()\n {\n return head.prev;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean isEmpty()\n {\n return head == null;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int size()\n {\n return size;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void clear()\n {\n if (!isEmpty()) {\n ListNodeImpl node = head;\n do {\n ListNodeImpl next = node.next;\n boolean removed = removeListNode(node); // clears all links of removed node\n assert removed;\n node = next;\n } while (node != head);\n\n head = null;\n assert size == 0;\n }\n }\n\n // internal modification methods\n\n /**\n * Adds the given {@link ListNode} to this {@code List}.\n *

      \n * Sets the {@code list} reference of {@code node} to this list, increases this lists\n * {@code size} and {@code modcount} by one.\n *

      \n * \n * @param node the node to add to this list\n * @throws IllegalArgumentException if {@code node} is already contained in this or another\n * {@code DoublyLinkedList}\n */\n private void addListNode(ListNodeImpl node)\n { // call this before any modification of this list is done\n if (node.list != null) {\n String list = (node.list == this) ? \"this\" : \"other\";\n throw new IllegalArgumentException(\n \"Node <\" + node + \"> already contained in \" + list + \" list\");\n }\n node.list = this;\n size++;\n modCount++;\n }\n\n /**\n * Atomically moves all {@link ListNode ListNodes} from {@code list} to this list as if each\n * node was removed with {@link #removeListNode(ListNodeImpl)} from {@code list} and\n * subsequently added to this list by {@link #addListNode(ListNodeImpl)}.\n */\n private void moveAllListNodes(DoublyLinkedList list)\n { // call this before any modification of this list is done\n\n for (ListNodeIteratorImpl it = list.new ListNodeIteratorImpl(0); it.hasNext();) {\n ListNodeImpl node = it.nextNode();\n assert node.list == list;\n node.list = this;\n }\n size += list.size;\n list.size = 0;\n modCount++;\n list.modCount++;\n }\n\n /**\n * Removes the given {@link ListNode} from this {@code List}, if it is contained in this\n * {@code List}.\n *

      \n * If {@code node} is contained in this list, sets the {@code list}, {@code next} and\n * {@code prev} reference of {@code node} to {@code null} decreases this list's {@code size} and\n * increases the {@code modcount} by one.\n *

      \n * \n * @param node the node to remove from this list\n * @return true if {@code node} was removed from this list, else false\n */\n private boolean removeListNode(ListNodeImpl node)\n { // call this before any modification of this list is done\n if (node.list == this) {\n\n node.list = null;\n node.next = null;\n node.prev = null;\n\n size--;\n modCount++;\n return true;\n }\n return false;\n }\n\n /**\n * Establishes the links between the given {@link ListNodeImpl nodes} in such a way that the\n * {@code predecessor} is linked before the {@code successor}.\n * \n * @param predecessor the first node linked before the other\n * @param successor the second node linked after the other\n */\n private void link(ListNodeImpl predecessor, ListNodeImpl successor)\n {\n predecessor.next = successor;\n successor.prev = predecessor;\n }\n\n /** Insert non null {@code node} before non null {@code successor} into the list. */\n private void linkBefore(ListNodeImpl node, ListNodeImpl successor)\n {\n addListNode(node);\n link(successor.prev, node);\n link(node, successor);\n }\n\n /** Insert non null {@code node} as last node into the list. */\n private void linkLast(ListNodeImpl node)\n {\n if (isEmpty()) { // node will be the first and only one\n addListNode(node);\n link(node, node); // self link\n head = node;\n } else {\n linkBefore(node, head);\n }\n }\n\n /** Insert non null {@code list} before node at {@code index} into the list. */\n private void linkListIntoThisBefore(int index, DoublyLinkedList list)\n {\n int previousSize = size;\n moveAllListNodes(list);\n\n // link list's node into this list\n if (previousSize == 0) {\n head = list.head; // head and tail already linked together\n } else {\n ListNodeImpl refNode = (index == previousSize) ? head : getNodeAt(index);\n\n ListNodeImpl listTail = list.tail();\n link(refNode.prev, list.head); // changes list.tail()\n link(listTail, refNode);\n\n if (index == 0) {\n head = list.head;\n }\n }\n // clear list but do not call list.clear(), since their nodes are still used\n list.head = null;\n }\n\n /** Remove the non null {@code node} from the list. */\n private boolean unlink(ListNodeImpl node)\n {\n ListNodeImpl prev = node.prev;\n ListNodeImpl next = node.next;\n if (removeListNode(node)) { // clears prev and next of node\n if (size == 0) {\n head = null;\n } else {\n // list is circular, don't have to worry about null values\n link(prev, next);\n\n if (head == node) {\n head = next;\n }\n }\n return true;\n }\n return false;\n }\n\n // ----------------------------------------------------------------------------\n // public modification and access methods\n\n // ListNode methods:\n // Base methods to access, add and remove nodes to/from this list.\n // Used by all public methods if possible\n\n /**\n * Inserts the specified {@link ListNode node} at the specified position in this list.\n *

      \n * This method has a linear runtime complexity O(n) that depends linearly on the distance of the\n * index to the nearest end. Adding {@code node} as first or last takes only constant time O(1).\n *

      \n * \n * @param index index at which the specified {@code node} is to be inserted\n * @param node the node to add\n * @throws IndexOutOfBoundsException if the index is out of range\n * ({@code index < 0 || index > size()})\n * @throws IllegalArgumentException if {@code node} is already part of this or another\n * {@code DoublyLinkedList}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public void addNode(int index, ListNode node)\n {\n ListNodeImpl nodeImpl = (ListNodeImpl) node;\n if (index == size) { // also true if this is empty\n linkLast(nodeImpl);\n } else {\n ListNodeImpl successor = index == 0 ? head : getNodeAt(index);\n linkBefore(nodeImpl, successor);\n if (head == successor) {\n head = nodeImpl;\n }\n }\n }\n\n /**\n * Inserts the specified {@link ListNode node} at the front of this list.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n * \n * @param node the node to add\n * @throws IllegalArgumentException if {@code node} is already part of this or another\n * {@code DoublyLinkedList}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public void addNodeFirst(ListNode node)\n {\n addNode(0, node);\n }\n\n /**\n * Inserts the specified {@link ListNode node} at the end of this list.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n * \n * @param node the node to add\n * @throws IllegalArgumentException if {@code node} is already part of this or another\n * {@code DoublyLinkedList}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public void addNodeLast(ListNode node)\n {\n addNode(size, node);\n }\n\n /**\n * Inserts the specified {@link ListNode node} before the specified {@code successor} in this\n * list.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n * \n * @param node the node to add\n * @param successor {@code ListNode} before which the {@code node} is inserted\n * @throws IllegalArgumentException if {@code node} is already contained in this or another\n * {@code DoublyLinkedList} or {@code successor} is not contained in this list\n * @throws NullPointerException if {@code successor} or {@code node} is {@code null}\n */\n public void addNodeBefore(ListNode node, ListNode successor)\n {\n ListNodeImpl successorImpl = (ListNodeImpl) successor;\n ListNodeImpl nodeImpl = (ListNodeImpl) node;\n\n if (successorImpl.list != this) {\n throw new IllegalArgumentException(\"Node <\" + successorImpl + \"> not in this list\");\n }\n linkBefore(nodeImpl, successorImpl);\n if (head == successorImpl) {\n head = nodeImpl;\n }\n }\n\n /**\n * Returns the first {@link ListNode node} of this list.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n * \n * @return the first {@code ListNode} of this list\n * @throws NoSuchElementException if this list is empty\n */\n public ListNode getFirstNode()\n {\n if (isEmpty()) {\n throw new NoSuchElementException();\n }\n return head;\n }\n\n /**\n * Returns the last {@link ListNode node} of this list.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n * \n * @return the last {@code ListNode} of this list\n * @throws NoSuchElementException if this list is empty\n */\n public ListNode getLastNode()\n {\n if (isEmpty()) {\n throw new NoSuchElementException();\n }\n return tail();\n }\n\n /**\n * Returns the {@link ListNode node} at the specified position in this list.\n *

      \n * This method has linear runtime complexity O(n).\n *

      \n * \n * @param index index of the {@code ListNode} to return\n * @return the {@code ListNode} at the specified position in this list\n * @throws IndexOutOfBoundsException if the index is out of range\n * ({@code index < 0 || index >= size()})\n */\n public ListNode getNode(int index)\n {\n return getNodeAt(index);\n }\n\n /**\n * Returns the {@link ListNodeImpl node} at the specified position in this list.\n * \n * @param index index of the {@code ListNodeImpl} to return\n * @return the {@code ListNode} at the specified position in this list\n * @throws IndexOutOfBoundsException if the index is out of range\n * ({@code index < 0 || index >= size()})\n */\n private ListNodeImpl getNodeAt(int index)\n {\n if (index < 0 || size <= index) {\n throw new IndexOutOfBoundsException(\"Index: \" + index);\n }\n ListNodeImpl node;\n if (index < size / 2) {\n node = head;\n for (int i = 0; i < index; i++) {\n node = node.next;\n }\n } else {\n node = tail();\n for (int i = size - 1; index < i; i--) {\n node = node.prev;\n }\n }\n return node;\n }\n\n /**\n * Returns the index of the specified {@link ListNode node} in this list, or -1 if this list\n * does not contain the {@code node}.\n *

      \n * More formally, returns the index {@code i} such that {@code node == getNode(i)}, or -1 if\n * there is no such index. Because a {@code ListNode} is contained in at most one list exactly\n * once, the returned index (if not -1) is the only occurrence of that {@code node}.\n *

      \n *

      \n * This method has linear runtime complexity O(n) to find {@code node} but returns in constant\n * time O(1) if {@code node} is not {@link #containsNode(ListNode) contained} in this list.\n *

      \n * \n * @param node the node to search for\n * @return the index of the specified {@code node} in this list, or -1 if this list does not\n * contain {@code node}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public int indexOfNode(ListNode node)\n {\n if (!containsNode(node)) {\n return -1;\n }\n ListNodeImpl current = head;\n for (int i = 0; i < size; i++) {\n if (current == node) {\n return i;\n }\n current = current.next;\n }\n // should never happen:\n throw new IllegalStateException(\"Node contained in list not found: \" + node);\n }\n\n /**\n * Returns true if this {@code DoublyLinkedList} contains the specified {@link ListNode}.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n * \n * @param node the node whose presence in this {@code DoublyLinkedList} is to be tested\n * @return true if this {@code DoublyLinkedList} contains the {@link ListNode}\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public boolean containsNode(ListNode node)\n {\n return ((ListNodeImpl) node).list == this;\n }\n\n /**\n * Removes the {@link ListNode node} from this list. Returns true if {@code node} was in this\n * list and is now removed. If {@code node} is not contained in this list, the list is left\n * unchanged.\n *

      \n * This method has constant runtime complexity O(1).\n *

      \n *\n * @param node the node to remove from this list\n * @return true if node was removed from this list\n * @throws NullPointerException if {@code node} is {@code null}\n */\n public boolean removeNode(ListNode node)\n {\n return unlink((ListNodeImpl) node);\n }\n\n /**\n * Returns the first {@link ListNode node} holding the specified {@code element} in this list.\n * More formally, returns the first {@code ListNode} such that\n * {@code Objects.equals(element, node.getValue())}, or {@code null} if there is no such node.\n *

      \n * This method has linear runtime complexity O(n).\n *

      \n * \n * @param element the element whose {@code ListNode} is to return\n * @return the first {@code ListNode} holding the {@code element} or null if no node was found\n */\n public ListNode nodeOf(Object element)\n {\n return searchNode(() -> head, n -> n.next, element).getFirst();\n }\n\n /**\n * Returns the last {@link ListNode node} holding the specified {@code element} in this list.\n * More formally, returns the last {@code ListNode} such that\n * {@code Objects.equals(element, node.getValue())}, or {@code null} if there is no such node.\n *

      \n * This method has linear runtime complexity O(n).\n *

      \n * \n * @param element the element whose {@code ListNode} is to return\n * @return the last {@code ListNode} holding the {@code element} or null if no node was found\n */\n public ListNode lastNodeOf(Object element)\n {\n return searchNode(this::tail, n -> n.prev, element).getFirst();\n }\n\n /**\n * Returns a {@link Pair} of the first encountered {@link ListNode} in this list, whose\n * {@code value} is equal to the given {@code element}, and its index. Or if this list does not\n * contain such node a Pair of {@code null} and {@code -1};\n *

      \n * The search starts at the node supplied by {@code first} and advances in the direction induced\n * by the specified {@code next} operator.\n *

      \n * \n * @param first supplier of the first node to check if this list is not empty\n * @param next {@code Function} to get from the current node the next node to check\n * @param element the element for that the first node with equal value is searched.\n * @return a {@link Pair} of the first encountered {@code ListNode} holding a {@code value}\n * equal to {@code element} and its index, or if no such node was found a\n * {@code Pair.of(null, -1)}\n */\n private Pair, Integer> searchNode(\n Supplier> first, UnaryOperator> next, Object element)\n {\n if (!isEmpty()) {\n int index = 0;\n ListNodeImpl firstNode = first.get();\n ListNodeImpl node = firstNode;\n do {\n if (Objects.equals(node.value, element)) {\n return Pair.of(node, index);\n }\n index++;\n node = next.apply(node);\n } while (node != firstNode);\n }\n return Pair.of(null, -1);\n }\n\n /**\n * Inserts the specified element at the front of this list. Returns the {@link ListNode}\n * allocated to store the {@code value}. The returned {@code ListNode} is the new head of the\n * list.\n *

      \n * This method is equivalent to {@link #addFirst(Object)} but returns the allocated\n * {@code ListNode}.\n *

      \n * \n * @param element the element to add\n * @return the {@code ListNode} allocated to store the {@code value}\n */\n public ListNode addElementFirst(E element)\n {\n ListNode node = new ListNodeImpl<>(element);\n addNode(0, node);\n return node;\n }\n\n /**\n * Inserts the specified element at the end of this list. Returns the {@link ListNode} allocated\n * to store the {@code value}. The returned {@code ListNode} is the new tail of the list.\n *

      \n * This method is equivalent to {@link #addLast(Object)} but returns the allocated\n * {@code ListNode}.\n *

      \n * \n * @param element the element to add\n * @return the {@code ListNode} allocated to store the {@code value}\n */\n public ListNode addElementLast(E element)\n {\n ListNode node = new ListNodeImpl<>(element);\n addNode(size, node);\n return node;\n }\n\n /**\n * Inserts the specified element before the specified {@link ListNode successor} in this list.\n * Returns the {@code ListNode} allocated to store the {@code value}.\n *\n * @param successor {@code ListNode} before which the node holding {@code value} is inserted\n * @param element the element to add\n * @return the {@code ListNode} allocated to store the {@code value}\n * @throws IllegalArgumentException if {@code successor} is not contained in this list\n * @throws NullPointerException if {@code successor} is {@code null}\n */\n public ListNode addElementBeforeNode(ListNode successor, E element)\n {\n ListNode node = new ListNodeImpl<>(element);\n addNodeBefore(node, successor);\n return node;\n }\n\n // List methods (shortcut for most commonly used methods to avoid iterator creation)\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void add(int index, E element)\n {\n if (index == size) { // also true if this is empty\n addElementLast(element);\n } else {\n addElementBeforeNode(getNode(index), element);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E get(int index)\n {\n return getNodeAt(index).value;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E remove(int index)\n {\n ListNode node = getNode(index);\n removeNode(node);\n return node.getValue();\n }\n\n // Deque methods\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void addFirst(E e)\n {\n addElementFirst(e);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void addLast(E e)\n {\n addElementLast(e);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean offerFirst(E e)\n {\n addElementFirst(e);\n return true;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean offerLast(E e)\n {\n addElementLast(e);\n return true;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E removeFirst()\n {\n if (isEmpty()) {\n throw new NoSuchElementException();\n }\n\n ListNode node = head;\n removeNode(node); // changes head\n return node.getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E removeLast()\n {\n if (isEmpty()) {\n throw new NoSuchElementException();\n }\n\n ListNode node = tail();\n removeNode(node); // changes tail\n return node.getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E pollFirst()\n {\n if (isEmpty()) {\n return null;\n }\n ListNode node = head;\n removeNode(node); // changes head\n return node.getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E pollLast()\n {\n if (isEmpty()) {\n return null;\n }\n ListNode node = tail();\n removeNode(node); // changes tail()\n return node.getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E getFirst()\n {\n return getFirstNode().getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E getLast()\n {\n return getLastNode().getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E peekFirst()\n {\n return isEmpty() ? null : getFirst();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E peekLast()\n {\n return isEmpty() ? null : getLast();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean removeFirstOccurrence(Object o)\n {\n ListNode node = nodeOf(o);\n if (node != null) {\n removeNode(node);\n return true;\n }\n return false;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean removeLastOccurrence(Object o)\n {\n ListNode node = lastNodeOf(o);\n if (node != null) {\n removeNode(node);\n return true;\n }\n return false;\n }\n\n // Queue methods\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean offer(E e)\n {\n return offerLast(e);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E remove()\n {\n return removeFirst();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E poll()\n {\n return pollFirst();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E element()\n {\n return getFirst();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E peek()\n {\n return peekFirst();\n }\n\n // Stack methods\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void push(E e)\n {\n addFirst(e);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public E pop()\n {\n return removeFirst();\n }\n\n // special bulk methods\n\n /**\n * Inverts the list. For instance, calling this method on the list $(a,b,c,\\dots,x,y,z)$ will\n * result in the list $(z,y,x,\\dots,c,b,a)$. This method does only pointer manipulation, meaning\n * that all the list nodes allocated for the previously added elements are valid after this\n * method finishes.\n */\n public void invert()\n {\n if (size < 2) {\n return;\n }\n ListNodeImpl newHead = tail();\n ListNodeImpl current = head;\n do {\n ListNodeImpl next = current.next;\n\n current.next = current.prev;\n current.prev = next;\n\n current = next;\n } while (current != head);\n head = newHead;\n ++modCount;\n }\n\n /**\n * Moves all {@link ListNode ListNodes} of the given {@code sourceList} to this list and inserts\n * them all before the node previously at the given position. All the {@code nodes} of\n * {@code movedList} are moved to this list. When this method terminates this list contains all\n * nodes of {@code movedList} and {@code movedList} is empty.\n *\n * @param index index of the first element of {@code list} in this {@code list} after it was\n * added\n * @param movedList the {@code DoublyLinkedList} to move to this one\n * @throws NullPointerException if {@code movedList} is {@code null}\n */\n public void moveFrom(int index, DoublyLinkedList movedList)\n {\n linkListIntoThisBefore(index, movedList);\n }\n\n /**\n * Appends the {@code movedList} to the end of this list. All the elements from\n * {@code movedList} are transferred to this list, i.e. the {@code list} is empty after calling\n * this method.\n *\n * @param movedList the {@code DoublyLinkedList} to append to this one\n * @throws NullPointerException if {@code movedList} is {@code null}\n */\n public void append(DoublyLinkedList movedList)\n {\n moveFrom(size, movedList);\n }\n\n /**\n * Prepends the {@code movedList} to the beginning of this list. All the elements from\n * {@code movedList} are transferred to this list, i.e. the {@code movedList} is empty after\n * calling this method.\n *\n * @param movedList the {@code DoublyLinkedList} to prepend to this one\n * @throws NullPointerException if {@code movedList} is {@code null}\n */\n public void prepend(DoublyLinkedList movedList)\n {\n moveFrom(0, movedList);\n }\n\n // ----------------------------------------------------------------------------\n // (List)Iterators\n\n /**\n * Returns a {@link NodeIterator} that starts at the first {@link ListNode} of this list that is\n * equal to the specified {@code firstElement}, iterates in forward direction over the end of\n * this list until the first node.\n *

      \n * The first call to {@link NodeIterator#nextNode()} returns the first {@code node} that holds a\n * value such that {@code Objects.equals(node.getValue, firstElement)} returns {@code true}. The\n * returned {@code NodeIterator} iterates in forward direction returning the respective next\n * element in subsequent calls to {@code next(Node)}. The returned iterator ignores the actual\n * bounds of this {@code DoublyLinkedList} and iterates until the node before the first one is\n * reached. Its {@link NodeIterator#hasNext() hasNext()} returns {@code false} if the next node\n * would be the first one.\n *

      \n * \n * @param firstElement the element equal to the first {@code next()}\n * @return a circular {@code NodeIterator} iterating forward from {@code firstElement}\n */\n public NodeIterator circularIterator(E firstElement)\n {\n ListNodeImpl startNode = (ListNodeImpl) nodeOf(firstElement);\n if (startNode == null) {\n throw new NoSuchElementException();\n }\n return new ListNodeIteratorImpl(0, startNode);\n }\n\n /**\n * Returns a {@link NodeIterator} that starts at the first {@link ListNode} of this list that is\n * equal to the specified {@code firstElement}, iterates in reverse direction over the end of\n * this list until the first node.\n *

      \n * The first call to {@link NodeIterator#nextNode()} returns the first {@code node} that holds a\n * value such that {@code Objects.equals(node.getValue, firstElement)} returns {@code true}. The\n * returned {@code NodeIterator} iterates in reverse direction returning the respective previous\n * element in subsequent calls to {@code next(Node)}. The returned iterator ignores the actual\n * bounds of this {@code DoublyLinkedList} and iterates until the node before the first one is\n * reached. Its {@link NodeIterator#hasNext() hasNext()} returns {@code false} if the next node\n * would be the first one.\n *

      \n * \n * @param firstElement the element equal to the first {@code next()}\n * @return a circular {@code NodeIterator} iterating backwards from {@code firstElement}\n */\n public NodeIterator reverseCircularIterator(E firstElement)\n {\n ListNodeImpl startNode = (ListNodeImpl) nodeOf(firstElement);\n if (startNode == null) {\n throw new NoSuchElementException();\n }\n return reverseIterator(new ListNodeIteratorImpl(size, startNode.next));\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public NodeIterator descendingIterator()\n {\n return reverseIterator(listIterator(size));\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public NodeIterator iterator()\n {\n return listIterator();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeIterator listIterator()\n {\n return listIterator(0);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeIterator listIterator(int index)\n {\n return new ListNodeIteratorImpl(index);\n }\n\n /**\n * Returns a {@link ListNodeIterator} over the elements in this list (in proper sequence)\n * starting with the first {@link ListNode} whose value is equal to the specified\n * {@code element}.\n *\n * @param element the first element to be returned from the list iterator (by a call to the\n * {@code next} method)\n * @return a list iterator over the elements in this list (in proper sequence)\n * @throws NoSuchElementException if {@code element} is not in the list\n */\n public ListNodeIterator listIterator(E element)\n {\n Pair, Integer> startPair = searchNode(() -> head, n -> n.next, element);\n ListNodeImpl startNode = startPair.getFirst();\n int startIndex = startPair.getSecond();\n if (startNode == null) {\n throw new NoSuchElementException();\n }\n return new ListNodeIteratorImpl(startIndex, startNode);\n }\n\n /**\n * An extension of the {@link Iterator} interface for {@link DoublyLinkedList DoublyLinkedLists}\n * exposing their {@link ListNode ListNodes}.\n *\n * @param the list element type\n */\n public interface NodeIterator\n extends\n Iterator\n {\n /**\n * {@inheritDoc}\n */\n @Override\n default E next()\n {\n return nextNode().getValue();\n }\n\n /**\n * Returns the next {@link ListNode} in the list and advances the cursor position.\n *\n * @return the next {@code ListNode}\n * @see ListIterator#next()\n */\n ListNode nextNode();\n\n }\n\n /**\n * An extension of the {@link ListIterator} interface for {@link DoublyLinkedList\n * DoublyLinkedLists} exposing their {@link ListNode ListNodes}.\n *\n * @param the list element type\n */\n public interface ListNodeIterator\n extends\n ListIterator,\n NodeIterator\n {\n /**\n * {@inheritDoc}\n */\n @Override\n default E next()\n {\n return nextNode().getValue();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n default E previous()\n {\n return previousNode().getValue();\n }\n\n /**\n * Returns the previous {@link ListNode} in the list and moves the cursor position\n * backwards.\n *\n * @return the previous {@code ListNode}\n * @see ListIterator#previous()\n */\n ListNode previousNode();\n\n }\n\n /**\n * An implementation of the {@link DoublyLinkedList.ListNodeIterator} interface.\n */\n private class ListNodeIteratorImpl\n implements\n ListNodeIterator\n {\n /** Index in this list of the ListNode returned next. */\n private int nextIndex;\n /** ListNode this iterator will return next. Null if this list is empty. */\n private ListNodeImpl next;\n /** ListNode this iterator returned last. */\n private ListNodeImpl last = null;\n\n /**\n * The number of modifications the list have had at the moment when this iterator was\n * created\n */\n private int expectedModCount = modCount;\n\n private ListNodeIteratorImpl(int startIndex)\n {\n this.nextIndex = startIndex;\n if (startIndex == size) {\n this.next = isEmpty() ? null : head;\n } else {\n this.next = getNodeAt(startIndex);\n }\n }\n\n private ListNodeIteratorImpl(int startIndex, ListNodeImpl startNode)\n {\n this.nextIndex = startIndex;\n this.next = startNode;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean hasNext()\n {\n return nextIndex < size;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean hasPrevious()\n {\n return nextIndex > 0;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int nextIndex()\n {\n return nextIndex;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int previousIndex()\n {\n return nextIndex - 1;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeImpl nextNode()\n {\n checkForComodification();\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n\n last = next;\n next = next.next;\n nextIndex++;\n return last;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNode previousNode()\n {\n checkForComodification();\n if (!hasPrevious()) {\n throw new NoSuchElementException();\n }\n\n last = next = next.prev;\n nextIndex--;\n return last;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void add(E e)\n {\n checkForComodification();\n\n if (nextIndex == size) {\n addElementLast(e); // sets head to new node of e if was empty\n if (size == 1) { // was empty\n next = head; // jump over head threshold, so cursor is at the end\n }\n } else {\n addElementBeforeNode(next, e);\n }\n last = null;\n nextIndex++;\n expectedModCount++;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void set(E e)\n {\n if (last == null) {\n throw new IllegalStateException();\n }\n checkForComodification();\n // replace node returned last with a new node holding e\n\n ListNode nextNode = last.next;\n boolean wasLast = last == tail();\n removeNode(last);\n if (wasLast) { // or the sole node\n last = (ListNodeImpl) addElementLast(e);\n } else {\n last = (ListNodeImpl) addElementBeforeNode(nextNode, e);\n }\n expectedModCount += 2; // because of unlink and add\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void remove()\n {\n if (last == null) {\n throw new IllegalStateException();\n }\n checkForComodification();\n\n ListNodeImpl lastsNext = last.next;\n removeNode(last);\n if (next == last) { // previousNode() called before\n // removed element after cursor (which would have been next)\n next = lastsNext;\n } else { // nextNode() called before\n // removed element before cursor (next is unaffected but the index decreases)\n nextIndex--;\n }\n last = null;\n expectedModCount++;\n }\n\n /**\n * Verifies that the list structure hasn't been changed since the iteration started\n */\n private void checkForComodification()\n {\n if (expectedModCount != modCount) {\n throw new ConcurrentModificationException();\n }\n }\n }\n\n /**\n * Returns a {@link NodeIterator} that iterates in reverse order, assuming the cursor of the\n * specified {@link ListNodeIterator} is behind the tail of the list.\n */\n private static NodeIterator reverseIterator(ListNodeIterator listIterator)\n {\n return new NodeIterator()\n {\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean hasNext()\n {\n return listIterator.hasPrevious();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNode nextNode()\n {\n return listIterator.previousNode();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void remove()\n {\n listIterator.remove();\n }\n };\n }\n\n /**\n * Container for the elements stored in a {@link DoublyLinkedList}.\n *

      \n * A {@link ListNode} is either contained exactly once in exactly one {@code DoublyLinkedList}\n * or contained in no {@code DoublyLinkedList}.\n *

      \n * \n * @param the type of the element stored in this node\n */\n public interface ListNode\n {\n /**\n * Returns the immutable value this {@code ListNode} contains.\n *\n * @return the value this list node contains\n */\n V getValue();\n\n /**\n * Returns the next node in the list structure with respect to this node\n *\n * @return the next node in the list structure with respect to this node\n */\n ListNode getNext();\n\n /**\n * Returns the previous node in the list structure with respect to this node\n *\n * @return the previous node in the list structure with respect to this node\n */\n ListNode getPrev();\n }\n\n /**\n * The default {@link ListNode} implementation that enables checks and enforcement of a single\n * container list policy.\n */\n private static class ListNodeImpl\n implements\n ListNode\n {\n private final V value;\n private DoublyLinkedList list = null;\n private ListNodeImpl next = null;\n private ListNodeImpl prev = null;\n\n /**\n * Creates new list node\n *\n * @param value the value this list node stores\n */\n ListNodeImpl(V value)\n {\n this.value = value;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n if (list == null) {\n return \" - \" + value + \" - \"; // not in a list\n } else {\n return prev.value + \" -> \" + value + \" -> \" + next.value;\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public V getValue()\n {\n return value;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeImpl getNext()\n {\n return next;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public ListNodeImpl getPrev()\n {\n return prev;\n }\n }\n}\n", "file_name": "DoublyLinkedList.java", "human_label": "Move the nodes of the given doubly linked list to a new list sequentially.", "level": "class_runnable", "lineno": "137", "name": "moveAllListNodes", "oracle_context": "{ \"apis\" : \"[hasNext, nextNode, ListNodeIteratorImpl, ListNodeImpl, size]\", \"classes\" : \"[ListNodeImpl]\", \"vars\" : \"[size, modCount]\" }", "package": "org.jgrapht.util", "project": "jgrapht-master" }, { "_id": "636767151a6d9265ec017b6b", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.List;\\nimport java.util.Locale;\\nString EMPTY;\\nint INDEX_NOT_FOUND;\\nint PAD_LIMIT;\\nchar[] escapes;\\nStringUtils();\\nisNotEmpty(String str);\\nisBlank(String str);\\nisNotBlank(String str);\\ntrim(String str);\\ntrimToNull(String str);\\ntrimToEmpty(String str);\\nstrip(String str);\\nstripToNull(String str);\\nstripToEmpty(String str);\\nstrip(String str,String stripChars);\\nstripStart(String str,String stripChars);\\nstripEnd(String str,String stripChars);\\nstripAll(String[] strs);\\nstripAll(String[] strs,String stripChars);\\nequals(String str1,String str2);\\nequalsIgnoreCase(String str1,String str2);\\nindexOf(String str,char searchChar);\\nindexOf(String str,char searchChar,int startPos);\\nindexOf(String str,String searchStr);\\nordinalIndexOf(String str,String searchStr,int ordinal);\\nordinalIndexOf(String str,String searchStr,int ordinal,boolean lastIndex);\\nindexOf(String str,String searchStr,int startPos);\\nindexOfIgnoreCase(String str,String searchStr);\\nindexOfIgnoreCase(String str,String searchStr,int startPos);\\nlastIndexOf(String str,char searchChar);\\nlastIndexOf(String str,char searchChar,int startPos);\\nlastIndexOf(String str,String searchStr);\\nlastOrdinalIndexOf(String str,String searchStr,int ordinal);\\nlastIndexOf(String str,String searchStr,int startPos);\\nlastIndexOfIgnoreCase(String str,String searchStr);\\nlastIndexOfIgnoreCase(String str,String searchStr,int startPos);\\ncontains(String str,char searchChar);\\ncontains(String str,String searchStr);\\ncontainsIgnoreCase(String str,String searchStr);\\nindexOfAny(String str,char[] searchChars);\\nindexOfAny(String str,String searchChars);\\ncontainsAny(String str,char[] searchChars);\\ncontainsAny(String str,String searchChars);\\nindexOfAnyBut(String str,char[] searchChars);\\nindexOfAnyBut(String str,String searchChars);\\ncontainsOnly(String str,char[] valid);\\ncontainsOnly(String str,String validChars);\\ncontainsNone(String str,char[] searchChars);\\ncontainsNone(String str,String invalidChars);\\nindexOfAny(String str,String[] searchStrs);\\nlastIndexOfAny(String str,String[] searchStrs);\\nsubstring(String str,int start);\\nsubstring(String str,int start,int end);\\nleft(String str,int len);\\nright(String str,int len);\\nmid(String str,int pos,int len);\\nsubstringBefore(String str,String separator);\\nsubstringAfter(String str,String separator);\\nsubstringBeforeLast(String str,String separator);\\nsubstringAfterLast(String str,String separator);\\nsubstringBetween(String str,String tag);\\nsubstringBetween(String str,String open,String close);\\nsubstringsBetween(String str,String open,String close);\\nsplitKeep(String str,char separatorChar);\\nsplitKeep(String str,String separatorStr);\\nsplit(String str);\\nsplit(String str,char separatorChar);\\nsplit(String str,String separatorChars);\\nsplit(String str,String separatorChars,int max);\\nsplitByWholeSeparator(String str,String separator);\\nsplitByWholeSeparator(String str,String separator,int max);\\nsplitByWholeSeparatorPreserveAllTokens(String str,String separator);\\nsplitByWholeSeparatorPreserveAllTokens(String str,String separator,int max);\\nsplitByWholeSeparatorWorker(String str,String separator,int max,boolean preserveAllTokens);\\nsplitPreserveAllTokens(String str);\\nsplitPreserveAllTokens(String str,char separatorChar);\\nsplitWorker(String str,char separatorChar,boolean preserveAllTokens);\\nsplitPreserveAllTokens(String str,String separatorChars);\\nsplitPreserveAllTokens(String str,String separatorChars,int max);\\nsplitWorker(String str,String separatorChars,int max,boolean preserveAllTokens);\\nsplitByCharacterType(String str);\\nsplitByCharacterTypeCamelCase(String str);\\nsplitByCharacterType(String str,boolean camelCase);\\njoin(Object[] array);\\njoin(Object[] array,char separator);\\njoin(Object[] array,char separator,int startIndex,int endIndex);\\njoin(Object[] array,String separator);\\njoin(Object[] array,String separator,int startIndex,int endIndex);\\ndeleteWhitespace(String str);\\nremoveStart(String str,String remove);\\nremoveStartIgnoreCase(String str,String remove);\\nremoveEnd(String str,String remove);\\nremoveEndIgnoreCase(String str,String remove);\\nremove(String str,String remove);\\nremove(String str,char remove);\\nreplaceOnce(String text,String searchString,String replacement);\\nreplace(String text,String searchString,String replacement);\\nreplace(String text,String searchString,String replacement,int max);\\nreplaceEach(String text,String[] searchList,String[] replacementList);\\nreplaceEachRepeatedly(String text,String[] searchList,String[] replacementList);\\nreplaceEach(String text,String[] searchList,String[] replacementList,boolean repeat,int timeToLive);\\nreplaceChars(String str,char searchChar,char replaceChar);\\nreplaceChars(String str,String searchChars,String replaceChars);\\noverlay(String str,String overlay,int start,int end);\\nchomp(String str);\\nchomp(String str,String separator);\\nchop(String str);\\nrepeat(char character,int repeat);\\nrepeat(String str,int repeat);\\nrepeat(String str,String separator,int repeat);\\npadding(int repeat,char padChar);\\nrightPad(String str,int size);\\nrightPad(String str,int size,char padChar);\\nrightPad(String str,int size,String padStr);\\nleftPad(String str,int size);\\nleftPad(String str,int size,char padChar);\\nleftPad(String str,int size,String padStr);\\nlength(String str);\\ncenter(String str,int size);\\ncenter(String str,int size,char padChar);\\ncenter(String str,int size,String padStr);\\nupperCase(String str);\\nupperCase(String str,Locale locale);\\nlowerCase(String str);\\nlowerCase(String str,Locale locale);\\ncapitalize(String str);\\nuncapitalize(String str);\\nswapCase(String str);\\ncountMatches(String str,String sub);\\nisAlpha(String str);\\nisAlphaSpace(String str);\\nisAlphanumeric(String str);\\nisAlphanumericSpace(String str);\\nisAsciiPrintable(String str);\\nisNumeric(String str);\\nisNumericSpace(String str);\\nisWhitespace(String str);\\nisAllLowerCase(String str);\\nisAllUpperCase(String str);\\ndefaultString(String str);\\ndefaultString(String str,String defaultStr);\\ndefaultIfBlank(String str,String defaultStr);\\ndefaultIfEmpty(String str,String defaultStr);\\nreverse(String str);\\nreverseDelimited(String str,char separatorChar);\\nabbreviate(String str,int maxWidth);\\nabbreviate(String str,int offset,int maxWidth);\\nabbreviateMiddle(String str,String middle,int length);\\ndifference(String str1,String str2);\\nindexOfDifference(String str1,String str2);\\nindexOfDifference(String[] strs);\\ngetCommonPrefix(String[] strs);\\ngetLevenshteinDistance(String s,String t);\\nstartsWith(String str,String prefix);\\nstartsWithIgnoreCase(String str,String prefix);\\nstartsWith(String str,String prefix,boolean ignoreCase);\\nstartsWithAny(String string,String[] searchStrings);\\nendsWith(String str,String suffix);\\nendsWithIgnoreCase(String str,String suffix);\\nendsWith(String str,String suffix,boolean ignoreCase);\\nnormalizeSpace(String str);\\nendsWithAny(String string,String[] searchStrings);\\nfirstCharToUpperCase(String value);\\nfirstCharToLowerCase(String value);\\nequalsBlankIgnoreCase(String str1,String str2);\\nquote(String input);\\nquote(Appendable buffer,String input);\\ntoString(Object object);\\nisEmpty(String str);\\n\", \"repo_level\" : \"\" }", "class_name": "StringUtils", "code": "private static boolean startsWith(final String str,final String prefix,final boolean ignoreCase){\n if (str == null || prefix == null) {\n return str == null && prefix == null;\n }\n if (prefix.length() > str.length()) {\n return false;\n }\n return str.regionMatches(ignoreCase,0,prefix,0,prefix.length());\n}\n", "docstring": "/** \n *

      Check if a String starts with a specified prefix (optionally case insensitive).

      \n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @param ignoreCase inidicates whether the compare should ignore case(case insensitive) or not.\n * @return true if the String starts with the prefix orboth null\n */\n", "end_lineno": "5838", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Locale;\n\n/**\n *

      Operations on {@link String} that are\n * null safe.

      \n *\n *
        \n *
      • IsEmpty/IsBlank\n * - checks if a String contains text
      • \n *
      • Trim/Strip\n * - removes leading and trailing whitespace
      • \n *
      • Equals\n * - compares two strings null-safe
      • \n *
      • startsWith\n * - check if a String starts with a prefix null-safe
      • \n *
      • endsWith\n * - check if a String ends with a suffix null-safe
      • \n *
      • IndexOf/LastIndexOf/Contains\n * - null-safe index-of checks\n *
      • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut\n * - index-of any of a set of Strings
      • \n *
      • ContainsOnly/ContainsNone/ContainsAny\n * - does String contains only/none/any of these characters
      • \n *
      • Substring/Left/Right/Mid\n * - null-safe substring extractions
      • \n *
      • SubstringBefore/SubstringAfter/SubstringBetween\n * - substring extraction relative to other strings
      • \n *
      • Split/Join\n * - splits a String into an array of substrings and vice versa
      • \n *
      • Remove/Delete\n * - removes part of a String
      • \n *
      • Replace/Overlay\n * - Searches a String and replaces one String with another
      • \n *
      • Chomp/Chop\n * - removes the last part of a String
      • \n *
      • LeftPad/RightPad/Center/Repeat\n * - pads a String
      • \n *
      • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize\n * - changes the case of a String
      • \n *
      • CountMatches\n * - counts the number of occurrences of one String in another
      • \n *
      • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable\n * - checks the characters in a String
      • \n *
      • DefaultString\n * - protects against a null input String
      • \n *
      • Reverse/ReverseDelimited\n * - reverses a String
      • \n *
      • Abbreviate\n * - abbreviates a string using ellipsis
      • \n *
      • Difference\n * - compares Strings and reports on their differences
      • \n *
      • LevensteinDistance\n * - the number of changes needed to change one String into another
      • \n *
      \n *\n *

      The StringUtils class defines certain words related to\n * String handling.

      \n *\n *
        \n *
      • null - null
      • \n *
      • empty - a zero-length string (\"\")
      • \n *
      • space - the space character (' ', char 32)
      • \n *
      • whitespace - the characters defined by {@link Character#isWhitespace(char)}
      • \n *
      • trim - the characters <= 32 as in {@link String#trim()}
      • \n *
      \n *\n *

      StringUtils handles null input Strings quietly.\n * That is to say that a null input will return null.\n * Where a boolean or int is being returned\n * details vary by method.

      \n *\n *

      A side effect of the null handling is that a\n * NullPointerException should be considered a bug in\n * StringUtils (except for deprecated methods).

      \n *\n *

      Methods in this class give sample code to explain their operation.\n * The symbol * is used to indicate any input including null.

      \n *\n *

      #ThreadSafe#

      \n * @see String\n * @author Apache Software Foundation\n * @author Apache Jakarta Turbine\n * @author Jon S. Stevens\n * @author Daniel L. Rall\n * @author Greg Coladonato\n * @author Ed Korthof\n * @author Rand McNeely\n * @author Fredrik Westermarck\n * @author Holger Krauth\n * @author Alexander Day Chaffee\n * @author Henning P. Schmiedehausen\n * @author Arun Mammen Thomas\n * @author Gary Gregory\n * @author Phil Steitz\n * @author Al Chou\n * @author Michael Davey\n * @author Reuben Sivan\n * @author Chris Hyzer\n * @author Scott Johnson\n * @since 1.0\n * @version $Id: StringUtils.java 1058365 2011-01-13 00:04:49Z niallp $\n */\n//@Immutable\npublic class StringUtils {\n // Performance testing notes (JDK 1.4, Jul03, scolebourne)\n // Whitespace:\n // Character.isWhitespace() is faster than WHITESPACE.indexOf()\n // where WHITESPACE is a string of all whitespace characters\n //\n // Character access:\n // String.charAt(n) versus toCharArray(), then array[n]\n // String.charAt(n) is about 15% worse for a 10K string\n // They are about equal for a length 50 string\n // String.charAt(n) is about 4 times better for a length 3 string\n // String.charAt(n) is best bet overall\n //\n // Append:\n // String.concat about twice as fast as StringBuffer.append\n // (not sure who tested this)\n /**\n * The empty String \"\".\n * @since 2.0\n */\n public static final String EMPTY = \"\";\n /**\n * Represents a failed index search.\n * @since 2.1\n */\n public static final int INDEX_NOT_FOUND = -1;\n /**\n *

      The maximum size to which the padding constant(s) can expand.

      \n */\n private static final int PAD_LIMIT = 8192;\n\n /**\n *

      StringUtils instances should NOT be constructed in\n * standard programming. Instead, the class should be used as\n * StringUtils.trim(\" foo \");.

      \n *\n *

      This constructor is public to permit tools that require a JavaBean\n * instance to operate.

      \n */\n public StringUtils() {\n super();\n }\n // Empty checks\n //-----------------------------------------------------------------------\n\n /**\n *

      Checks if a String is empty (\"\") or null.

      \n *\n *
      \n     * StringUtils.isEmpty(null)      = true\n     * StringUtils.isEmpty(\"\")        = true\n     * StringUtils.isEmpty(\" \")       = false\n     * StringUtils.isEmpty(\"bob\")     = false\n     * StringUtils.isEmpty(\"  bob  \") = false\n     * 
      \n *\n *

      NOTE: This method changed in Lang version 2.0.\n * It no longer trims the String.\n * That functionality is available in isBlank().

      \n *\n * @param str the String to check, may be null\n * @return true if the String is empty or null\n */\n public static boolean isEmpty(final String str) {\n return str == null || str.length() == 0;\n }\n\n /**\n *

      Checks if a String is not empty (\"\") and not null.

      \n *\n *
      \n     * StringUtils.isNotEmpty(null)      = false\n     * StringUtils.isNotEmpty(\"\")        = false\n     * StringUtils.isNotEmpty(\" \")       = true\n     * StringUtils.isNotEmpty(\"bob\")     = true\n     * StringUtils.isNotEmpty(\"  bob  \") = true\n     * 
      \n *\n * @param str the String to check, may be null\n * @return true if the String is not empty and not null\n */\n public static boolean isNotEmpty(final String str) {\n return !StringUtils.isEmpty(str);\n }\n\n /**\n *

      Checks if a String is whitespace, empty (\"\") or null.

      \n *\n *
      \n     * StringUtils.isBlank(null)      = true\n     * StringUtils.isBlank(\"\")        = true\n     * StringUtils.isBlank(\" \")       = true\n     * StringUtils.isBlank(\"bob\")     = false\n     * StringUtils.isBlank(\"  bob  \") = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @return true if the String is null, empty or whitespace\n * @since 2.0\n */\n public static boolean isBlank(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return true;\n }\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i)) == false) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

      Checks if a String is not empty (\"\"), not null and not whitespace only.

      \n *\n *
      \n     * StringUtils.isNotBlank(null)      = false\n     * StringUtils.isNotBlank(\"\")        = false\n     * StringUtils.isNotBlank(\" \")       = false\n     * StringUtils.isNotBlank(\"bob\")     = true\n     * StringUtils.isNotBlank(\"  bob  \") = true\n     * 
      \n *\n * @param str the String to check, may be null\n * @return true if the String is\n * not empty and not null and not whitespace\n * @since 2.0\n */\n public static boolean isNotBlank(final String str) {\n return !StringUtils.isBlank(str);\n }\n // Trim\n //-----------------------------------------------------------------------\n\n /**\n *

      Removes control characters (char <= 32) from both\n * ends of this String, handling null by returning\n * null.

      \n *\n *

      The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #strip(String)}.

      \n *\n *

      To trim your choice of characters, use the\n * {@link #strip(String, String)} methods.

      \n *\n *
      \n     * StringUtils.trim(null)          = null\n     * StringUtils.trim(\"\")            = \"\"\n     * StringUtils.trim(\"     \")       = \"\"\n     * StringUtils.trim(\"abc\")         = \"abc\"\n     * StringUtils.trim(\"    abc    \") = \"abc\"\n     * 
      \n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed string, null if null String input\n */\n public static String trim(final String str) {\n return str == null ? null : str.trim();\n }\n\n /**\n *

      Removes control characters (char <= 32) from both\n * ends of this String returning null if the String is\n * empty (\"\") after the trim or if it is null.\n *\n *

      The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #stripToNull(String)}.

      \n *\n *
      \n     * StringUtils.trimToNull(null)          = null\n     * StringUtils.trimToNull(\"\")            = null\n     * StringUtils.trimToNull(\"     \")       = null\n     * StringUtils.trimToNull(\"abc\")         = \"abc\"\n     * StringUtils.trimToNull(\"    abc    \") = \"abc\"\n     * 
      \n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed String,\n * null if only chars <= 32, empty or null String input\n * @since 2.0\n */\n public static String trimToNull(final String str) {\n String ts = StringUtils.trim(str);\n return StringUtils.isEmpty(ts) ? null : ts;\n }\n\n /**\n *

      Removes control characters (char <= 32) from both\n * ends of this String returning an empty String (\"\") if the String\n * is empty (\"\") after the trim or if it is null.\n *\n *

      The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #stripToEmpty(String)}.

      \n *\n *
      \n     * StringUtils.trimToEmpty(null)          = \"\"\n     * StringUtils.trimToEmpty(\"\")            = \"\"\n     * StringUtils.trimToEmpty(\"     \")       = \"\"\n     * StringUtils.trimToEmpty(\"abc\")         = \"abc\"\n     * StringUtils.trimToEmpty(\"    abc    \") = \"abc\"\n     * 
      \n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed String, or an empty String if null input\n * @since 2.0\n */\n public static String trimToEmpty(final String str) {\n return str == null ? StringUtils.EMPTY : str.trim();\n }\n // Stripping\n //-----------------------------------------------------------------------\n\n /**\n *

      Strips whitespace from the start and end of a String.

      \n *\n *

      This is similar to {@link #trim(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

      \n *\n *

      A null input String returns null.

      \n *\n *
      \n     * StringUtils.strip(null)     = null\n     * StringUtils.strip(\"\")       = \"\"\n     * StringUtils.strip(\"   \")    = \"\"\n     * StringUtils.strip(\"abc\")    = \"abc\"\n     * StringUtils.strip(\"  abc\")  = \"abc\"\n     * StringUtils.strip(\"abc  \")  = \"abc\"\n     * StringUtils.strip(\" abc \")  = \"abc\"\n     * StringUtils.strip(\" ab c \") = \"ab c\"\n     * 
      \n *\n * @param str the String to remove whitespace from, may be null\n * @return the stripped String, null if null String input\n */\n public static String strip(final String str) {\n return StringUtils.strip(str, null);\n }\n\n /**\n *

      Strips whitespace from the start and end of a String returning\n * null if the String is empty (\"\") after the strip.

      \n *\n *

      This is similar to {@link #trimToNull(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

      \n *\n *
      \n     * StringUtils.stripToNull(null)     = null\n     * StringUtils.stripToNull(\"\")       = null\n     * StringUtils.stripToNull(\"   \")    = null\n     * StringUtils.stripToNull(\"abc\")    = \"abc\"\n     * StringUtils.stripToNull(\"  abc\")  = \"abc\"\n     * StringUtils.stripToNull(\"abc  \")  = \"abc\"\n     * StringUtils.stripToNull(\" abc \")  = \"abc\"\n     * StringUtils.stripToNull(\" ab c \") = \"ab c\"\n     * 
      \n *\n * @param str the String to be stripped, may be null\n * @return the stripped String,\n * null if whitespace, empty or null String input\n * @since 2.0\n */\n public static String stripToNull(String str) {\n if (str == null) {\n return null;\n }\n str = StringUtils.strip(str, null);\n return str.length() == 0 ? null : str;\n }\n\n /**\n *

      Strips whitespace from the start and end of a String returning\n * an empty String if null input.

      \n *\n *

      This is similar to {@link #trimToEmpty(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

      \n *\n *
      \n     * StringUtils.stripToEmpty(null)     = \"\"\n     * StringUtils.stripToEmpty(\"\")       = \"\"\n     * StringUtils.stripToEmpty(\"   \")    = \"\"\n     * StringUtils.stripToEmpty(\"abc\")    = \"abc\"\n     * StringUtils.stripToEmpty(\"  abc\")  = \"abc\"\n     * StringUtils.stripToEmpty(\"abc  \")  = \"abc\"\n     * StringUtils.stripToEmpty(\" abc \")  = \"abc\"\n     * StringUtils.stripToEmpty(\" ab c \") = \"ab c\"\n     * 
      \n *\n * @param str the String to be stripped, may be null\n * @return the trimmed String, or an empty String if null input\n * @since 2.0\n */\n public static String stripToEmpty(final String str) {\n return str == null ? StringUtils.EMPTY : StringUtils.strip(str, null);\n }\n\n /**\n *

      Strips any of a set of characters from the start and end of a String.\n * This is similar to {@link String#trim()} but allows the characters\n * to be stripped to be controlled.

      \n *\n *

      A null input String returns null.\n * An empty string (\"\") input returns the empty string.

      \n *\n *

      If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.\n * Alternatively use {@link #strip(String)}.

      \n *\n *
      \n     * StringUtils.strip(null, *)          = null\n     * StringUtils.strip(\"\", *)            = \"\"\n     * StringUtils.strip(\"abc\", null)      = \"abc\"\n     * StringUtils.strip(\"  abc\", null)    = \"abc\"\n     * StringUtils.strip(\"abc  \", null)    = \"abc\"\n     * StringUtils.strip(\" abc \", null)    = \"abc\"\n     * StringUtils.strip(\"  abcyx\", \"xyz\") = \"  abc\"\n     * 
      \n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String strip(String str, final String stripChars) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n str = StringUtils.stripStart(str, stripChars);\n return StringUtils.stripEnd(str, stripChars);\n }\n\n /**\n *

      Strips any of a set of characters from the start of a String.

      \n *\n *

      A null input String returns null.\n * An empty string (\"\") input returns the empty string.

      \n *\n *

      If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.

      \n *\n *
      \n     * StringUtils.stripStart(null, *)          = null\n     * StringUtils.stripStart(\"\", *)            = \"\"\n     * StringUtils.stripStart(\"abc\", \"\")        = \"abc\"\n     * StringUtils.stripStart(\"abc\", null)      = \"abc\"\n     * StringUtils.stripStart(\"  abc\", null)    = \"abc\"\n     * StringUtils.stripStart(\"abc  \", null)    = \"abc  \"\n     * StringUtils.stripStart(\" abc \", null)    = \"abc \"\n     * StringUtils.stripStart(\"yxabc  \", \"xyz\") = \"abc  \"\n     * 
      \n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String stripStart(final String str, final String stripChars) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n int start = 0;\n if (stripChars == null) {\n while (start != strLen && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n } else if (stripChars.length() == 0) {\n return str;\n } else {\n while (start != strLen && stripChars.indexOf(str.charAt(start)) != StringUtils.INDEX_NOT_FOUND) {\n start++;\n }\n }\n return str.substring(start);\n }\n\n /**\n *

      Strips any of a set of characters from the end of a String.

      \n *\n *

      A null input String returns null.\n * An empty string (\"\") input returns the empty string.

      \n *\n *

      If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.

      \n *\n *
      \n     * StringUtils.stripEnd(null, *)          = null\n     * StringUtils.stripEnd(\"\", *)            = \"\"\n     * StringUtils.stripEnd(\"abc\", \"\")        = \"abc\"\n     * StringUtils.stripEnd(\"abc\", null)      = \"abc\"\n     * StringUtils.stripEnd(\"  abc\", null)    = \"  abc\"\n     * StringUtils.stripEnd(\"abc  \", null)    = \"abc\"\n     * StringUtils.stripEnd(\" abc \", null)    = \" abc\"\n     * StringUtils.stripEnd(\"  abcyx\", \"xyz\") = \"  abc\"\n     * StringUtils.stripEnd(\"120.00\", \".0\")   = \"12\"\n     * 
      \n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the set of characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String stripEnd(final String str, final String stripChars) {\n int end;\n if (str == null || (end = str.length()) == 0) {\n return str;\n }\n if (stripChars == null) {\n while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n } else if (stripChars.length() == 0) {\n return str;\n } else {\n while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != StringUtils.INDEX_NOT_FOUND) {\n end--;\n }\n }\n return str.substring(0, end);\n }\n // StripAll\n //-----------------------------------------------------------------------\n\n /**\n *

      Strips whitespace from the start and end of every String in an array.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

      \n *\n *

      A new array is returned each time, except for length zero.\n * A null array will return null.\n * An empty array will return itself.\n * A null array entry will be ignored.

      \n *\n *
      \n     * StringUtils.stripAll(null)             = null\n     * StringUtils.stripAll([])               = []\n     * StringUtils.stripAll([\"abc\", \"  abc\"]) = [\"abc\", \"abc\"]\n     * StringUtils.stripAll([\"abc  \", null])  = [\"abc\", null]\n     * 
      \n *\n * @param strs the array to remove whitespace from, may be null\n * @return the stripped Strings, null if null array input\n */\n public static String[] stripAll(final String[] strs) {\n return StringUtils.stripAll(strs, null);\n }\n\n /**\n *

      Strips any of a set of characters from the start and end of every\n * String in an array.

      \n * Whitespace is defined by {@link Character#isWhitespace(char)}.

      \n *\n *

      A new array is returned each time, except for length zero.\n * A null array will return null.\n * An empty array will return itself.\n * A null array entry will be ignored.\n * A null stripChars will strip whitespace as defined by\n * {@link Character#isWhitespace(char)}.

      \n *\n *
      \n     * StringUtils.stripAll(null, *)                = null\n     * StringUtils.stripAll([], *)                  = []\n     * StringUtils.stripAll([\"abc\", \"  abc\"], null) = [\"abc\", \"abc\"]\n     * StringUtils.stripAll([\"abc  \", null], null)  = [\"abc\", null]\n     * StringUtils.stripAll([\"abc  \", null], \"yz\")  = [\"abc  \", null]\n     * StringUtils.stripAll([\"yabcz\", null], \"yz\")  = [\"abc\", null]\n     * 
      \n *\n * @param strs the array to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped Strings, null if null array input\n */\n public static String[] stripAll(final String[] strs, final String stripChars) {\n int strsLen;\n if (strs == null || (strsLen = strs.length) == 0) {\n return strs;\n }\n String[] newArr = new String[strsLen];\n for (int i = 0; i < strsLen; i++) {\n newArr[i] = StringUtils.strip(strs[i], stripChars);\n }\n return newArr;\n }\n // Equals\n //-----------------------------------------------------------------------\n\n /**\n *

      Compares two Strings, returning true if they are equal.

      \n *\n *

      nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

      \n *\n *
      \n     * StringUtils.equals(null, null)   = true\n     * StringUtils.equals(null, \"abc\")  = false\n     * StringUtils.equals(\"abc\", null)  = false\n     * StringUtils.equals(\"abc\", \"abc\") = true\n     * StringUtils.equals(\"abc\", \"ABC\") = false\n     * 
      \n *\n * @see String#equals(Object)\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return true if the Strings are equal, case sensitive, or\n * both null\n */\n public static boolean equals(final String str1, final String str2) {\n return str1 == null ? str2 == null : str1.equals(str2);\n }\n\n /**\n *

      Compares two Strings, returning true if they are equal ignoring\n * the case.

      \n *\n *

      nulls are handled without exceptions. Two null\n * references are considered equal. Comparison is case insensitive.

      \n *\n *
      \n     * StringUtils.equalsIgnoreCase(null, null)   = true\n     * StringUtils.equalsIgnoreCase(null, \"abc\")  = false\n     * StringUtils.equalsIgnoreCase(\"abc\", null)  = false\n     * StringUtils.equalsIgnoreCase(\"abc\", \"abc\") = true\n     * StringUtils.equalsIgnoreCase(\"abc\", \"ABC\") = true\n     * 
      \n *\n * @see String#equalsIgnoreCase(String)\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return true if the Strings are equal, case insensitive, or\n * both null\n */\n public static boolean equalsIgnoreCase(final String str1, final String str2) {\n return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);\n }\n // IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(int)}.

      \n *\n *

      A null or empty (\"\") String will return INDEX_NOT_FOUND (-1).

      \n *\n *
      \n     * StringUtils.indexOf(null, *)         = -1\n     * StringUtils.indexOf(\"\", *)           = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'a') = 0\n     * StringUtils.indexOf(\"aabaabaa\", 'b') = 2\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return the first index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchChar);\n }\n\n /**\n *

      Finds the first index within a String from a start position,\n * handling null.\n * This method uses {@link String#indexOf(int, int)}.

      \n *\n *

      A null or empty (\"\") String will return (INDEX_NOT_FOUND) -1.\n * A negative start position is treated as zero.\n * A start position greater than the string length returns -1.

      \n *\n *
      \n     * StringUtils.indexOf(null, *, *)          = -1\n     * StringUtils.indexOf(\"\", *, *)            = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 0)  = 2\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 3)  = 5\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 9)  = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'b', -1) = 2\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final char searchChar, final int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchChar, startPos);\n }\n\n /**\n *

      Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

      \n *\n *

      A null String will return -1.

      \n *\n *
      \n     * StringUtils.indexOf(null, *)          = -1\n     * StringUtils.indexOf(*, null)          = -1\n     * StringUtils.indexOf(\"\", \"\")           = 0\n     * StringUtils.indexOf(\"\", *)            = -1 (except when * = \"\")\n     * StringUtils.indexOf(\"aabaabaa\", \"a\")  = 0\n     * StringUtils.indexOf(\"aabaabaa\", \"b\")  = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"ab\") = 1\n     * StringUtils.indexOf(\"aabaabaa\", \"\")   = 0\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr);\n }\n\n /**\n *

      Finds the n-th index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

      \n *\n *

      A null String will return -1.

      \n *\n *
      \n     * StringUtils.ordinalIndexOf(null, *, *)          = -1\n     * StringUtils.ordinalIndexOf(*, null, *)          = -1\n     * StringUtils.ordinalIndexOf(\"\", \"\", *)           = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"a\", 1)  = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"a\", 2)  = 1\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"b\", 1)  = 2\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"b\", 2)  = 5\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"ab\", 1) = 1\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"ab\", 2) = 4\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"\", 1)   = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"\", 2)   = 0\n     * 
      \n *\n *

      Note that 'head(String str, int n)' may be implemented as:

      \n *\n *
      \n     *   str.substring(0, lastOrdinalIndexOf(str, \"\\n\", n))\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th searchStr to find\n * @return the n-th index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n * @since 2.1\n */\n public static int ordinalIndexOf(final String str, final String searchStr, final int ordinal) {\n return StringUtils.ordinalIndexOf(str, searchStr, ordinal, false);\n }\n\n /**\n *

      Finds the n-th index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

      \n *\n *

      A null String will return -1.

      \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th searchStr to find\n * @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf()\n * @return the n-th index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n */\n // Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int)\n private static int ordinalIndexOf(final String str, final String searchStr, final int ordinal, final boolean lastIndex) {\n if (str == null || searchStr == null || ordinal <= 0) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return lastIndex ? str.length() : 0;\n }\n int found = 0;\n int index = lastIndex ? str.length() : StringUtils.INDEX_NOT_FOUND;\n do {\n if (lastIndex) {\n index = str.lastIndexOf(searchStr, index - 1);\n } else {\n index = str.indexOf(searchStr, index + 1);\n }\n if (index < 0) {\n return index;\n }\n found++;\n } while (found < ordinal);\n return index;\n }\n\n /**\n *

      Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(String, int)}.

      \n *\n *

      A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

      \n *\n *
      \n     * StringUtils.indexOf(null, *, *)          = -1\n     * StringUtils.indexOf(*, null, *)          = -1\n     * StringUtils.indexOf(\"\", \"\", 0)           = 0\n     * StringUtils.indexOf(\"\", *, 0)            = -1 (except when * = \"\")\n     * StringUtils.indexOf(\"aabaabaa\", \"a\", 0)  = 0\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 0)  = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"ab\", 0) = 1\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 3)  = 5\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 9)  = -1\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", -1) = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"\", 2)   = 2\n     * StringUtils.indexOf(\"abc\", \"\", 9)        = 3\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final String searchStr, final int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n // JDK1.2/JDK1.3 have a bug, when startPos > str.length for \"\", hence\n if (searchStr.length() == 0 && startPos >= str.length()) {\n return str.length();\n }\n return str.indexOf(searchStr, startPos);\n }\n\n /**\n *

      Case in-sensitive find of the first index within a String.

      \n *\n *

      A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

      \n *\n *
      \n     * StringUtils.indexOfIgnoreCase(null, *)          = -1\n     * StringUtils.indexOfIgnoreCase(*, null)          = -1\n     * StringUtils.indexOfIgnoreCase(\"\", \"\")           = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"a\")  = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"b\")  = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"ab\") = 1\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int indexOfIgnoreCase(final String str, final String searchStr) {\n return StringUtils.indexOfIgnoreCase(str, searchStr, 0);\n }\n\n /**\n *

      Case in-sensitive find of the first index within a String\n * from the specified position.

      \n *\n *

      A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

      \n *\n *
      \n     * StringUtils.indexOfIgnoreCase(null, *, *)          = -1\n     * StringUtils.indexOfIgnoreCase(*, null, *)          = -1\n     * StringUtils.indexOfIgnoreCase(\"\", \"\", 0)           = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"A\", 0)  = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 0)  = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"AB\", 0) = 1\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 3)  = 5\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 9)  = -1\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", -1) = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"\", 2)   = 2\n     * StringUtils.indexOfIgnoreCase(\"abc\", \"\", 9)        = 3\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int indexOfIgnoreCase(final String str, final String searchStr, int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (startPos < 0) {\n startPos = 0;\n }\n int endLimit = str.length() - searchStr.length() + 1;\n if (startPos > endLimit) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return startPos;\n }\n for (int i = startPos; i < endLimit; i++) {\n if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {\n return i;\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // LastIndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

      Finds the last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(int)}.

      \n *\n *

      A null or empty (\"\") String will return -1.

      \n *\n *
      \n     * StringUtils.lastIndexOf(null, *)         = -1\n     * StringUtils.lastIndexOf(\"\", *)           = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'a') = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b') = 5\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return the last index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar);\n }\n\n /**\n *

      Finds the last index within a String from a start position,\n * handling null.\n * This method uses {@link String#lastIndexOf(int, int)}.

      \n *\n *

      A null or empty (\"\") String will return -1.\n * A negative start position returns -1.\n * A start position greater than the string length searches the whole string.

      \n *\n *
      \n     * StringUtils.lastIndexOf(null, *, *)          = -1\n     * StringUtils.lastIndexOf(\"\", *,  *)           = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 8)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 4)  = 2\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 0)  = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 9)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', -1) = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'a', 0)  = 0\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @param startPos the start position\n * @return the last index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final char searchChar, final int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar, startPos);\n }\n\n /**\n *

      Finds the last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String)}.

      \n *\n *

      A null String will return -1.

      \n *\n *
      \n     * StringUtils.lastIndexOf(null, *)          = -1\n     * StringUtils.lastIndexOf(*, null)          = -1\n     * StringUtils.lastIndexOf(\"\", \"\")           = 0\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\")  = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\")  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"ab\") = 4\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"\")   = 8\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the last index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr);\n }\n\n /**\n *

      Finds the n-th last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String)}.

      \n *\n *

      A null String will return -1.

      \n *\n *
      \n     * StringUtils.lastOrdinalIndexOf(null, *, *)          = -1\n     * StringUtils.lastOrdinalIndexOf(*, null, *)          = -1\n     * StringUtils.lastOrdinalIndexOf(\"\", \"\", *)           = 0\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"a\", 1)  = 7\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"a\", 2)  = 6\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"b\", 1)  = 5\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"b\", 2)  = 2\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"ab\", 1) = 4\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"ab\", 2) = 1\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"\", 1)   = 8\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"\", 2)   = 8\n     * 
      \n *\n *

      Note that 'tail(String str, int n)' may be implemented as:

      \n *\n *
      \n     *   str.substring(lastOrdinalIndexOf(str, \"\\n\", n) + 1)\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th last searchStr to find\n * @return the n-th last index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n * @since 2.5\n */\n public static int lastOrdinalIndexOf(final String str, final String searchStr, final int ordinal) {\n return StringUtils.ordinalIndexOf(str, searchStr, ordinal, true);\n }\n\n /**\n *

      Finds the first index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String, int)}.

      \n *\n *

      A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

      \n *\n *
      \n     * StringUtils.lastIndexOf(null, *, *)          = -1\n     * StringUtils.lastIndexOf(*, null, *)          = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\", 8)  = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 8)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"ab\", 8) = 4\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 9)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", -1) = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\", 0)  = 0\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 0)  = -1\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final String searchStr, final int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr, startPos);\n }\n\n /**\n *

      Case in-sensitive find of the last index within a String.

      \n *\n *

      A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

      \n *\n *
      \n     * StringUtils.lastIndexOfIgnoreCase(null, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(*, null)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\")  = 7\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\")  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"AB\") = 4\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int lastIndexOfIgnoreCase(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return StringUtils.lastIndexOfIgnoreCase(str, searchStr, str.length());\n }\n\n /**\n *

      Case in-sensitive find of the last index within a String\n * from the specified position.

      \n *\n *

      A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

      \n *\n *
      \n     * StringUtils.lastIndexOfIgnoreCase(null, *, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(*, null, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\", 8)  = 7\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 8)  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"AB\", 8) = 4\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 9)  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", -1) = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\", 0)  = 0\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 0)  = -1\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int lastIndexOfIgnoreCase(final String str, final String searchStr, int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (startPos > str.length() - searchStr.length()) {\n startPos = str.length() - searchStr.length();\n }\n if (startPos < 0) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return startPos;\n }\n for (int i = startPos; i >= 0; i--) {\n if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {\n return i;\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // Contains\n //-----------------------------------------------------------------------\n\n /**\n *

      Checks if String contains a search character, handling null.\n * This method uses {@link String#indexOf(int)}.

      \n *\n *

      A null or empty (\"\") String will return false.

      \n *\n *
      \n     * StringUtils.contains(null, *)    = false\n     * StringUtils.contains(\"\", *)      = false\n     * StringUtils.contains(\"abc\", 'a') = true\n     * StringUtils.contains(\"abc\", 'z') = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return true if the String contains the search character,\n * false if not or null string input\n * @since 2.0\n */\n public static boolean contains(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return false;\n }\n return str.indexOf(searchChar) >= 0;\n }\n\n /**\n *

      Checks if String contains a search String, handling null.\n * This method uses {@link String#indexOf(String)}.

      \n *\n *

      A null String will return false.

      \n *\n *
      \n     * StringUtils.contains(null, *)     = false\n     * StringUtils.contains(*, null)     = false\n     * StringUtils.contains(\"\", \"\")      = true\n     * StringUtils.contains(\"abc\", \"\")   = true\n     * StringUtils.contains(\"abc\", \"a\")  = true\n     * StringUtils.contains(\"abc\", \"z\")  = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return true if the String contains the search String,\n * false if not or null string input\n * @since 2.0\n */\n public static boolean contains(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n return str.contains(searchStr);\n }\n\n /**\n *

      Checks if String contains a search String irrespective of case,\n * handling null. Case-insensitivity is defined as by\n * {@link String#equalsIgnoreCase(String)}.\n *\n *

      A null String will return false.

      \n *\n *
      \n     * StringUtils.contains(null, *) = false\n     * StringUtils.contains(*, null) = false\n     * StringUtils.contains(\"\", \"\") = true\n     * StringUtils.contains(\"abc\", \"\") = true\n     * StringUtils.contains(\"abc\", \"a\") = true\n     * StringUtils.contains(\"abc\", \"z\") = false\n     * StringUtils.contains(\"abc\", \"A\") = true\n     * StringUtils.contains(\"abc\", \"Z\") = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return true if the String contains the search String irrespective of\n * case or false if not or null string input\n */\n public static boolean containsIgnoreCase(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n int len = searchStr.length();\n int max = str.length() - len;\n for (int i = 0; i <= max; i++) {\n if (str.regionMatches(true, i, searchStr, 0, len)) {\n return true;\n }\n }\n return false;\n }\n // IndexOfAny chars\n //-----------------------------------------------------------------------\n\n /**\n *

      Search a String to find the first index of any\n * character in the given set of characters.

      \n *\n *

      A null String will return -1.\n * A null or zero length search array will return -1.

      \n *\n *
      \n     * StringUtils.indexOfAny(null, *)                = -1\n     * StringUtils.indexOfAny(\"\", *)                  = -1\n     * StringUtils.indexOfAny(*, null)                = -1\n     * StringUtils.indexOfAny(*, [])                  = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\",['z','a']) = 0\n     * StringUtils.indexOfAny(\"zzabyycdxx\",['b','y']) = 3\n     * StringUtils.indexOfAny(\"aba\", ['z'])           = -1\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAny(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) {\n // ch is a supplementary character\n if (searchChars[j + 1] == str.charAt(i + 1)) {\n return i;\n }\n } else {\n return i;\n }\n }\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Search a String to find the first index of any\n * character in the given set of characters.

      \n *\n *

      A null String will return -1.\n * A null search string will return -1.

      \n *\n *
      \n     * StringUtils.indexOfAny(null, *)            = -1\n     * StringUtils.indexOfAny(\"\", *)              = -1\n     * StringUtils.indexOfAny(*, null)            = -1\n     * StringUtils.indexOfAny(*, \"\")              = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", \"za\") = 0\n     * StringUtils.indexOfAny(\"zzabyycdxx\", \"by\") = 3\n     * StringUtils.indexOfAny(\"aba\",\"z\")          = -1\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAny(final String str, final String searchChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return StringUtils.indexOfAny(str, searchChars.toCharArray());\n }\n // ContainsAny\n //-----------------------------------------------------------------------\n\n /**\n *

      Checks if the String contains any character in the given\n * set of characters.

      \n *\n *

      A null String will return false.\n * A null or zero length search array will return false.

      \n *\n *
      \n     * StringUtils.containsAny(null, *)                = false\n     * StringUtils.containsAny(\"\", *)                  = false\n     * StringUtils.containsAny(*, null)                = false\n     * StringUtils.containsAny(*, [])                  = false\n     * StringUtils.containsAny(\"zzabyycdxx\",['z','a']) = true\n     * StringUtils.containsAny(\"zzabyycdxx\",['b','y']) = true\n     * StringUtils.containsAny(\"aba\", ['z'])           = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the true if any of the chars are found,\n * false if no match or null input\n * @since 2.4\n */\n public static boolean containsAny(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return false;\n }\n int csLength = str.length();\n int searchLength = searchChars.length;\n int csLast = csLength - 1;\n int searchLast = searchLength - 1;\n for (int i = 0; i < csLength; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLength; j++) {\n if (searchChars[j] == ch) {\n if (CharUtils.isHighSurrogate(ch)) {\n if (j == searchLast) {\n // missing low surrogate, fine, like String.indexOf(String)\n return true;\n }\n if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) {\n return true;\n }\n } else {\n // ch is in the Basic Multilingual Plane\n return true;\n }\n }\n }\n }\n return false;\n }\n\n /**\n *

      \n * Checks if the String contains any character in the given set of characters.\n *

      \n *\n *

      \n * A null String will return false. A null search string will return\n * false.\n *

      \n *\n *
      \n     * StringUtils.containsAny(null, *)            = false\n     * StringUtils.containsAny(\"\", *)              = false\n     * StringUtils.containsAny(*, null)            = false\n     * StringUtils.containsAny(*, \"\")              = false\n     * StringUtils.containsAny(\"zzabyycdxx\", \"za\") = true\n     * StringUtils.containsAny(\"zzabyycdxx\", \"by\") = true\n     * StringUtils.containsAny(\"aba\",\"z\")          = false\n     * 
      \n *\n * @param str\n * the String to check, may be null\n * @param searchChars\n * the chars to search for, may be null\n * @return the true if any of the chars are found, false if no match or null input\n * @since 2.4\n */\n public static boolean containsAny(final String str, final String searchChars) {\n if (searchChars == null) {\n return false;\n }\n return StringUtils.containsAny(str, searchChars.toCharArray());\n }\n // IndexOfAnyBut chars\n //-----------------------------------------------------------------------\n\n /**\n *

      Search a String to find the first index of any\n * character not in the given set of characters.

      \n *\n *

      A null String will return -1.\n * A null or zero length search array will return -1.

      \n *\n *
      \n     * StringUtils.indexOfAnyBut(null, *)                              = -1\n     * StringUtils.indexOfAnyBut(\"\", *)                                = -1\n     * StringUtils.indexOfAnyBut(*, null)                              = -1\n     * StringUtils.indexOfAnyBut(*, [])                                = -1\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", new char[] {'z', 'a'} ) = 3\n     * StringUtils.indexOfAnyBut(\"aba\", new char[] {'z'} )             = 0\n     * StringUtils.indexOfAnyBut(\"aba\", new char[] {'a', 'b'} )        = -1\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAnyBut(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n outer:\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) {\n if (searchChars[j + 1] == str.charAt(i + 1)) {\n continue outer;\n }\n } else {\n continue outer;\n }\n }\n }\n return i;\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Search a String to find the first index of any\n * character not in the given set of characters.

      \n *\n *

      A null String will return -1.\n * A null or empty search string will return -1.

      \n *\n *
      \n     * StringUtils.indexOfAnyBut(null, *)            = -1\n     * StringUtils.indexOfAnyBut(\"\", *)              = -1\n     * StringUtils.indexOfAnyBut(*, null)            = -1\n     * StringUtils.indexOfAnyBut(*, \"\")              = -1\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", \"za\") = 3\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", \"\")   = -1\n     * StringUtils.indexOfAnyBut(\"aba\",\"ab\")         = -1\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAnyBut(final String str, final String searchChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n char ch = str.charAt(i);\n boolean chFound = searchChars.indexOf(ch) >= 0;\n if (i + 1 < strLen && CharUtils.isHighSurrogate(ch)) {\n char ch2 = str.charAt(i + 1);\n if (chFound && searchChars.indexOf(ch2) < 0) {\n return i;\n }\n } else {\n if (!chFound) {\n return i;\n }\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // ContainsOnly\n //-----------------------------------------------------------------------\n\n /**\n *

      Checks if the String contains only certain characters.

      \n *\n *

      A null String will return false.\n * A null valid character array will return false.\n * An empty String (length()=0) always returns true.

      \n *\n *
      \n     * StringUtils.containsOnly(null, *)       = false\n     * StringUtils.containsOnly(*, null)       = false\n     * StringUtils.containsOnly(\"\", *)         = true\n     * StringUtils.containsOnly(\"ab\", '')      = false\n     * StringUtils.containsOnly(\"abab\", 'abc') = true\n     * StringUtils.containsOnly(\"ab1\", 'abc')  = false\n     * StringUtils.containsOnly(\"abz\", 'abc')  = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @param valid an array of valid chars, may be null\n * @return true if it only contains valid chars and is non-null\n */\n public static boolean containsOnly(final String str, final char[] valid) {\n // All these pre-checks are to maintain API with an older version\n if (valid == null || str == null) {\n return false;\n }\n if (str.length() == 0) {\n return true;\n }\n if (valid.length == 0) {\n return false;\n }\n return StringUtils.indexOfAnyBut(str, valid) == StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Checks if the String contains only certain characters.

      \n *\n *

      A null String will return false.\n * A null valid character String will return false.\n * An empty String (length()=0) always returns true.

      \n *\n *
      \n     * StringUtils.containsOnly(null, *)       = false\n     * StringUtils.containsOnly(*, null)       = false\n     * StringUtils.containsOnly(\"\", *)         = true\n     * StringUtils.containsOnly(\"ab\", \"\")      = false\n     * StringUtils.containsOnly(\"abab\", \"abc\") = true\n     * StringUtils.containsOnly(\"ab1\", \"abc\")  = false\n     * StringUtils.containsOnly(\"abz\", \"abc\")  = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @param validChars a String of valid chars, may be null\n * @return true if it only contains valid chars and is non-null\n * @since 2.0\n */\n public static boolean containsOnly(final String str, final String validChars) {\n if (str == null || validChars == null) {\n return false;\n }\n return StringUtils.containsOnly(str, validChars.toCharArray());\n }\n // ContainsNone\n //-----------------------------------------------------------------------\n\n /**\n *

      Checks that the String does not contain certain characters.

      \n *\n *

      A null String will return true.\n * A null invalid character array will return true.\n * An empty String (length()=0) always returns true.

      \n *\n *
      \n     * StringUtils.containsNone(null, *)       = true\n     * StringUtils.containsNone(*, null)       = true\n     * StringUtils.containsNone(\"\", *)         = true\n     * StringUtils.containsNone(\"ab\", '')      = true\n     * StringUtils.containsNone(\"abab\", 'xyz') = true\n     * StringUtils.containsNone(\"ab1\", 'xyz')  = true\n     * StringUtils.containsNone(\"abz\", 'xyz')  = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchChars an array of invalid chars, may be null\n * @return true if it contains none of the invalid chars, or is null\n * @since 2.0\n */\n public static boolean containsNone(final String str, final char[] searchChars) {\n if (str == null || searchChars == null) {\n return true;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (CharUtils.isHighSurrogate(ch)) {\n if (j == searchLast) {\n // missing low surrogate, fine, like String.indexOf(String)\n return false;\n }\n if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) {\n return false;\n }\n } else {\n // ch is in the Basic Multilingual Plane\n return false;\n }\n }\n }\n }\n return true;\n }\n\n /**\n *

      Checks that the String does not contain certain characters.

      \n *\n *

      A null String will return true.\n * A null invalid character array will return true.\n * An empty String (\"\") always returns true.

      \n *\n *
      \n     * StringUtils.containsNone(null, *)       = true\n     * StringUtils.containsNone(*, null)       = true\n     * StringUtils.containsNone(\"\", *)         = true\n     * StringUtils.containsNone(\"ab\", \"\")      = true\n     * StringUtils.containsNone(\"abab\", \"xyz\") = true\n     * StringUtils.containsNone(\"ab1\", \"xyz\")  = true\n     * StringUtils.containsNone(\"abz\", \"xyz\")  = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @param invalidChars a String of invalid chars, may be null\n * @return true if it contains none of the invalid chars, or is null\n * @since 2.0\n */\n public static boolean containsNone(final String str, final String invalidChars) {\n if (str == null || invalidChars == null) {\n return true;\n }\n return StringUtils.containsNone(str, invalidChars.toCharArray());\n }\n // IndexOfAny strings\n //-----------------------------------------------------------------------\n\n /**\n *

      Find the first index of any of a set of potential substrings.

      \n *\n *

      A null String will return -1.\n * A null or zero length search array will return -1.\n * A null search array entry will be ignored, but a search\n * array containing \"\" will return 0 if str is not\n * null. This method uses {@link String#indexOf(String)}.

      \n *\n *
      \n     * StringUtils.indexOfAny(null, *)                     = -1\n     * StringUtils.indexOfAny(*, null)                     = -1\n     * StringUtils.indexOfAny(*, [])                       = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"ab\",\"cd\"])   = 2\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"cd\",\"ab\"])   = 2\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"])   = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"zab\",\"aby\"]) = 1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"\"])          = 0\n     * StringUtils.indexOfAny(\"\", [\"\"])                    = 0\n     * StringUtils.indexOfAny(\"\", [\"a\"])                   = -1\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStrs the Strings to search for, may be null\n * @return the first index of any of the searchStrs in str, -1 if no match\n */\n public static int indexOfAny(final String str, final String[] searchStrs) {\n if (str == null || searchStrs == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int sz = searchStrs.length;\n // String's can't have a MAX_VALUEth index.\n int ret = Integer.MAX_VALUE;\n int tmp = 0;\n for (int i = 0; i < sz; i++) {\n String search = searchStrs[i];\n if (search == null) {\n continue;\n }\n tmp = str.indexOf(search);\n if (tmp == StringUtils.INDEX_NOT_FOUND) {\n continue;\n }\n if (tmp < ret) {\n ret = tmp;\n }\n }\n return ret == Integer.MAX_VALUE ? StringUtils.INDEX_NOT_FOUND : ret;\n }\n\n /**\n *

      Find the latest index of any of a set of potential substrings.

      \n *\n *

      A null String will return -1.\n * A null search array will return -1.\n * A null or zero length search array entry will be ignored,\n * but a search array containing \"\" will return the length of str\n * if str is not null. This method uses {@link String#indexOf(String)}

      \n *\n *
      \n     * StringUtils.lastIndexOfAny(null, *)                   = -1\n     * StringUtils.lastIndexOfAny(*, null)                   = -1\n     * StringUtils.lastIndexOfAny(*, [])                     = -1\n     * StringUtils.lastIndexOfAny(*, [null])                 = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"ab\",\"cd\"]) = 6\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"cd\",\"ab\"]) = 6\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"]) = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"]) = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"\"])   = 10\n     * 
      \n *\n * @param str the String to check, may be null\n * @param searchStrs the Strings to search for, may be null\n * @return the last index of any of the Strings, -1 if no match\n */\n public static int lastIndexOfAny(final String str, final String[] searchStrs) {\n if (str == null || searchStrs == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int sz = searchStrs.length;\n int ret = StringUtils.INDEX_NOT_FOUND;\n int tmp = 0;\n for (int i = 0; i < sz; i++) {\n String search = searchStrs[i];\n if (search == null) {\n continue;\n }\n tmp = str.lastIndexOf(search);\n if (tmp > ret) {\n ret = tmp;\n }\n }\n return ret;\n }\n // Substring\n //-----------------------------------------------------------------------\n\n /**\n *

      Gets a substring from the specified String avoiding exceptions.

      \n *\n *

      A negative start position can be used to start n\n * characters from the end of the String.

      \n *\n *

      A null String will return null.\n * An empty (\"\") String will return \"\".

      \n *\n *
      \n     * StringUtils.substring(null, *)   = null\n     * StringUtils.substring(\"\", *)     = \"\"\n     * StringUtils.substring(\"abc\", 0)  = \"abc\"\n     * StringUtils.substring(\"abc\", 2)  = \"c\"\n     * StringUtils.substring(\"abc\", 4)  = \"\"\n     * StringUtils.substring(\"abc\", -2) = \"bc\"\n     * StringUtils.substring(\"abc\", -4) = \"abc\"\n     * 
      \n *\n * @param str the String to get the substring from, may be null\n * @param start the position to start from, negative means\n * count back from the end of the String by this many characters\n * @return substring from start position, null if null String input\n */\n public static String substring(final String str, int start) {\n if (str == null) {\n return null;\n }\n // handle negatives, which means last n characters\n if (start < 0) {\n start = str.length() + start; // remember start is negative\n }\n if (start < 0) {\n start = 0;\n }\n if (start > str.length()) {\n return StringUtils.EMPTY;\n }\n return str.substring(start);\n }\n\n /**\n *

      Gets a substring from the specified String avoiding exceptions.

      \n *\n *

      A negative start position can be used to start/end n\n * characters from the end of the String.

      \n *\n *

      The returned substring starts with the character in the start\n * position and ends before the end position. All position counting is\n * zero-based -- i.e., to start at the beginning of the string use\n * start = 0. Negative start and end positions can be used to\n * specify offsets relative to the end of the String.

      \n *\n *

      If start is not strictly to the left of end, \"\"\n * is returned.

      \n *\n *
      \n     * StringUtils.substring(null, *, *)    = null\n     * StringUtils.substring(\"\", * ,  *)    = \"\";\n     * StringUtils.substring(\"abc\", 0, 2)   = \"ab\"\n     * StringUtils.substring(\"abc\", 2, 0)   = \"\"\n     * StringUtils.substring(\"abc\", 2, 4)   = \"c\"\n     * StringUtils.substring(\"abc\", 4, 6)   = \"\"\n     * StringUtils.substring(\"abc\", 2, 2)   = \"\"\n     * StringUtils.substring(\"abc\", -2, -1) = \"b\"\n     * StringUtils.substring(\"abc\", -4, 2)  = \"ab\"\n     * 
      \n *\n * @param str the String to get the substring from, may be null\n * @param start the position to start from, negative means\n * count back from the end of the String by this many characters\n * @param end the position to end at (exclusive), negative means\n * count back from the end of the String by this many characters\n * @return substring from start position to end positon,\n * null if null String input\n */\n public static String substring(final String str, int start, int end) {\n if (str == null) {\n return null;\n }\n // handle negatives\n if (end < 0) {\n end = str.length() + end; // remember end is negative\n }\n if (start < 0) {\n start = str.length() + start; // remember start is negative\n }\n // check length next\n if (end > str.length()) {\n end = str.length();\n }\n // if start is greater than end, return \"\"\n if (start > end) {\n return StringUtils.EMPTY;\n }\n if (start < 0) {\n start = 0;\n }\n if (end < 0) {\n end = 0;\n }\n return str.substring(start, end);\n }\n // Left/Right/Mid\n //-----------------------------------------------------------------------\n\n /**\n *

      Gets the leftmost len characters of a String.

      \n *\n *

      If len characters are not available, or the\n * String is null, the String will be returned without\n * an exception. An empty String is returned if len is negative.

      \n *\n *
      \n     * StringUtils.left(null, *)    = null\n     * StringUtils.left(*, -ve)     = \"\"\n     * StringUtils.left(\"\", *)      = \"\"\n     * StringUtils.left(\"abc\", 0)   = \"\"\n     * StringUtils.left(\"abc\", 2)   = \"ab\"\n     * StringUtils.left(\"abc\", 4)   = \"abc\"\n     * 
      \n *\n * @param str the String to get the leftmost characters from, may be null\n * @param len the length of the required String\n * @return the leftmost characters, null if null String input\n */\n public static String left(final String str, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0) {\n return StringUtils.EMPTY;\n }\n if (str.length() <= len) {\n return str;\n }\n return str.substring(0, len);\n }\n\n /**\n *

      Gets the rightmost len characters of a String.

      \n *\n *

      If len characters are not available, or the String\n * is null, the String will be returned without an\n * an exception. An empty String is returned if len is negative.

      \n *\n *
      \n     * StringUtils.right(null, *)    = null\n     * StringUtils.right(*, -ve)     = \"\"\n     * StringUtils.right(\"\", *)      = \"\"\n     * StringUtils.right(\"abc\", 0)   = \"\"\n     * StringUtils.right(\"abc\", 2)   = \"bc\"\n     * StringUtils.right(\"abc\", 4)   = \"abc\"\n     * 
      \n *\n * @param str the String to get the rightmost characters from, may be null\n * @param len the length of the required String\n * @return the rightmost characters, null if null String input\n */\n public static String right(final String str, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0) {\n return StringUtils.EMPTY;\n }\n if (str.length() <= len) {\n return str;\n }\n return str.substring(str.length() - len);\n }\n\n /**\n *

      Gets len characters from the middle of a String.

      \n *\n *

      If len characters are not available, the remainder\n * of the String will be returned without an exception. If the\n * String is null, null will be returned.\n * An empty String is returned if len is negative or exceeds the\n * length of str.

      \n *\n *
      \n     * StringUtils.mid(null, *, *)    = null\n     * StringUtils.mid(*, *, -ve)     = \"\"\n     * StringUtils.mid(\"\", 0, *)      = \"\"\n     * StringUtils.mid(\"abc\", 0, 2)   = \"ab\"\n     * StringUtils.mid(\"abc\", 0, 4)   = \"abc\"\n     * StringUtils.mid(\"abc\", 2, 4)   = \"c\"\n     * StringUtils.mid(\"abc\", 4, 2)   = \"\"\n     * StringUtils.mid(\"abc\", -2, 2)  = \"ab\"\n     * 
      \n *\n * @param str the String to get the characters from, may be null\n * @param pos the position to start from, negative treated as zero\n * @param len the length of the required String\n * @return the middle characters, null if null String input\n */\n public static String mid(final String str, int pos, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0 || pos > str.length()) {\n return StringUtils.EMPTY;\n }\n if (pos < 0) {\n pos = 0;\n }\n if (str.length() <= pos + len) {\n return str.substring(pos);\n }\n return str.substring(pos, pos + len);\n }\n // SubStringAfter/SubStringBefore\n //-----------------------------------------------------------------------\n\n /**\n *

      Gets the substring before the first occurrence of a separator.\n * The separator is not returned.

      \n *\n *

      A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * A null separator will return the input string.

      \n *\n *

      If nothing is found, the string input is returned.

      \n *\n *
      \n     * StringUtils.substringBefore(null, *)      = null\n     * StringUtils.substringBefore(\"\", *)        = \"\"\n     * StringUtils.substringBefore(\"abc\", \"a\")   = \"\"\n     * StringUtils.substringBefore(\"abcba\", \"b\") = \"a\"\n     * StringUtils.substringBefore(\"abc\", \"c\")   = \"ab\"\n     * StringUtils.substringBefore(\"abc\", \"d\")   = \"abc\"\n     * StringUtils.substringBefore(\"abc\", \"\")    = \"\"\n     * StringUtils.substringBefore(\"abc\", null)  = \"abc\"\n     * 
      \n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring before the first occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringBefore(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || separator == null) {\n return str;\n }\n if (separator.length() == 0) {\n return StringUtils.EMPTY;\n }\n int pos = str.indexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n return str.substring(0, pos);\n }\n\n /**\n *

      Gets the substring after the first occurrence of a separator.\n * The separator is not returned.

      \n *\n *

      A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * A null separator will return the empty string if the\n * input string is not null.

      \n *\n *

      If nothing is found, the empty string is returned.

      \n *\n *
      \n     * StringUtils.substringAfter(null, *)      = null\n     * StringUtils.substringAfter(\"\", *)        = \"\"\n     * StringUtils.substringAfter(*, null)      = \"\"\n     * StringUtils.substringAfter(\"abc\", \"a\")   = \"bc\"\n     * StringUtils.substringAfter(\"abcba\", \"b\") = \"cba\"\n     * StringUtils.substringAfter(\"abc\", \"c\")   = \"\"\n     * StringUtils.substringAfter(\"abc\", \"d\")   = \"\"\n     * StringUtils.substringAfter(\"abc\", \"\")    = \"abc\"\n     * 
      \n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring after the first occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringAfter(final String str, final String separator) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (separator == null) {\n return StringUtils.EMPTY;\n }\n int pos = str.indexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return StringUtils.EMPTY;\n }\n return str.substring(pos + separator.length());\n }\n\n /**\n *

      Gets the substring before the last occurrence of a separator.\n * The separator is not returned.

      \n *\n *

      A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * An empty or null separator will return the input string.

      \n *\n *

      If nothing is found, the string input is returned.

      \n *\n *
      \n     * StringUtils.substringBeforeLast(null, *)      = null\n     * StringUtils.substringBeforeLast(\"\", *)        = \"\"\n     * StringUtils.substringBeforeLast(\"abcba\", \"b\") = \"abc\"\n     * StringUtils.substringBeforeLast(\"abc\", \"c\")   = \"ab\"\n     * StringUtils.substringBeforeLast(\"a\", \"a\")     = \"\"\n     * StringUtils.substringBeforeLast(\"a\", \"z\")     = \"a\"\n     * StringUtils.substringBeforeLast(\"a\", null)    = \"a\"\n     * StringUtils.substringBeforeLast(\"a\", \"\")      = \"a\"\n     * 
      \n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring before the last occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringBeforeLast(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(separator)) {\n return str;\n }\n int pos = str.lastIndexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n return str.substring(0, pos);\n }\n\n /**\n *

      Gets the substring after the last occurrence of a separator.\n * The separator is not returned.

      \n *\n *

      A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * An empty or null separator will return the empty string if\n * the input string is not null.

      \n *\n *

      If nothing is found, the empty string is returned.

      \n *\n *
      \n     * StringUtils.substringAfterLast(null, *)      = null\n     * StringUtils.substringAfterLast(\"\", *)        = \"\"\n     * StringUtils.substringAfterLast(*, \"\")        = \"\"\n     * StringUtils.substringAfterLast(*, null)      = \"\"\n     * StringUtils.substringAfterLast(\"abc\", \"a\")   = \"bc\"\n     * StringUtils.substringAfterLast(\"abcba\", \"b\") = \"a\"\n     * StringUtils.substringAfterLast(\"abc\", \"c\")   = \"\"\n     * StringUtils.substringAfterLast(\"a\", \"a\")     = \"\"\n     * StringUtils.substringAfterLast(\"a\", \"z\")     = \"\"\n     * 
      \n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring after the last occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringAfterLast(final String str, final String separator) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (StringUtils.isEmpty(separator)) {\n return StringUtils.EMPTY;\n }\n int pos = str.lastIndexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND || pos == str.length() - separator.length()) {\n return StringUtils.EMPTY;\n }\n return str.substring(pos + separator.length());\n }\n // Substring between\n //-----------------------------------------------------------------------\n\n /**\n *

      Gets the String that is nested in between two instances of the\n * same String.

      \n *\n *

      A null input String returns null.\n * A null tag returns null.

      \n *\n *
      \n     * StringUtils.substringBetween(null, *)            = null\n     * StringUtils.substringBetween(\"\", \"\")             = \"\"\n     * StringUtils.substringBetween(\"\", \"tag\")          = null\n     * StringUtils.substringBetween(\"tagabctag\", null)  = null\n     * StringUtils.substringBetween(\"tagabctag\", \"\")    = \"\"\n     * StringUtils.substringBetween(\"tagabctag\", \"tag\") = \"abc\"\n     * 
      \n *\n * @param str the String containing the substring, may be null\n * @param tag the String before and after the substring, may be null\n * @return the substring, null if no match\n * @since 2.0\n */\n public static String substringBetween(final String str, final String tag) {\n return StringUtils.substringBetween(str, tag, tag);\n }\n\n /**\n *

      Gets the String that is nested in between two Strings.\n * Only the first match is returned.

      \n *\n *

      A null input String returns null.\n * A null open/close returns null (no match).\n * An empty (\"\") open and close returns an empty string.

      \n *\n *
      \n     * StringUtils.substringBetween(\"wx[b]yz\", \"[\", \"]\") = \"b\"\n     * StringUtils.substringBetween(null, *, *)          = null\n     * StringUtils.substringBetween(*, null, *)          = null\n     * StringUtils.substringBetween(*, *, null)          = null\n     * StringUtils.substringBetween(\"\", \"\", \"\")          = \"\"\n     * StringUtils.substringBetween(\"\", \"\", \"]\")         = null\n     * StringUtils.substringBetween(\"\", \"[\", \"]\")        = null\n     * StringUtils.substringBetween(\"yabcz\", \"\", \"\")     = \"\"\n     * StringUtils.substringBetween(\"yabcz\", \"y\", \"z\")   = \"abc\"\n     * StringUtils.substringBetween(\"yabczyabcz\", \"y\", \"z\")   = \"abc\"\n     * 
      \n *\n * @param str the String containing the substring, may be null\n * @param open the String before the substring, may be null\n * @param close the String after the substring, may be null\n * @return the substring, null if no match\n * @since 2.0\n */\n public static String substringBetween(final String str, final String open, final String close) {\n if (str == null || open == null || close == null) {\n return null;\n }\n int start = str.indexOf(open);\n if (start != StringUtils.INDEX_NOT_FOUND) {\n int end = str.indexOf(close, start + open.length());\n if (end != StringUtils.INDEX_NOT_FOUND) {\n return str.substring(start + open.length(), end);\n }\n }\n return null;\n }\n\n /**\n *

      Searches a String for substrings delimited by a start and end tag,\n * returning all matching substrings in an array.

      \n *\n *

      A null input String returns null.\n * A null open/close returns null (no match).\n * An empty (\"\") open/close returns null (no match).

      \n *\n *
      \n     * StringUtils.substringsBetween(\"[a][b][c]\", \"[\", \"]\") = [\"a\",\"b\",\"c\"]\n     * StringUtils.substringsBetween(null, *, *)            = null\n     * StringUtils.substringsBetween(*, null, *)            = null\n     * StringUtils.substringsBetween(*, *, null)            = null\n     * StringUtils.substringsBetween(\"\", \"[\", \"]\")          = []\n     * 
      \n *\n * @param str the String containing the substrings, null returns null, empty returns empty\n * @param open the String identifying the start of the substring, empty returns null\n * @param close the String identifying the end of the substring, empty returns null\n * @return a String Array of substrings, or null if no match\n * @since 2.3\n */\n public static String[] substringsBetween(final String str, final String open, final String close) {\n if (str == null || StringUtils.isEmpty(open) || StringUtils.isEmpty(close)) {\n return null;\n }\n int strLen = str.length();\n if (strLen == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n int closeLen = close.length();\n int openLen = open.length();\n List list = new ArrayList();\n int pos = 0;\n while (pos < strLen - closeLen) {\n int start = str.indexOf(open, pos);\n if (start < 0) {\n break;\n }\n start += openLen;\n int end = str.indexOf(close, start);\n if (end < 0) {\n break;\n }\n list.add(str.substring(start, end));\n pos = end + closeLen;\n }\n if (list.isEmpty()) {\n return null;\n }\n return list.toArray(new String[list.size()]);\n }\n // Splitting\n //-----------------------------------------------------------------------\n\n /**\n *

      Splits the provided text into an array, using whitespace as the separator. but keep separator.

      \n *\n *
      \n     * StringUtils.splitKeep(null)          = null\n     * StringUtils.splitKeep(\"\")            = []\n     * StringUtils.splitKeep(\"a b c\", \" \")  = [\"a\", \" \", \"b\", \" \", \"c\"]\n     * StringUtils.splitKeep(\"abc def\", \" \")= [\"abc\", \" \", \"def\"]\n     * StringUtils.splitKeep(\" abc \", \" \")  = [\" \", \"abc\", \" \"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] splitKeep(String str, char separatorChar) {\n return splitKeep(str, String.valueOf(separatorChar));\n }\n\n /**\n *

      Splits the provided text into an array, using whitespace as the separator. but keep separator.

      \n *\n *
      \n     * StringUtils.splitKeep(null)          = null\n     * StringUtils.splitKeep(\"\")            = []\n     * StringUtils.splitKeep(\"a b c\", \" \")  = [\"a\", \" \", \"b\", \" \", \"c\"]\n     * StringUtils.splitKeep(\"abc def\", \" \")= [\"abc\", \" \", \"def\"]\n     * StringUtils.splitKeep(\" abc \", \" \")  = [\" \", \"abc\", \" \"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] splitKeep(String str, String separatorStr) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n int CHARS = separatorStr.length();\n if (CHARS == 0) {\n throw new IllegalArgumentException(\"chars must be > 0\");\n }\n int lastIndex = 0;\n ArrayList dat = new ArrayList<>();\n while (true) {\n int lookIndex = str.indexOf(separatorStr, lastIndex);\n if (lookIndex == -1) {\n String substring = str.substring(lastIndex);\n if (substring.length() > 0) {\n dat.add(substring);\n }\n break;\n } else {\n if (lastIndex != lookIndex) {\n String term = str.substring(lastIndex, lookIndex);\n dat.add(term);\n }\n dat.add(separatorStr);\n lastIndex = lookIndex + CHARS;\n }\n }\n return dat.toArray(new String[0]);\n }\n\n /**\n *

      Splits the provided text into an array, using whitespace as the\n * separator.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

      \n *\n *

      The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

      \n *\n *

      A null input String returns null.

      \n *\n *
      \n     * StringUtils.split(null)       = null\n     * StringUtils.split(\"\")         = []\n     * StringUtils.split(\"abc def\")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\") = [\"abc\", \"def\"]\n     * StringUtils.split(\" abc \")    = [\"abc\"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str) {\n return StringUtils.split(str, null, -1);\n }\n\n /**\n *

      Splits the provided text into an array, separator specified.\n * This is an alternative to using StringTokenizer.

      \n *\n *

      The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

      \n *\n *

      A null input String returns null.

      \n *\n *
      \n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"a.b.c\", '.')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.split(\"a..b.c\", '.')   = [\"a\", \"b\", \"c\"]\n     * StringUtils.split(\"a:b:c\", '.')    = [\"a:b:c\"]\n     * StringUtils.split(\"a b c\", ' ')    = [\"a\", \"b\", \"c\"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @param separatorChar the character used as the delimiter\n * @return an array of parsed Strings, null if null String input\n * @since 2.0\n */\n public static String[] split(final String str, final char separatorChar) {\n return StringUtils.splitWorker(str, separatorChar, false);\n }\n\n /**\n *

      Splits the provided text into an array, separators specified.\n * This is an alternative to using StringTokenizer.

      \n *\n *

      The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

      \n *\n *

      A null input String returns null.\n * A null separatorChars splits on whitespace.

      \n *\n *
      \n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"abc def\", null) = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc def\", \" \")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\", \" \") = [\"abc\", \"def\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\") = [\"ab\", \"cd\", \"ef\"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str, final String separatorChars) {\n return StringUtils.splitWorker(str, separatorChars, -1, false);\n }\n\n /**\n *

      Splits the provided text into an array with a maximum length,\n * separators specified.

      \n *\n *

      The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.

      \n *\n *

      A null input String returns null.\n * A null separatorChars splits on whitespace.

      \n *\n *

      If more than max delimited substrings are found, the last\n * returned string includes all characters after the first max - 1\n * returned strings (including separator characters).

      \n *\n *
      \n     * StringUtils.split(null, *, *)            = null\n     * StringUtils.split(\"\", *, *)              = []\n     * StringUtils.split(\"ab de fg\", null, 0)   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab   de fg\", null, 0) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\", 0)    = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\", 2)    = [\"ab\", \"cd:ef\"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str, final String separatorChars, final int max) {\n return StringUtils.splitWorker(str, separatorChars, max, false);\n }\n\n /**\n *

      Splits the provided text into an array, separator string specified.

      \n *\n *

      The separator(s) will not be included in the returned String array.\n * Adjacent separators are treated as one separator.

      \n *\n *

      A null input String returns null.\n * A null separator splits on whitespace.

      \n *\n *
      \n     * StringUtils.splitByWholeSeparator(null, *)               = null\n     * StringUtils.splitByWholeSeparator(\"\", *)                 = []\n     * StringUtils.splitByWholeSeparator(\"ab de fg\", null)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab   de fg\", null)    = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab:cd:ef\", \":\")       = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\") = [\"ab\", \"cd\", \"ef\"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String was input\n */\n public static String[] splitByWholeSeparator(final String str, final String separator) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, -1, false);\n }\n\n /**\n *

      Splits the provided text into an array, separator string specified.\n * Returns a maximum of max substrings.

      \n *\n *

      The separator(s) will not be included in the returned String array.\n * Adjacent separators are treated as one separator.

      \n *\n *

      A null input String returns null.\n * A null separator splits on whitespace.

      \n *\n *
      \n     * StringUtils.splitByWholeSeparator(null, *, *)               = null\n     * StringUtils.splitByWholeSeparator(\"\", *, *)                 = []\n     * StringUtils.splitByWholeSeparator(\"ab de fg\", null, 0)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab   de fg\", null, 0)    = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab:cd:ef\", \":\", 2)       = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\", 5) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\", 2) = [\"ab\", \"cd-!-ef\"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @return an array of parsed Strings, null if null String was input\n */\n public static String[] splitByWholeSeparator(final String str, final String separator, final int max) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, max, false);\n }\n\n /**\n *

      Splits the provided text into an array, separator string specified.

      \n *\n *

      The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

      \n *\n *

      A null input String returns null.\n * A null separator splits on whitespace.

      \n *\n *
      \n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *)               = null\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"\", *)                 = []\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab de fg\", null)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab   de fg\", null)    = [\"ab\", \"\", \"\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab:cd:ef\", \":\")       = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\") = [\"ab\", \"cd\", \"ef\"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String was input\n * @since 2.4\n */\n public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, -1, true);\n }\n\n /**\n *

      Splits the provided text into an array, separator string specified.\n * Returns a maximum of max substrings.

      \n *\n *

      The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

      \n *\n *

      A null input String returns null.\n * A null separator splits on whitespace.

      \n *\n *
      \n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *)               = null\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"\", *, *)                 = []\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab de fg\", null, 0)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab   de fg\", null, 0)    = [\"ab\", \"\", \"\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab:cd:ef\", \":\", 2)       = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\", 5) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\", 2) = [\"ab\", \"cd-!-ef\"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @return an array of parsed Strings, null if null String was input\n * @since 2.4\n */\n public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator, final int max) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, max, true);\n }\n\n /**\n * Performs the logic for the splitByWholeSeparatorPreserveAllTokens methods.\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n private static String[] splitByWholeSeparatorWorker(final String str, final String separator, final int max, final boolean preserveAllTokens) {\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n if (separator == null || StringUtils.EMPTY.equals(separator)) {\n // Split on whitespace.\n return StringUtils.splitWorker(str, null, max, preserveAllTokens);\n }\n int separatorLength = separator.length();\n ArrayList substrings = new ArrayList<>();\n int numberOfSubstrings = 0;\n int beg = 0;\n int end = 0;\n while (end < len) {\n end = str.indexOf(separator, beg);\n if (end > -1) {\n if (end > beg) {\n numberOfSubstrings += 1;\n if (numberOfSubstrings == max) {\n end = len;\n substrings.add(str.substring(beg));\n } else {\n // The following is OK, because String.substring( beg, end ) excludes\n // the character at the position 'end'.\n substrings.add(str.substring(beg, end));\n // Set the starting point for the next search.\n // The following is equivalent to beg = end + (separatorLength - 1) + 1,\n // which is the right calculation:\n beg = end + separatorLength;\n }\n } else {\n // We found a consecutive occurrence of the separator, so skip it.\n if (preserveAllTokens) {\n numberOfSubstrings += 1;\n if (numberOfSubstrings == max) {\n end = len;\n substrings.add(str.substring(beg));\n } else {\n substrings.add(StringUtils.EMPTY);\n }\n }\n beg = end + separatorLength;\n }\n } else {\n // String.substring( beg ) goes from 'beg' to the end of the String.\n substrings.add(str.substring(beg));\n end = len;\n }\n }\n return substrings.toArray(new String[0]);\n }\n // -----------------------------------------------------------------------\n\n /**\n *

      Splits the provided text into an array, using whitespace as the\n * separator, preserving all tokens, including empty tokens created by\n * adjacent separators. This is an alternative to using StringTokenizer.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

      \n *\n *

      The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

      \n *\n *

      A null input String returns null.

      \n *\n *
      \n     * StringUtils.splitPreserveAllTokens(null)       = null\n     * StringUtils.splitPreserveAllTokens(\"\")         = []\n     * StringUtils.splitPreserveAllTokens(\"abc def\")  = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc  def\") = [\"abc\", \"\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\" abc \")    = [\"\", \"abc\", \"\"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str) {\n return StringUtils.splitWorker(str, null, -1, true);\n }\n\n /**\n *

      Splits the provided text into an array, separator specified,\n * preserving all tokens, including empty tokens created by adjacent\n * separators. This is an alternative to using StringTokenizer.

      \n *\n *

      The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

      \n *\n *

      A null input String returns null.

      \n *\n *
      \n     * StringUtils.splitPreserveAllTokens(null, *)         = null\n     * StringUtils.splitPreserveAllTokens(\"\", *)           = []\n     * StringUtils.splitPreserveAllTokens(\"a.b.c\", '.')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a..b.c\", '.')   = [\"a\", \"\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a:b:c\", '.')    = [\"a:b:c\"]\n     * StringUtils.splitPreserveAllTokens(\"a\\tb\\nc\", null) = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c\", ' ')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c \", ' ')   = [\"a\", \"b\", \"c\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c  \", ' ')   = [\"a\", \"b\", \"c\", \"\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\" a b c\", ' ')   = [\"\", a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"  a b c\", ' ')  = [\"\", \"\", a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\" a b c \", ' ')  = [\"\", a\", \"b\", \"c\", \"\"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @param separatorChar the character used as the delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final char separatorChar) {\n return StringUtils.splitWorker(str, separatorChar, true);\n }\n\n /**\n * Performs the logic for the split and\n * splitPreserveAllTokens methods that do not return a\n * maximum array length.\n *\n * @param str the String to parse, may be null\n * @param separatorChar the separate character\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n */\n private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n List list = new ArrayList<>();\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n while (i < len) {\n if (str.charAt(i) == separatorChar) {\n if (match || preserveAllTokens) {\n list.add(str.substring(start, i));\n match = false;\n lastMatch = true;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[0]);\n }\n\n /**\n *

      Splits the provided text into an array, separators specified,\n * preserving all tokens, including empty tokens created by adjacent\n * separators. This is an alternative to using StringTokenizer.

      \n *\n *

      The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

      \n *\n *

      A null input String returns null.\n * A null separatorChars splits on whitespace.

      \n *\n *
      \n     * StringUtils.splitPreserveAllTokens(null, *)           = null\n     * StringUtils.splitPreserveAllTokens(\"\", *)             = []\n     * StringUtils.splitPreserveAllTokens(\"abc def\", null)   = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc def\", \" \")    = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc  def\", \" \")   = [\"abc\", \"\", def\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\")   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef:\", \":\")  = [\"ab\", \"cd\", \"ef\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef::\", \":\") = [\"ab\", \"cd\", \"ef\", \"\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"ab::cd:ef\", \":\")  = [\"ab\", \"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\":cd:ef\", \":\")     = [\"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"::cd:ef\", \":\")    = [\"\", \"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\":cd:ef:\", \":\")    = [\"\", cd\", \"ef\", \"\"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final String separatorChars) {\n return StringUtils.splitWorker(str, separatorChars, -1, true);\n }\n\n /**\n *

      Splits the provided text into an array with a maximum length,\n * separators specified, preserving all tokens, including empty tokens\n * created by adjacent separators.

      \n *\n *

      The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * Adjacent separators are treated as one separator.

      \n *\n *

      A null input String returns null.\n * A null separatorChars splits on whitespace.

      \n *\n *

      If more than max delimited substrings are found, the last\n * returned string includes all characters after the first max - 1\n * returned strings (including separator characters).

      \n *\n *
      \n     * StringUtils.splitPreserveAllTokens(null, *, *)            = null\n     * StringUtils.splitPreserveAllTokens(\"\", *, *)              = []\n     * StringUtils.splitPreserveAllTokens(\"ab de fg\", null, 0)   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 0) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\", 0)    = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\", 2)    = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 2) = [\"ab\", \"  de fg\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 3) = [\"ab\", \"\", \" de fg\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 4) = [\"ab\", \"\", \"\", \"de fg\"]\n     * 
      \n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) {\n return StringUtils.splitWorker(str, separatorChars, max, true);\n }\n\n /**\n * Performs the logic for the split and\n * splitPreserveAllTokens methods that return a maximum array\n * length.\n *\n * @param str the String to parse, may be null\n * @param separatorChars the separate character\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit.\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n */\n private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n // Direct code is quicker than StringTokenizer.\n // Also, StringTokenizer uses isSpace() not isWhitespace()\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n List list = new ArrayList<>();\n int sizePlus1 = 1;\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n if (separatorChars == null) {\n // Null separator means use whitespace\n while (i < len) {\n if (Character.isWhitespace(str.charAt(i))) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else if (separatorChars.length() == 1) {\n // Optimise 1 character case\n char sep = separatorChars.charAt(0);\n while (i < len) {\n if (str.charAt(i) == sep) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else {\n // standard case\n while (i < len) {\n if (separatorChars.indexOf(str.charAt(i)) >= 0) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[0]);\n }\n\n /**\n *

      Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens.\n *

      \n     * StringUtils.splitByCharacterType(null)         = null\n     * StringUtils.splitByCharacterType(\"\")           = []\n     * StringUtils.splitByCharacterType(\"ab de fg\")   = [\"ab\", \" \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterType(\"ab   de fg\") = [\"ab\", \"   \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterType(\"ab:cd:ef\")   = [\"ab\", \":\", \"cd\", \":\", \"ef\"]\n     * StringUtils.splitByCharacterType(\"number5\")    = [\"number\", \"5\"]\n     * StringUtils.splitByCharacterType(\"fooBar\")     = [\"foo\", \"B\", \"ar\"]\n     * StringUtils.splitByCharacterType(\"foo200Bar\")  = [\"foo\", \"200\", \"B\", \"ar\"]\n     * StringUtils.splitByCharacterType(\"ASFRules\")   = [\"ASFR\", \"ules\"]\n     * 
      \n * @param str the String to split, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n public static String[] splitByCharacterType(final String str) {\n return StringUtils.splitByCharacterType(str, false);\n }\n\n /**\n *

      Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens, with the\n * following exception: the character of type\n * Character.UPPERCASE_LETTER, if any, immediately\n * preceding a token of type Character.LOWERCASE_LETTER\n * will belong to the following token rather than to the preceding, if any,\n * Character.UPPERCASE_LETTER token.\n *

      \n     * StringUtils.splitByCharacterTypeCamelCase(null)         = null\n     * StringUtils.splitByCharacterTypeCamelCase(\"\")           = []\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab de fg\")   = [\"ab\", \" \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab   de fg\") = [\"ab\", \"   \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab:cd:ef\")   = [\"ab\", \":\", \"cd\", \":\", \"ef\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"number5\")    = [\"number\", \"5\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"fooBar\")     = [\"foo\", \"Bar\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"foo200Bar\")  = [\"foo\", \"200\", \"Bar\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ASFRules\")   = [\"ASF\", \"Rules\"]\n     * 
      \n * @param str the String to split, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n public static String[] splitByCharacterTypeCamelCase(final String str) {\n return StringUtils.splitByCharacterType(str, true);\n }\n\n /**\n *

      Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens, with the\n * following exception: if camelCase is true,\n * the character of type Character.UPPERCASE_LETTER, if any,\n * immediately preceding a token of type Character.LOWERCASE_LETTER\n * will belong to the following token rather than to the preceding, if any,\n * Character.UPPERCASE_LETTER token.\n * @param str the String to split, may be null\n * @param camelCase whether to use so-called \"camel-case\" for letter types\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n private static String[] splitByCharacterType(final String str, final boolean camelCase) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n char[] c = str.toCharArray();\n List list = new ArrayList();\n int tokenStart = 0;\n int currentType = Character.getType(c[tokenStart]);\n for (int pos = tokenStart + 1; pos < c.length; pos++) {\n int type = Character.getType(c[pos]);\n if (type == currentType) {\n continue;\n }\n if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) {\n int newTokenStart = pos - 1;\n if (newTokenStart != tokenStart) {\n list.add(new String(c, tokenStart, newTokenStart - tokenStart));\n tokenStart = newTokenStart;\n }\n } else {\n list.add(new String(c, tokenStart, pos - tokenStart));\n tokenStart = pos;\n }\n currentType = type;\n }\n list.add(new String(c, tokenStart, c.length - tokenStart));\n return list.toArray(new String[0]);\n }\n // Joining\n //-----------------------------------------------------------------------\n\n /**\n *

      Joins the elements of the provided array into a single String\n * containing the provided list of elements.

      \n *\n *

      No separator is added to the joined String.\n * Null objects or empty strings within the array are represented by\n * empty strings.

      \n *\n *
      \n     * StringUtils.join(null)            = null\n     * StringUtils.join([])              = \"\"\n     * StringUtils.join([null])          = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"]) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"]) = \"a\"\n     * 
      \n *\n * @param array the array of values to join together, may be null\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array) {\n return StringUtils.join(array, null);\n }\n\n /**\n *

      Joins the elements of the provided array into a single String\n * containing the provided list of elements.

      \n *\n *

      No delimiter is added before or after the list.\n * Null objects or empty strings within the array are represented by\n * empty strings.

      \n *\n *
      \n     * StringUtils.join(null, *)               = null\n     * StringUtils.join([], *)                 = \"\"\n     * StringUtils.join([null], *)             = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], ';')  = \"a;b;c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ';')  = \";;a\"\n     * 
      \n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array, final char separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array, separator, 0, array.length);\n }\n\n /**\n *

      Joins the elements of the provided array into a single String\n * containing the provided list of elements.

      \n *\n *

      No delimiter is added before or after the list.\n * Null objects or empty strings within the array are represented by\n * empty strings.

      \n *\n *
      \n     * StringUtils.join(null, *)               = null\n     * StringUtils.join([], *)                 = \"\"\n     * StringUtils.join([null], *)             = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], ';')  = \"a;b;c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ';')  = \";;a\"\n     * 
      \n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use\n * @param startIndex the first index to start joining from. It is\n * an error to pass in an end index past the end of the array\n * @param endIndex the index to stop joining from (exclusive). It is\n * an error to pass in an end index past the end of the array\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) {\n if (array == null) {\n return null;\n }\n int bufSize = endIndex - startIndex;\n if (bufSize <= 0) {\n return StringUtils.EMPTY;\n }\n bufSize *= (array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1;\n StringBuilder buf = new StringBuilder(bufSize);\n for (int i = startIndex; i < endIndex; i++) {\n if (i > startIndex) {\n buf.append(separator);\n }\n if (array[i] != null) {\n buf.append(array[i]);\n }\n }\n return buf.toString();\n }\n\n /**\n *

      Joins the elements of the provided array into a single String\n * containing the provided list of elements.

      \n *\n *

      No delimiter is added before or after the list.\n * A null separator is the same as an empty String (\"\").\n * Null objects or empty strings within the array are represented by\n * empty strings.

      \n *\n *
      \n     * StringUtils.join(null, *)                = null\n     * StringUtils.join([], *)                  = \"\"\n     * StringUtils.join([null], *)              = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"--\")  = \"a--b--c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null)  = \"abc\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"\")    = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ',')   = \",,a\"\n     * 
      \n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use, null treated as \"\"\n * @return the joined String, null if null array input\n */\n public static String join(final Object[] array, final String separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array, separator, 0, array.length);\n }\n\n /**\n *

      Joins the elements of the provided array into a single String\n * containing the provided list of elements.

      \n *\n *

      No delimiter is added before or after the list.\n * A null separator is the same as an empty String (\"\").\n * Null objects or empty strings within the array are represented by\n * empty strings.

      \n *\n *
      \n     * StringUtils.join(null, *)                = null\n     * StringUtils.join([], *)                  = \"\"\n     * StringUtils.join([null], *)              = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"--\")  = \"a--b--c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null)  = \"abc\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"\")    = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ',')   = \",,a\"\n     * 
      \n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use, null treated as \"\"\n * @param startIndex the first index to start joining from. It is\n * an error to pass in an end index past the end of the array\n * @param endIndex the index to stop joining from (exclusive). It is\n * an error to pass in an end index past the end of the array\n * @return the joined String, null if null array input\n */\n public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {\n if (array == null) {\n return null;\n }\n if (separator == null) {\n separator = StringUtils.EMPTY;\n }\n // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))\n // (Assuming that all Strings are roughly equally long)\n int bufSize = endIndex - startIndex;\n if (bufSize <= 0) {\n return StringUtils.EMPTY;\n }\n bufSize *= (array[startIndex] == null ? 16 : array[startIndex].toString().length()) + separator.length();\n StringBuilder buf = new StringBuilder(bufSize);\n for (int i = startIndex; i < endIndex; i++) {\n if (i > startIndex) {\n buf.append(separator);\n }\n if (array[i] != null) {\n buf.append(array[i]);\n }\n }\n return buf.toString();\n }\n // Delete\n //-----------------------------------------------------------------------\n\n /**\n *

      Deletes all whitespaces from a String as defined by\n * {@link Character#isWhitespace(char)}.

      \n *\n *
      \n     * StringUtils.deleteWhitespace(null)         = null\n     * StringUtils.deleteWhitespace(\"\")           = \"\"\n     * StringUtils.deleteWhitespace(\"abc\")        = \"abc\"\n     * StringUtils.deleteWhitespace(\"   ab  c  \") = \"abc\"\n     * 
      \n *\n * @param str the String to delete whitespace from, may be null\n * @return the String without whitespaces, null if null String input\n */\n public static String deleteWhitespace(final String str) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n int sz = str.length();\n char[] chs = new char[sz];\n int count = 0;\n for (int i = 0; i < sz; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n chs[count++] = str.charAt(i);\n }\n }\n if (count == sz) {\n return str;\n }\n return new String(chs, 0, count);\n }\n // Remove\n //-----------------------------------------------------------------------\n\n /**\n *

      Removes a substring only if it is at the begining of a source string,\n * otherwise returns the source string.

      \n *\n *

      A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

      \n *\n *
      \n     * StringUtils.removeStart(null, *)      = null\n     * StringUtils.removeStart(\"\", *)        = \"\"\n     * StringUtils.removeStart(*, null)      = *\n     * StringUtils.removeStart(\"www.domain.com\", \"www.\")   = \"domain.com\"\n     * StringUtils.removeStart(\"domain.com\", \"www.\")       = \"domain.com\"\n     * StringUtils.removeStart(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeStart(\"abc\", \"\")    = \"abc\"\n     * 
      \n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String removeStart(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (str.startsWith(remove)) {\n return str.substring(remove.length());\n }\n return str;\n }\n\n /**\n *

      Case insensitive removal of a substring if it is at the begining of a source string,\n * otherwise returns the source string.

      \n *\n *

      A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

      \n *\n *
      \n     * StringUtils.removeStartIgnoreCase(null, *)      = null\n     * StringUtils.removeStartIgnoreCase(\"\", *)        = \"\"\n     * StringUtils.removeStartIgnoreCase(*, null)      = *\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"www.\")   = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"WWW.\")   = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"domain.com\", \"www.\")       = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"abc\", \"\")    = \"abc\"\n     * 
      \n *\n * @param str the source String to search, may be null\n * @param remove the String to search for (case insensitive) and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.4\n */\n public static String removeStartIgnoreCase(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (StringUtils.startsWithIgnoreCase(str, remove)) {\n return str.substring(remove.length());\n }\n return str;\n }\n\n /**\n *

      Removes a substring only if it is at the end of a source string,\n * otherwise returns the source string.

      \n *\n *

      A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

      \n *\n *
      \n     * StringUtils.removeEnd(null, *)      = null\n     * StringUtils.removeEnd(\"\", *)        = \"\"\n     * StringUtils.removeEnd(*, null)      = *\n     * StringUtils.removeEnd(\"www.domain.com\", \".com.\")  = \"www.domain.com\"\n     * StringUtils.removeEnd(\"www.domain.com\", \".com\")   = \"www.domain\"\n     * StringUtils.removeEnd(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeEnd(\"abc\", \"\")    = \"abc\"\n     * 
      \n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String removeEnd(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (str.endsWith(remove)) {\n return str.substring(0, str.length() - remove.length());\n }\n return str;\n }\n\n /**\n *

      Case insensitive removal of a substring if it is at the end of a source string,\n * otherwise returns the source string.

      \n *\n *

      A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

      \n *\n *
      \n     * StringUtils.removeEndIgnoreCase(null, *)      = null\n     * StringUtils.removeEndIgnoreCase(\"\", *)        = \"\"\n     * StringUtils.removeEndIgnoreCase(*, null)      = *\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".com.\")  = \"www.domain.com\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".com\")   = \"www.domain\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeEndIgnoreCase(\"abc\", \"\")    = \"abc\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".COM\") = \"www.domain\")\n     * StringUtils.removeEndIgnoreCase(\"www.domain.COM\", \".com\") = \"www.domain\")\n     * 
      \n *\n * @param str the source String to search, may be null\n * @param remove the String to search for (case insensitive) and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.4\n */\n public static String removeEndIgnoreCase(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (StringUtils.endsWithIgnoreCase(str, remove)) {\n return str.substring(0, str.length() - remove.length());\n }\n return str;\n }\n\n /**\n *

      Removes all occurrences of a substring from within the source string.

      \n *\n *

      A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null remove string will return the source string.\n * An empty (\"\") remove string will return the source string.

      \n *\n *
      \n     * StringUtils.remove(null, *)        = null\n     * StringUtils.remove(\"\", *)          = \"\"\n     * StringUtils.remove(*, null)        = *\n     * StringUtils.remove(*, \"\")          = *\n     * StringUtils.remove(\"queued\", \"ue\") = \"qd\"\n     * StringUtils.remove(\"queued\", \"zz\") = \"queued\"\n     * 
      \n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String remove(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n return StringUtils.replace(str, remove, StringUtils.EMPTY, -1);\n }\n\n /**\n *

      Removes all occurrences of a character from within the source string.

      \n *\n *

      A null source string will return null.\n * An empty (\"\") source string will return the empty string.

      \n *\n *
      \n     * StringUtils.remove(null, *)       = null\n     * StringUtils.remove(\"\", *)         = \"\"\n     * StringUtils.remove(\"queued\", 'u') = \"qeed\"\n     * StringUtils.remove(\"queued\", 'z') = \"queued\"\n     * 
      \n *\n * @param str the source String to search, may be null\n * @param remove the char to search for and remove, may be null\n * @return the substring with the char removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String remove(final String str, final char remove) {\n if (StringUtils.isEmpty(str) || str.indexOf(remove) == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n char[] chars = str.toCharArray();\n int pos = 0;\n for (int i = 0; i < chars.length; i++) {\n if (chars[i] != remove) {\n chars[pos++] = chars[i];\n }\n }\n return new String(chars, 0, pos);\n }\n // Replacing\n //-----------------------------------------------------------------------\n\n /**\n *

      Replaces a String with another String inside a larger String, once.

      \n *\n *

      A null reference passed to this method is a no-op.

      \n *\n *
      \n     * StringUtils.replaceOnce(null, *, *)        = null\n     * StringUtils.replaceOnce(\"\", *, *)          = \"\"\n     * StringUtils.replaceOnce(\"any\", null, *)    = \"any\"\n     * StringUtils.replaceOnce(\"any\", *, null)    = \"any\"\n     * StringUtils.replaceOnce(\"any\", \"\", *)      = \"any\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", null)  = \"aba\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", \"\")    = \"ba\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", \"z\")   = \"zba\"\n     * 
      \n *\n * @see #replace(String text, String searchString, String replacement, int max)\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace with, may be null\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replaceOnce(final String text, final String searchString, final String replacement) {\n return StringUtils.replace(text, searchString, replacement, 1);\n }\n\n /**\n *

      Replaces all occurrences of a String within another String.

      \n *\n *

      A null reference passed to this method is a no-op.

      \n *\n *
      \n     * StringUtils.replace(null, *, *)        = null\n     * StringUtils.replace(\"\", *, *)          = \"\"\n     * StringUtils.replace(\"any\", null, *)    = \"any\"\n     * StringUtils.replace(\"any\", *, null)    = \"any\"\n     * StringUtils.replace(\"any\", \"\", *)      = \"any\"\n     * StringUtils.replace(\"aba\", \"a\", null)  = \"aba\"\n     * StringUtils.replace(\"aba\", \"a\", \"\")    = \"b\"\n     * StringUtils.replace(\"aba\", \"a\", \"z\")   = \"zbz\"\n     * 
      \n *\n * @see #replace(String text, String searchString, String replacement, int max)\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace it with, may be null\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replace(final String text, final String searchString, final String replacement) {\n return StringUtils.replace(text, searchString, replacement, -1);\n }\n\n /**\n *

      Replaces a String with another String inside a larger String,\n * for the first max values of the search String.

      \n *\n *

      A null reference passed to this method is a no-op.

      \n *\n *
      \n     * StringUtils.replace(null, *, *, *)         = null\n     * StringUtils.replace(\"\", *, *, *)           = \"\"\n     * StringUtils.replace(\"any\", null, *, *)     = \"any\"\n     * StringUtils.replace(\"any\", *, null, *)     = \"any\"\n     * StringUtils.replace(\"any\", \"\", *, *)       = \"any\"\n     * StringUtils.replace(\"any\", *, *, 0)        = \"any\"\n     * StringUtils.replace(\"abaa\", \"a\", null, -1) = \"abaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"\", -1)   = \"b\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 0)   = \"abaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 1)   = \"zbaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 2)   = \"zbza\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", -1)  = \"zbzz\"\n     * 
      \n *\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace it with, may be null\n * @param max maximum number of values to replace, or -1 if no maximum\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replace(final String text, final String searchString, final String replacement, int max) {\n if (StringUtils.isEmpty(text) || StringUtils.isEmpty(searchString) || replacement == null || max == 0) {\n return text;\n }\n int start = 0;\n int end = text.indexOf(searchString, start);\n if (end == StringUtils.INDEX_NOT_FOUND) {\n return text;\n }\n int replLength = searchString.length();\n int increase = replacement.length() - replLength;\n increase = Math.max(increase, 0);\n increase *= max < 0 ? 16 : Math.min(max, 64);\n StringBuilder buf = new StringBuilder(text.length() + increase);\n while (end != StringUtils.INDEX_NOT_FOUND) {\n buf.append(text.substring(start, end)).append(replacement);\n start = end + replLength;\n if (--max == 0) {\n break;\n }\n end = text.indexOf(searchString, start);\n }\n buf.append(text.substring(start));\n return buf.toString();\n }\n\n /**\n *

      \n * Replaces all occurrences of Strings within another String.\n *

      \n *\n *

      \n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored. This will not repeat. For repeating replaces, call the\n * overloaded method.\n *

      \n *\n *
      \n     *  StringUtils.replaceEach(null, *, *)        = null\n     *  StringUtils.replaceEach(\"\", *, *)          = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0]) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null)  = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"})  = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"})  = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"})  = \"wcte\"\n     *  (example of how it does not repeat)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"})  = \"dcte\"\n     * 
      \n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) {\n return StringUtils.replaceEach(text, searchList, replacementList, false, 0);\n }\n\n /**\n *

      \n * Replaces all occurrences of Strings within another String.\n *

      \n *\n *

      \n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored. This will not repeat. For repeating replaces, call the\n * overloaded method.\n *

      \n *\n *
      \n     *  StringUtils.replaceEach(null, *, *, *) = null\n     *  StringUtils.replaceEach(\"\", *, *, *) = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0], *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"}, *) = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"}, *) = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"}, *) = \"wcte\"\n     *  (example of how it repeats)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, false) = \"dcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, true) = \"tcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, true) = IllegalArgumentException\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, false) = \"dcabe\"\n     * 
      \n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IllegalArgumentException\n * if the search is repeating and there is an endless loop due\n * to outputs of one being inputs to another\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) {\n // timeToLive should be 0 if not used or nothing to replace, else it's\n // the length of the replace array\n int timeToLive = searchList == null ? 0 : searchList.length;\n return StringUtils.replaceEach(text, searchList, replacementList, true, timeToLive);\n }\n\n /**\n *

      \n * Replaces all occurrences of Strings within another String.\n *

      \n *\n *

      \n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored.\n *

      \n *\n *
      \n     *  StringUtils.replaceEach(null, *, *, *) = null\n     *  StringUtils.replaceEach(\"\", *, *, *) = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0], *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"}, *) = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"}, *) = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"}, *) = \"wcte\"\n     *  (example of how it repeats)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, false) = \"dcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, true) = \"tcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, *) = IllegalArgumentException\n     * 
      \n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @param repeat if true, then replace repeatedly\n * until there are no more possible replacements or timeToLive < 0\n * @param timeToLive\n * if less than 0 then there is a circular reference and endless\n * loop\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IllegalArgumentException\n * if the search is repeating and there is an endless loop due\n * to outputs of one being inputs to another\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n private static String replaceEach(final String text, final String[] searchList, final String[] replacementList, final boolean repeat, final int timeToLive) {\n // mchyzer Performance note: This creates very few new objects (one major goal)\n // let me know if there are performance requests, we can create a harness to measure\n if (text == null || text.length() == 0 || searchList == null || searchList.length == 0 || replacementList == null || replacementList.length == 0) {\n return text;\n }\n // if recursing, this shouldnt be less than 0\n if (timeToLive < 0) {\n throw new IllegalStateException(\"TimeToLive of \" + timeToLive + \" is less than 0: \" + text);\n }\n int searchLength = searchList.length;\n int replacementLength = replacementList.length;\n // make sure lengths are ok, these need to be equal\n if (searchLength != replacementLength) {\n throw new IllegalArgumentException(\"Search and Replace array lengths don't match: \" + searchLength + \" vs \" + replacementLength);\n }\n // keep track of which still have matches\n boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];\n // index on index that the match was found\n int textIndex = -1;\n int replaceIndex = -1;\n int tempIndex = -1;\n // index of replace array that will replace the search string found\n // NOTE: logic duplicated below START\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) {\n continue;\n }\n tempIndex = text.indexOf(searchList[i]);\n // see if we need to keep searching for this\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n // NOTE: logic mostly below END\n // no search strings found, we are done\n if (textIndex == -1) {\n return text;\n }\n int start = 0;\n // get a good guess on the size of the result buffer so it doesnt have to double if it goes over a bit\n int increase = 0;\n // count the replacement text elements that are larger than their corresponding text being replaced\n for (int i = 0; i < searchList.length; i++) {\n if (searchList[i] == null || replacementList[i] == null) {\n continue;\n }\n int greater = replacementList[i].length() - searchList[i].length();\n if (greater > 0) {\n increase += 3 * greater; // assume 3 matches\n }\n }\n // have upper-bound at 20% increase, then let Java take over\n increase = Math.min(increase, text.length() / 5);\n StringBuilder buf = new StringBuilder(text.length() + increase);\n while (textIndex != -1) {\n for (int i = start; i < textIndex; i++) {\n buf.append(text.charAt(i));\n }\n buf.append(replacementList[replaceIndex]);\n start = textIndex + searchList[replaceIndex].length();\n textIndex = -1;\n replaceIndex = -1;\n tempIndex = -1;\n // find the next earliest match\n // NOTE: logic mostly duplicated above START\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) {\n continue;\n }\n tempIndex = text.indexOf(searchList[i], start);\n // see if we need to keep searching for this\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n // NOTE: logic duplicated above END\n }\n int textLength = text.length();\n for (int i = start; i < textLength; i++) {\n buf.append(text.charAt(i));\n }\n String result = buf.toString();\n if (!repeat) {\n return result;\n }\n return StringUtils.replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);\n }\n // Replace, character based\n //-----------------------------------------------------------------------\n\n /**\n *

      Replaces all occurrences of a character in a String with another.\n * This is a null-safe version of {@link String#replace(char, char)}.

      \n *\n *

      A null string input returns null.\n * An empty (\"\") string input returns an empty string.

      \n *\n *
      \n     * StringUtils.replaceChars(null, *, *)        = null\n     * StringUtils.replaceChars(\"\", *, *)          = \"\"\n     * StringUtils.replaceChars(\"abcba\", 'b', 'y') = \"aycya\"\n     * StringUtils.replaceChars(\"abcba\", 'z', 'y') = \"abcba\"\n     * 
      \n *\n * @param str String to replace characters in, may be null\n * @param searchChar the character to search for, may be null\n * @param replaceChar the character to replace, may be null\n * @return modified String, null if null string input\n * @since 2.0\n */\n public static String replaceChars(final String str, final char searchChar, final char replaceChar) {\n if (str == null) {\n return null;\n }\n return str.replace(searchChar, replaceChar);\n }\n\n /**\n *

      Replaces multiple characters in a String in one go.\n * This method can also be used to delete characters.

      \n *\n *

      For example:
      \n * replaceChars("hello", "ho", "jy") = jelly.

      \n *\n *

      A null string input returns null.\n * An empty (\"\") string input returns an empty string.\n * A null or empty set of search characters returns the input string.

      \n *\n *

      The length of the search characters should normally equal the length\n * of the replace characters.\n * If the search characters is longer, then the extra search characters\n * are deleted.\n * If the search characters is shorter, then the extra replace characters\n * are ignored.

      \n *\n *
      \n     * StringUtils.replaceChars(null, *, *)           = null\n     * StringUtils.replaceChars(\"\", *, *)             = \"\"\n     * StringUtils.replaceChars(\"abc\", null, *)       = \"abc\"\n     * StringUtils.replaceChars(\"abc\", \"\", *)         = \"abc\"\n     * StringUtils.replaceChars(\"abc\", \"b\", null)     = \"ac\"\n     * StringUtils.replaceChars(\"abc\", \"b\", \"\")       = \"ac\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"yz\")  = \"ayzya\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"y\")   = \"ayya\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"yzx\") = \"ayzya\"\n     * 
      \n *\n * @param str String to replace characters in, may be null\n * @param searchChars a set of characters to search for, may be null\n * @param replaceChars a set of characters to replace, may be null\n * @return modified String, null if null string input\n * @since 2.0\n */\n public static String replaceChars(final String str, final String searchChars, String replaceChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return str;\n }\n if (replaceChars == null) {\n replaceChars = StringUtils.EMPTY;\n }\n boolean modified = false;\n int replaceCharsLength = replaceChars.length();\n int strLength = str.length();\n StringBuilder buf = new StringBuilder(strLength);\n for (int i = 0; i < strLength; i++) {\n char ch = str.charAt(i);\n int index = searchChars.indexOf(ch);\n if (index >= 0) {\n modified = true;\n if (index < replaceCharsLength) {\n buf.append(replaceChars.charAt(index));\n }\n } else {\n buf.append(ch);\n }\n }\n if (modified) {\n return buf.toString();\n }\n return str;\n }\n // Overlay\n //-----------------------------------------------------------------------\n\n /**\n *

      Overlays part of a String with another String.

      \n *\n *

      A null string input returns null.\n * A negative index is treated as zero.\n * An index greater than the string length is treated as the string length.\n * The start index is always the smaller of the two indices.

      \n *\n *
      \n     * StringUtils.overlay(null, *, *, *)            = null\n     * StringUtils.overlay(\"\", \"abc\", 0, 0)          = \"abc\"\n     * StringUtils.overlay(\"abcdef\", null, 2, 4)     = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"\", 2, 4)       = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"\", 4, 2)       = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 2, 4)   = \"abzzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 4, 2)   = \"abzzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", -1, 4)  = \"zzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 2, 8)   = \"abzzzz\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", -2, -3) = \"zzzzabcdef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 8, 10)  = \"abcdefzzzz\"\n     * 
      \n *\n * @param str the String to do overlaying in, may be null\n * @param overlay the String to overlay, may be null\n * @param start the position to start overlaying at\n * @param end the position to stop overlaying before\n * @return overlayed String, null if null String input\n * @since 2.0\n */\n public static String overlay(final String str, String overlay, int start, int end) {\n if (str == null) {\n return null;\n }\n if (overlay == null) {\n overlay = StringUtils.EMPTY;\n }\n int len = str.length();\n if (start < 0) {\n start = 0;\n }\n if (start > len) {\n start = len;\n }\n if (end < 0) {\n end = 0;\n }\n if (end > len) {\n end = len;\n }\n if (start > end) {\n int temp = start;\n start = end;\n end = temp;\n }\n return str.substring(0, start) + overlay + str.substring(end);\n }\n // Chomping\n //-----------------------------------------------------------------------\n\n /**\n *

      Removes one newline from end of a String if it's there,\n * otherwise leave it alone. A newline is "\\n",\n * "\\r", or "\\r\\n".

      \n *\n *

      NOTE: This method changed in 2.0.\n * It now more closely matches Perl chomp.

      \n *\n *
      \n     * StringUtils.chomp(null)          = null\n     * StringUtils.chomp(\"\")            = \"\"\n     * StringUtils.chomp(\"abc \\r\")      = \"abc \"\n     * StringUtils.chomp(\"abc\\n\")       = \"abc\"\n     * StringUtils.chomp(\"abc\\r\\n\")     = \"abc\"\n     * StringUtils.chomp(\"abc\\r\\n\\r\\n\") = \"abc\\r\\n\"\n     * StringUtils.chomp(\"abc\\n\\r\")     = \"abc\\n\"\n     * StringUtils.chomp(\"abc\\n\\rabc\")  = \"abc\\n\\rabc\"\n     * StringUtils.chomp(\"\\r\")          = \"\"\n     * StringUtils.chomp(\"\\n\")          = \"\"\n     * StringUtils.chomp(\"\\r\\n\")        = \"\"\n     * 
      \n *\n * @param str the String to chomp a newline from, may be null\n * @return String without newline, null if null String input\n */\n public static String chomp(final String str) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (str.length() == 1) {\n char ch = str.charAt(0);\n if (ch == CharUtils.CR || ch == CharUtils.LF) {\n return StringUtils.EMPTY;\n }\n return str;\n }\n int lastIdx = str.length() - 1;\n char last = str.charAt(lastIdx);\n if (last == CharUtils.LF) {\n if (str.charAt(lastIdx - 1) == CharUtils.CR) {\n lastIdx--;\n }\n } else if (last != CharUtils.CR) {\n lastIdx++;\n }\n return str.substring(0, lastIdx);\n }\n\n /**\n *

      Removes separator from the end of\n * str if it's there, otherwise leave it alone.

      \n *\n *

      NOTE: This method changed in version 2.0.\n * It now more closely matches Perl chomp.\n * For the previous behavior, use {@link #substringBeforeLast(String, String)}.\n * This method uses {@link String#endsWith(String)}.

      \n *\n *
      \n     * StringUtils.chomp(null, *)         = null\n     * StringUtils.chomp(\"\", *)           = \"\"\n     * StringUtils.chomp(\"foobar\", \"bar\") = \"foo\"\n     * StringUtils.chomp(\"foobar\", \"baz\") = \"foobar\"\n     * StringUtils.chomp(\"foo\", \"foo\")    = \"\"\n     * StringUtils.chomp(\"foo \", \"foo\")   = \"foo \"\n     * StringUtils.chomp(\" foo\", \"foo\")   = \" \"\n     * StringUtils.chomp(\"foo\", \"foooo\")  = \"foo\"\n     * StringUtils.chomp(\"foo\", \"\")       = \"foo\"\n     * StringUtils.chomp(\"foo\", null)     = \"foo\"\n     * 
      \n *\n * @param str the String to chomp from, may be null\n * @param separator separator String, may be null\n * @return String without trailing separator, null if null String input\n */\n public static String chomp(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || separator == null) {\n return str;\n }\n if (str.endsWith(separator)) {\n return str.substring(0, str.length() - separator.length());\n }\n return str;\n }\n // Chopping\n //-----------------------------------------------------------------------\n\n /**\n *

      Remove the last character from a String.

      \n *\n *

      If the String ends in \\r\\n, then remove both\n * of them.

      \n *\n *
      \n     * StringUtils.chop(null)          = null\n     * StringUtils.chop(\"\")            = \"\"\n     * StringUtils.chop(\"abc \\r\")      = \"abc \"\n     * StringUtils.chop(\"abc\\n\")       = \"abc\"\n     * StringUtils.chop(\"abc\\r\\n\")     = \"abc\"\n     * StringUtils.chop(\"abc\")         = \"ab\"\n     * StringUtils.chop(\"abc\\nabc\")    = \"abc\\nab\"\n     * StringUtils.chop(\"a\")           = \"\"\n     * StringUtils.chop(\"\\r\")          = \"\"\n     * StringUtils.chop(\"\\n\")          = \"\"\n     * StringUtils.chop(\"\\r\\n\")        = \"\"\n     * 
      \n *\n * @param str the String to chop last character from, may be null\n * @return String without last character, null if null String input\n */\n public static String chop(final String str) {\n if (str == null) {\n return null;\n }\n int strLen = str.length();\n if (strLen < 2) {\n return StringUtils.EMPTY;\n }\n int lastIdx = strLen - 1;\n String ret = str.substring(0, lastIdx);\n char last = str.charAt(lastIdx);\n if (last == CharUtils.LF) {\n if (ret.charAt(lastIdx - 1) == CharUtils.CR) {\n return ret.substring(0, lastIdx - 1);\n }\n }\n return ret;\n }\n // Padding\n //-----------------------------------------------------------------------\n\n /**\n *

      Repeat a String repeat times to form a\n * new String.

      \n *\n *
      \n     * StringUtils.repeat(null, 2) = null\n     * StringUtils.repeat(\"\", 0)   = \"\"\n     * StringUtils.repeat(\"\", 2)   = \"\"\n     * StringUtils.repeat(\"a\", 3)  = \"aaa\"\n     * StringUtils.repeat(\"ab\", 2) = \"abab\"\n     * StringUtils.repeat(\"a\", -2) = \"\"\n     * 
      \n *\n * @param character the Character to to repeat, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n */\n public static String repeat(final char character, final int repeat) {\n return repeat(character + \"\", repeat);\n }\n\n /**\n *

      Repeat a String repeat times to form a\n * new String.

      \n *\n *
      \n     * StringUtils.repeat(null, 2) = null\n     * StringUtils.repeat(\"\", 0)   = \"\"\n     * StringUtils.repeat(\"\", 2)   = \"\"\n     * StringUtils.repeat(\"a\", 3)  = \"aaa\"\n     * StringUtils.repeat(\"ab\", 2) = \"abab\"\n     * StringUtils.repeat(\"a\", -2) = \"\"\n     * 
      \n *\n * @param str the String to repeat, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n */\n public static String repeat(final String str, final int repeat) {\n // Performance tuned for 2.0 (JDK1.4)\n if (str == null) {\n return null;\n }\n if (repeat <= 0) {\n return StringUtils.EMPTY;\n }\n int inputLength = str.length();\n if (repeat == 1 || inputLength == 0) {\n return str;\n }\n if (inputLength == 1 && repeat <= StringUtils.PAD_LIMIT) {\n return StringUtils.padding(repeat, str.charAt(0));\n }\n int outputLength = inputLength * repeat;\n switch (inputLength) {\n case 1:\n char ch = str.charAt(0);\n char[] output1 = new char[outputLength];\n for (int i = repeat - 1; i >= 0; i--) {\n output1[i] = ch;\n }\n return new String(output1);\n case 2:\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n char[] output2 = new char[outputLength];\n for (int i = repeat * 2 - 2; i >= 0; i--, i--) {\n output2[i] = ch0;\n output2[i + 1] = ch1;\n }\n return new String(output2);\n default:\n StringBuilder buf = new StringBuilder(outputLength);\n for (int i = 0; i < repeat; i++) {\n buf.append(str);\n }\n return buf.toString();\n }\n }\n\n /**\n *

      Repeat a String repeat times to form a\n * new String, with a String separator injected each time.

      \n *\n *
      \n     * StringUtils.repeat(null, null, 2) = null\n     * StringUtils.repeat(null, \"x\", 2)  = null\n     * StringUtils.repeat(\"\", null, 0)   = \"\"\n     * StringUtils.repeat(\"\", \"\", 2)     = \"\"\n     * StringUtils.repeat(\"\", \"x\", 3)    = \"xxx\"\n     * StringUtils.repeat(\"?\", \", \", 3)  = \"?, ?, ?\"\n     * 
      \n *\n * @param str the String to repeat, may be null\n * @param separator the String to inject, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n * @since 2.5\n */\n public static String repeat(final String str, final String separator, final int repeat) {\n if (str == null || separator == null) {\n return StringUtils.repeat(str, repeat);\n } else {\n // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it\n String result = StringUtils.repeat(str + separator, repeat);\n return StringUtils.removeEnd(result, separator);\n }\n }\n\n /**\n *

      Returns padding using the specified delimiter repeated\n * to a given length.

      \n *\n *
      \n     * StringUtils.padding(0, 'e')  = \"\"\n     * StringUtils.padding(3, 'e')  = \"eee\"\n     * StringUtils.padding(-2, 'e') = IndexOutOfBoundsException\n     * 
      \n *\n *

      Note: this method doesn't not support padding with\n * Unicode Supplementary Characters\n * as they require a pair of chars to be represented.\n * If you are needing to support full I18N of your applications\n * consider using {@link #repeat(String, int)} instead.\n *

      \n *\n * @param repeat number of times to repeat delim\n * @param padChar character to repeat\n * @return String with repeated character\n * @throws IndexOutOfBoundsException if repeat < 0\n * @see #repeat(String, int)\n */\n private static String padding(final int repeat, final char padChar) throws IndexOutOfBoundsException {\n if (repeat < 0) {\n throw new IndexOutOfBoundsException(\"Cannot pad a negative amount: \" + repeat);\n }\n final char[] buf = new char[repeat];\n Arrays.fill(buf, padChar);\n return new String(buf);\n }\n\n /**\n *

      Right pad a String with spaces (' ').

      \n *\n *

      The String is padded to the size of size.

      \n *\n *
      \n     * StringUtils.rightPad(null, *)   = null\n     * StringUtils.rightPad(\"\", 3)     = \"   \"\n     * StringUtils.rightPad(\"bat\", 3)  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5)  = \"bat  \"\n     * StringUtils.rightPad(\"bat\", 1)  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1) = \"bat\"\n     * 
      \n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String rightPad(final String str, final int size) {\n return StringUtils.rightPad(str, size, ' ');\n }\n\n /**\n *

      Right pad a String with a specified character.

      \n *\n *

      The String is padded to the size of size.

      \n *\n *
      \n     * StringUtils.rightPad(null, *, *)     = null\n     * StringUtils.rightPad(\"\", 3, 'z')     = \"zzz\"\n     * StringUtils.rightPad(\"bat\", 3, 'z')  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, 'z')  = \"batzz\"\n     * StringUtils.rightPad(\"bat\", 1, 'z')  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1, 'z') = \"bat\"\n     * 
      \n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padChar the character to pad with\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n * @since 2.0\n */\n public static String rightPad(final String str, final int size, final char padChar) {\n if (str == null) {\n return null;\n }\n int pads = size - str.length();\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (pads > StringUtils.PAD_LIMIT) {\n return StringUtils.rightPad(str, size, String.valueOf(padChar));\n }\n return str.concat(StringUtils.padding(pads, padChar));\n }\n\n /**\n *

      Right pad a String with a specified String.

      \n *\n *

      The String is padded to the size of size.

      \n *\n *
      \n     * StringUtils.rightPad(null, *, *)      = null\n     * StringUtils.rightPad(\"\", 3, \"z\")      = \"zzz\"\n     * StringUtils.rightPad(\"bat\", 3, \"yz\")  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, \"yz\")  = \"batyz\"\n     * StringUtils.rightPad(\"bat\", 8, \"yz\")  = \"batyzyzy\"\n     * StringUtils.rightPad(\"bat\", 1, \"yz\")  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1, \"yz\") = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, null)  = \"bat  \"\n     * StringUtils.rightPad(\"bat\", 5, \"\")    = \"bat  \"\n     * 
      \n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padStr the String to pad with, null or empty treated as single space\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String rightPad(final String str, final int size, String padStr) {\n if (str == null) {\n return null;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int padLen = padStr.length();\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (padLen == 1 && pads <= StringUtils.PAD_LIMIT) {\n return StringUtils.rightPad(str, size, padStr.charAt(0));\n }\n if (pads == padLen) {\n return str.concat(padStr);\n } else if (pads < padLen) {\n return str.concat(padStr.substring(0, pads));\n } else {\n char[] padding = new char[pads];\n char[] padChars = padStr.toCharArray();\n for (int i = 0; i < pads; i++) {\n padding[i] = padChars[i % padLen];\n }\n return str.concat(new String(padding));\n }\n }\n\n /**\n *

      Left pad a String with spaces (' ').

      \n *\n *

      The String is padded to the size of size.

      \n *\n *
      \n     * StringUtils.leftPad(null, *)   = null\n     * StringUtils.leftPad(\"\", 3)     = \"   \"\n     * StringUtils.leftPad(\"bat\", 3)  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5)  = \"  bat\"\n     * StringUtils.leftPad(\"bat\", 1)  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1) = \"bat\"\n     * 
      \n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String leftPad(final String str, final int size) {\n return StringUtils.leftPad(str, size, ' ');\n }\n\n /**\n *

      Left pad a String with a specified character.

      \n *\n *

      Pad to a size of size.

      \n *\n *
      \n     * StringUtils.leftPad(null, *, *)     = null\n     * StringUtils.leftPad(\"\", 3, 'z')     = \"zzz\"\n     * StringUtils.leftPad(\"bat\", 3, 'z')  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, 'z')  = \"zzbat\"\n     * StringUtils.leftPad(\"bat\", 1, 'z')  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1, 'z') = \"bat\"\n     * 
      \n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padChar the character to pad with\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n * @since 2.0\n */\n public static String leftPad(final String str, final int size, final char padChar) {\n if (str == null) {\n return null;\n }\n int pads = size - str.length();\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (pads > StringUtils.PAD_LIMIT) {\n return StringUtils.leftPad(str, size, String.valueOf(padChar));\n }\n return StringUtils.padding(pads, padChar).concat(str);\n }\n\n /**\n *

      Left pad a String with a specified String.

      \n *\n *

      Pad to a size of size.

      \n *\n *
      \n     * StringUtils.leftPad(null, *, *)      = null\n     * StringUtils.leftPad(\"\", 3, \"z\")      = \"zzz\"\n     * StringUtils.leftPad(\"bat\", 3, \"yz\")  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, \"yz\")  = \"yzbat\"\n     * StringUtils.leftPad(\"bat\", 8, \"yz\")  = \"yzyzybat\"\n     * StringUtils.leftPad(\"bat\", 1, \"yz\")  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1, \"yz\") = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, null)  = \"  bat\"\n     * StringUtils.leftPad(\"bat\", 5, \"\")    = \"  bat\"\n     * 
      \n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padStr the String to pad with, null or empty treated as single space\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String leftPad(final String str, final int size, String padStr) {\n if (str == null) {\n return null;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int padLen = padStr.length();\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (padLen == 1 && pads <= StringUtils.PAD_LIMIT) {\n return StringUtils.leftPad(str, size, padStr.charAt(0));\n }\n if (pads == padLen) {\n return padStr.concat(str);\n } else if (pads < padLen) {\n return padStr.substring(0, pads).concat(str);\n } else {\n char[] padding = new char[pads];\n char[] padChars = padStr.toCharArray();\n for (int i = 0; i < pads; i++) {\n padding[i] = padChars[i % padLen];\n }\n return new String(padding).concat(str);\n }\n }\n\n /**\n * Gets a String's length or 0 if the String is null.\n *\n * @param str\n * a String or null\n * @return String length or 0 if the String is null.\n * @since 2.4\n */\n public static int length(final String str) {\n return str == null ? 0 : str.length();\n }\n // Centering\n //-----------------------------------------------------------------------\n\n /**\n *

      Centers a String in a larger String of size size\n * using the space character (' ').

      \n *\n *

      If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

      \n *\n *

      Equivalent to center(str, size, \" \").

      \n *\n *
      \n     * StringUtils.center(null, *)   = null\n     * StringUtils.center(\"\", 4)     = \"    \"\n     * StringUtils.center(\"ab\", -1)  = \"ab\"\n     * StringUtils.center(\"ab\", 4)   = \" ab \"\n     * StringUtils.center(\"abcd\", 2) = \"abcd\"\n     * StringUtils.center(\"a\", 4)    = \" a  \"\n     * 
      \n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @return centered String, null if null String input\n */\n public static String center(final String str, final int size) {\n return StringUtils.center(str, size, ' ');\n }\n\n /**\n *

      Centers a String in a larger String of size size.\n * Uses a supplied character as the value to pad the String with.

      \n *\n *

      If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

      \n *\n *
      \n     * StringUtils.center(null, *, *)     = null\n     * StringUtils.center(\"\", 4, ' ')     = \"    \"\n     * StringUtils.center(\"ab\", -1, ' ')  = \"ab\"\n     * StringUtils.center(\"ab\", 4, ' ')   = \" ab\"\n     * StringUtils.center(\"abcd\", 2, ' ') = \"abcd\"\n     * StringUtils.center(\"a\", 4, ' ')    = \" a  \"\n     * StringUtils.center(\"a\", 4, 'y')    = \"yayy\"\n     * 
      \n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @param padChar the character to pad the new String with\n * @return centered String, null if null String input\n * @since 2.0\n */\n public static String center(String str, final int size, final char padChar) {\n if (str == null || size <= 0) {\n return str;\n }\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str;\n }\n str = StringUtils.leftPad(str, strLen + pads / 2, padChar);\n str = StringUtils.rightPad(str, size, padChar);\n return str;\n }\n\n /**\n *

      Centers a String in a larger String of size size.\n * Uses a supplied String as the value to pad the String with.

      \n *\n *

      If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

      \n *\n *
      \n     * StringUtils.center(null, *, *)     = null\n     * StringUtils.center(\"\", 4, \" \")     = \"    \"\n     * StringUtils.center(\"ab\", -1, \" \")  = \"ab\"\n     * StringUtils.center(\"ab\", 4, \" \")   = \" ab\"\n     * StringUtils.center(\"abcd\", 2, \" \") = \"abcd\"\n     * StringUtils.center(\"a\", 4, \" \")    = \" a  \"\n     * StringUtils.center(\"a\", 4, \"yz\")   = \"yayz\"\n     * StringUtils.center(\"abc\", 7, null) = \"  abc  \"\n     * StringUtils.center(\"abc\", 7, \"\")   = \"  abc  \"\n     * 
      \n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @param padStr the String to pad the new String with, must not be null or empty\n * @return centered String, null if null String input\n * @throws IllegalArgumentException if padStr is null or empty\n */\n public static String center(String str, final int size, String padStr) {\n if (str == null || size <= 0) {\n return str;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str;\n }\n str = StringUtils.leftPad(str, strLen + pads / 2, padStr);\n str = StringUtils.rightPad(str, size, padStr);\n return str;\n }\n // Case conversion\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts a String to upper case as per {@link String#toUpperCase()}.

      \n *\n *

      A null input String returns null.

      \n *\n *
      \n     * StringUtils.upperCase(null)  = null\n     * StringUtils.upperCase(\"\")    = \"\"\n     * StringUtils.upperCase(\"aBc\") = \"ABC\"\n     * 
      \n *\n *

      Note: As described in the documentation for {@link String#toUpperCase()},\n * the result of this method is affected by the current locale.\n * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}\n * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

      \n *\n * @param str the String to upper case, may be null\n * @return the upper cased String, null if null String input\n */\n public static String upperCase(final String str) {\n if (str == null) {\n return null;\n }\n return str.toUpperCase();\n }\n\n /**\n *

      Converts a String to upper case as per {@link String#toUpperCase(Locale)}.

      \n *\n *

      A null input String returns null.

      \n *\n *
      \n     * StringUtils.upperCase(null, Locale.ENGLISH)  = null\n     * StringUtils.upperCase(\"\", Locale.ENGLISH)    = \"\"\n     * StringUtils.upperCase(\"aBc\", Locale.ENGLISH) = \"ABC\"\n     * 
      \n *\n * @param str the String to upper case, may be null\n * @param locale the locale that defines the case transformation rules, must not be null\n * @return the upper cased String, null if null String input\n * @since 2.5\n */\n public static String upperCase(final String str, final Locale locale) {\n if (str == null) {\n return null;\n }\n return str.toUpperCase(locale);\n }\n\n /**\n *

      Converts a String to lower case as per {@link String#toLowerCase()}.

      \n *\n *

      A null input String returns null.

      \n *\n *
      \n     * StringUtils.lowerCase(null)  = null\n     * StringUtils.lowerCase(\"\")    = \"\"\n     * StringUtils.lowerCase(\"aBc\") = \"abc\"\n     * 
      \n *\n *

      Note: As described in the documentation for {@link String#toLowerCase()},\n * the result of this method is affected by the current locale.\n * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}\n * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

      \n *\n * @param str the String to lower case, may be null\n * @return the lower cased String, null if null String input\n */\n public static String lowerCase(final String str) {\n if (str == null) {\n return null;\n }\n return str.toLowerCase();\n }\n\n /**\n *

      Converts a String to lower case as per {@link String#toLowerCase(Locale)}.

      \n *\n *

      A null input String returns null.

      \n *\n *
      \n     * StringUtils.lowerCase(null, Locale.ENGLISH)  = null\n     * StringUtils.lowerCase(\"\", Locale.ENGLISH)    = \"\"\n     * StringUtils.lowerCase(\"aBc\", Locale.ENGLISH) = \"abc\"\n     * 
      \n *\n * @param str the String to lower case, may be null\n * @param locale the locale that defines the case transformation rules, must not be null\n * @return the lower cased String, null if null String input\n * @since 2.5\n */\n public static String lowerCase(final String str, final Locale locale) {\n if (str == null) {\n return null;\n }\n return str.toLowerCase(locale);\n }\n\n /**\n *

      Capitalizes a String changing the first letter to title case as\n * per {@link Character#toTitleCase(char)}. No other letters are changed.

      \n *\n * A null input String returns null.

      \n *\n *
      \n     * StringUtils.capitalize(null)  = null\n     * StringUtils.capitalize(\"\")    = \"\"\n     * StringUtils.capitalize(\"cat\") = \"Cat\"\n     * StringUtils.capitalize(\"cAt\") = \"CAt\"\n     * 
      \n *\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null String input\n * @see #uncapitalize(String)\n * @since 2.0\n */\n public static String capitalize(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n return Character.toTitleCase(str.charAt(0)) + str.substring(1);\n }\n\n /**\n *

      Uncapitalizes a String changing the first letter to title case as\n * per {@link Character#toLowerCase(char)}. No other letters are changed.

      \n *\n * A null input String returns null.

      \n *\n *
      \n     * StringUtils.uncapitalize(null)  = null\n     * StringUtils.uncapitalize(\"\")    = \"\"\n     * StringUtils.uncapitalize(\"Cat\") = \"cat\"\n     * StringUtils.uncapitalize(\"CAT\") = \"cAT\"\n     * 
      \n *\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null String input\n * @see #capitalize(String)\n * @since 2.0\n */\n public static String uncapitalize(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n return Character.toLowerCase(str.charAt(0)) + str.substring(1);\n }\n\n /**\n *

      Swaps the case of a String changing upper and title case to\n * lower case, and lower case to upper case.

      \n *\n *
        \n *
      • Upper case character converts to Lower case
      • \n *
      • Title case character converts to Lower case
      • \n *
      • Lower case character converts to Upper case
      • \n *
      \n *\n * A null input String returns null.

      \n *\n *
      \n     * StringUtils.swapCase(null)                 = null\n     * StringUtils.swapCase(\"\")                   = \"\"\n     * StringUtils.swapCase(\"The dog has a BONE\") = \"tHE DOG HAS A bone\"\n     * 
      \n *\n *

      NOTE: This method changed in Lang version 2.0.\n * It no longer performs a word based algorithm.\n * If you only use ASCII, you will notice no change.\n * That functionality is available in WordUtils.

      \n *\n * @param str the String to swap case, may be null\n * @return the changed String, null if null String input\n */\n public static String swapCase(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n StringBuilder buffer = new StringBuilder(strLen);\n char ch = 0;\n for (int i = 0; i < strLen; i++) {\n ch = str.charAt(i);\n if (Character.isUpperCase(ch)) {\n ch = Character.toLowerCase(ch);\n } else if (Character.isTitleCase(ch)) {\n ch = Character.toLowerCase(ch);\n } else if (Character.isLowerCase(ch)) {\n ch = Character.toUpperCase(ch);\n }\n buffer.append(ch);\n }\n return buffer.toString();\n }\n // Count matches\n //-----------------------------------------------------------------------\n\n /**\n *

      Counts how many times the substring appears in the larger String.

      \n *\n *

      A null or empty (\"\") String input returns 0.

      \n *\n *
      \n     * StringUtils.countMatches(null, *)       = 0\n     * StringUtils.countMatches(\"\", *)         = 0\n     * StringUtils.countMatches(\"abba\", null)  = 0\n     * StringUtils.countMatches(\"abba\", \"\")    = 0\n     * StringUtils.countMatches(\"abba\", \"a\")   = 2\n     * StringUtils.countMatches(\"abba\", \"ab\")  = 1\n     * StringUtils.countMatches(\"abba\", \"xxx\") = 0\n     * 
      \n *\n * @param str the String to check, may be null\n * @param sub the substring to count, may be null\n * @return the number of occurrences, 0 if either String is null\n */\n public static int countMatches(final String str, final String sub) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(sub)) {\n return 0;\n }\n int count = 0;\n int idx = 0;\n while ((idx = str.indexOf(sub, idx)) != StringUtils.INDEX_NOT_FOUND) {\n count++;\n idx += sub.length();\n }\n return count;\n }\n // Character Tests\n //-----------------------------------------------------------------------\n\n /**\n *

      Checks if the String contains only unicode letters.

      \n *\n *

      null will return false.\n * An empty String (length()=0) will return true.

      \n *\n *
      \n     * StringUtils.isAlpha(null)   = false\n     * StringUtils.isAlpha(\"\")     = true\n     * StringUtils.isAlpha(\"  \")   = false\n     * StringUtils.isAlpha(\"abc\")  = true\n     * StringUtils.isAlpha(\"ab2c\") = false\n     * StringUtils.isAlpha(\"ab-c\") = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @return true if only contains letters, and is non-null\n */\n public static boolean isAlpha(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetter(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

      Checks if the String contains only unicode letters and\n * space (' ').

      \n *\n *

      null will return false\n * An empty String (length()=0) will return true.

      \n *\n *
      \n     * StringUtils.isAlphaSpace(null)   = false\n     * StringUtils.isAlphaSpace(\"\")     = true\n     * StringUtils.isAlphaSpace(\"  \")   = true\n     * StringUtils.isAlphaSpace(\"abc\")  = true\n     * StringUtils.isAlphaSpace(\"ab c\") = true\n     * StringUtils.isAlphaSpace(\"ab2c\") = false\n     * StringUtils.isAlphaSpace(\"ab-c\") = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @return true if only contains letters and space,\n * and is non-null\n */\n public static boolean isAlphaSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetter(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

      Checks if the String contains only unicode letters or digits.

      \n *\n *

      null will return false.\n * An empty String (length()=0) will return true.

      \n *\n *
      \n     * StringUtils.isAlphanumeric(null)   = false\n     * StringUtils.isAlphanumeric(\"\")     = true\n     * StringUtils.isAlphanumeric(\"  \")   = false\n     * StringUtils.isAlphanumeric(\"abc\")  = true\n     * StringUtils.isAlphanumeric(\"ab c\") = false\n     * StringUtils.isAlphanumeric(\"ab2c\") = true\n     * StringUtils.isAlphanumeric(\"ab-c\") = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @return true if only contains letters or digits,\n * and is non-null\n */\n public static boolean isAlphanumeric(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetterOrDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

      Checks if the String contains only unicode letters, digits\n * or space (' ').

      \n *\n *

      null will return false.\n * An empty String (length()=0) will return true.

      \n *\n *
      \n     * StringUtils.isAlphanumeric(null)   = false\n     * StringUtils.isAlphanumeric(\"\")     = true\n     * StringUtils.isAlphanumeric(\"  \")   = true\n     * StringUtils.isAlphanumeric(\"abc\")  = true\n     * StringUtils.isAlphanumeric(\"ab c\") = true\n     * StringUtils.isAlphanumeric(\"ab2c\") = true\n     * StringUtils.isAlphanumeric(\"ab-c\") = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @return true if only contains letters, digits or space,\n * and is non-null\n */\n public static boolean isAlphanumericSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetterOrDigit(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

      Checks if the string contains only ASCII printable characters.

      \n *\n *

      null will return false.\n * An empty String (length()=0) will return true.

      \n *\n *
      \n     * StringUtils.isAsciiPrintable(null)     = false\n     * StringUtils.isAsciiPrintable(\"\")       = true\n     * StringUtils.isAsciiPrintable(\" \")      = true\n     * StringUtils.isAsciiPrintable(\"Ceki\")   = true\n     * StringUtils.isAsciiPrintable(\"ab2c\")   = true\n     * StringUtils.isAsciiPrintable(\"!ab-c~\") = true\n     * StringUtils.isAsciiPrintable(\"\\u0020\") = true\n     * StringUtils.isAsciiPrintable(\"\\u0021\") = true\n     * StringUtils.isAsciiPrintable(\"\\u007e\") = true\n     * StringUtils.isAsciiPrintable(\"\\u007f\") = false\n     * StringUtils.isAsciiPrintable(\"Ceki G\\u00fclc\\u00fc\") = false\n     * 
      \n *\n * @param str the string to check, may be null\n * @return true if every character is in the range\n * 32 thru 126\n * @since 2.1\n */\n public static boolean isAsciiPrintable(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!CharUtils.isAsciiPrintable(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

      Checks if the String contains only unicode digits.\n * A decimal point is not a unicode digit and returns false.

      \n *\n *

      null will return false.\n * An empty String (length()=0) will return true.

      \n *\n *
      \n     * StringUtils.isNumeric(null)   = false\n     * StringUtils.isNumeric(\"\")     = true\n     * StringUtils.isNumeric(\"  \")   = false\n     * StringUtils.isNumeric(\"123\")  = true\n     * StringUtils.isNumeric(\"12 3\") = false\n     * StringUtils.isNumeric(\"ab2c\") = false\n     * StringUtils.isNumeric(\"12-3\") = false\n     * StringUtils.isNumeric(\"12.3\") = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @return true if only contains digits, and is non-null\n */\n public static boolean isNumeric(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

      Checks if the String contains only unicode digits or space\n * (' ').\n * A decimal point is not a unicode digit and returns false.

      \n *\n *

      null will return false.\n * An empty String (length()=0) will return true.

      \n *\n *
      \n     * StringUtils.isNumeric(null)   = false\n     * StringUtils.isNumeric(\"\")     = true\n     * StringUtils.isNumeric(\"  \")   = true\n     * StringUtils.isNumeric(\"123\")  = true\n     * StringUtils.isNumeric(\"12 3\") = true\n     * StringUtils.isNumeric(\"ab2c\") = false\n     * StringUtils.isNumeric(\"12-3\") = false\n     * StringUtils.isNumeric(\"12.3\") = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @return true if only contains digits or space,\n * and is non-null\n */\n public static boolean isNumericSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

      Checks if the String contains only whitespace.

      \n *\n *

      null will return false.\n * An empty String (length()=0) will return true.

      \n *\n *
      \n     * StringUtils.isWhitespace(null)   = false\n     * StringUtils.isWhitespace(\"\")     = true\n     * StringUtils.isWhitespace(\"  \")   = true\n     * StringUtils.isWhitespace(\"abc\")  = false\n     * StringUtils.isWhitespace(\"ab2c\") = false\n     * StringUtils.isWhitespace(\"ab-c\") = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @return true if only contains whitespace, and is non-null\n * @since 2.0\n */\n public static boolean isWhitespace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

      Checks if the String contains only lowercase characters.

      \n *\n *

      null will return false.\n * An empty String (length()=0) will return false.

      \n *\n *
      \n     * StringUtils.isAllLowerCase(null)   = false\n     * StringUtils.isAllLowerCase(\"\")     = false\n     * StringUtils.isAllLowerCase(\"  \")   = false\n     * StringUtils.isAllLowerCase(\"abc\")  = true\n     * StringUtils.isAllLowerCase(\"abC\") = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @return true if only contains lowercase characters, and is non-null\n * @since 2.5\n */\n public static boolean isAllLowerCase(final String str) {\n if (str == null || StringUtils.isEmpty(str)) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLowerCase(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

      Checks if the String contains only uppercase characters.

      \n *\n *

      null will return false.\n * An empty String (length()=0) will return false.

      \n *\n *
      \n     * StringUtils.isAllUpperCase(null)   = false\n     * StringUtils.isAllUpperCase(\"\")     = false\n     * StringUtils.isAllUpperCase(\"  \")   = false\n     * StringUtils.isAllUpperCase(\"ABC\")  = true\n     * StringUtils.isAllUpperCase(\"aBC\") = false\n     * 
      \n *\n * @param str the String to check, may be null\n * @return true if only contains uppercase characters, and is non-null\n * @since 2.5\n */\n public static boolean isAllUpperCase(final String str) {\n if (str == null || StringUtils.isEmpty(str)) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isUpperCase(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n // Defaults\n //-----------------------------------------------------------------------\n\n /**\n *

      Returns either the passed in String,\n * or if the String is null, an empty String (\"\").

      \n *\n *
      \n     * StringUtils.defaultString(null)  = \"\"\n     * StringUtils.defaultString(\"\")    = \"\"\n     * StringUtils.defaultString(\"bat\") = \"bat\"\n     * 
      \n *\n * @see ObjectUtils#toString(Object)\n * @see String#valueOf(Object)\n * @param str the String to check, may be null\n * @return the passed in String, or the empty String if it\n * was null\n */\n public static String defaultString(final String str) {\n return str == null ? StringUtils.EMPTY : str;\n }\n\n /**\n *

      Returns either the passed in String, or if the String is\n * null, the value of defaultStr.

      \n *\n *
      \n     * StringUtils.defaultString(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultString(\"\", \"NULL\")    = \"\"\n     * StringUtils.defaultString(\"bat\", \"NULL\") = \"bat\"\n     * 
      \n *\n * @see ObjectUtils#toString(Object, String)\n * @see String#valueOf(Object)\n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is null, may be null\n * @return the passed in String, or the default if it was null\n */\n public static String defaultString(final String str, final String defaultStr) {\n return str == null ? defaultStr : str;\n }\n\n /**\n *

      Returns either the passed in String, or if the String is\n * whitespace, empty (\"\") or null, the value of defaultStr.

      \n *\n *
      \n     * StringUtils.defaultIfBlank(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultIfBlank(\"\", \"NULL\")    = \"NULL\"\n     * StringUtils.defaultIfBlank(\" \", \"NULL\")   = \"NULL\"\n     * StringUtils.defaultIfBlank(\"bat\", \"NULL\") = \"bat\"\n     * StringUtils.defaultIfBlank(\"\", null)      = null\n     * 
      \n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is whitespace, empty (\"\") or null, may be null\n * @return the passed in String, or the default\n * @see StringUtils#defaultString(String, String)\n * @since 2.6\n */\n public static String defaultIfBlank(final String str, final String defaultStr) {\n return StringUtils.isBlank(str) ? defaultStr : str;\n }\n\n /**\n *

      Returns either the passed in String, or if the String is\n * empty or null, the value of defaultStr.

      \n *\n *
      \n     * StringUtils.defaultIfEmpty(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultIfEmpty(\"\", \"NULL\")    = \"NULL\"\n     * StringUtils.defaultIfEmpty(\"bat\", \"NULL\") = \"bat\"\n     * StringUtils.defaultIfEmpty(\"\", null)      = null\n     * 
      \n *\n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is empty (\"\") or null, may be null\n * @return the passed in String, or the default\n * @see StringUtils#defaultString(String, String)\n */\n public static String defaultIfEmpty(final String str, final String defaultStr) {\n return StringUtils.isEmpty(str) ? defaultStr : str;\n }\n // Reversing\n //-----------------------------------------------------------------------\n\n /**\n *

      Reverses a String as per {@link StringBuilder#reverse()}.

      \n *\n *

      A null String returns null.

      \n *\n *
      \n     * StringUtils.reverse(null)  = null\n     * StringUtils.reverse(\"\")    = \"\"\n     * StringUtils.reverse(\"bat\") = \"tab\"\n     * 
      \n *\n * @param str the String to reverse, may be null\n * @return the reversed String, null if null String input\n */\n public static String reverse(final String str) {\n if (str == null) {\n return null;\n }\n return new StringBuilder(str).reverse().toString();\n }\n\n /**\n *

      Reverses a String that is delimited by a specific character.

      \n *\n *

      The Strings between the delimiters are not reversed.\n * Thus java.lang.String becomes String.lang.java (if the delimiter\n * is '.').

      \n *\n *
      \n     * StringUtils.reverseDelimited(null, *)      = null\n     * StringUtils.reverseDelimited(\"\", *)        = \"\"\n     * StringUtils.reverseDelimited(\"a.b.c\", 'x') = \"a.b.c\"\n     * StringUtils.reverseDelimited(\"a.b.c\", \".\") = \"c.b.a\"\n     * 
      \n *\n * @param str the String to reverse, may be null\n * @param separatorChar the separator character to use\n * @return the reversed String, null if null String input\n * @since 2.0\n */\n public static String reverseDelimited(final String str, final char separatorChar) {\n if (str == null) {\n return null;\n }\n // could implement manually, but simple way is to reuse other,\n // probably slower, methods.\n String[] strs = StringUtils.split(str, separatorChar);\n ArrayUtils.reverse(strs);\n return StringUtils.join(strs, separatorChar);\n }\n // Abbreviating\n //-----------------------------------------------------------------------\n\n /**\n *

      Abbreviates a String using ellipses. This will turn\n * \"Now is the time for all good men\" into \"Now is the time for...\"

      \n *\n *

      Specifically:\n *

        \n *
      • If str is less than maxWidth characters\n * long, return it.
      • \n *
      • Else abbreviate it to (substring(str, 0, max-3) + \"...\").
      • \n *
      • If maxWidth is less than 4, throw an\n * IllegalArgumentException.
      • \n *
      • In no case will it return a String of length greater than\n * maxWidth.
      • \n *
      \n *

      \n *\n *
      \n     * StringUtils.abbreviate(null, *)      = null\n     * StringUtils.abbreviate(\"\", 4)        = \"\"\n     * StringUtils.abbreviate(\"abcdefg\", 6) = \"abc...\"\n     * StringUtils.abbreviate(\"abcdefg\", 7) = \"abcdefg\"\n     * StringUtils.abbreviate(\"abcdefg\", 8) = \"abcdefg\"\n     * StringUtils.abbreviate(\"abcdefg\", 4) = \"a...\"\n     * StringUtils.abbreviate(\"abcdefg\", 3) = IllegalArgumentException\n     * 
      \n *\n * @param str the String to check, may be null\n * @param maxWidth maximum length of result String, must be at least 4\n * @return abbreviated String, null if null String input\n * @throws IllegalArgumentException if the width is too small\n * @since 2.0\n */\n public static String abbreviate(final String str, final int maxWidth) {\n return StringUtils.abbreviate(str, 0, maxWidth);\n }\n\n /**\n *

      Abbreviates a String using ellipses. This will turn\n * \"Now is the time for all good men\" into \"...is the time for...\"

      \n *\n *

      Works like abbreviate(String, int), but allows you to specify\n * a \"left edge\" offset. Note that this left edge is not necessarily going to\n * be the leftmost character in the result, or the first character following the\n * ellipses, but it will appear somewhere in the result.\n *\n *

      In no case will it return a String of length greater than\n * maxWidth.

      \n *\n *
      \n     * StringUtils.abbreviate(null, *, *)                = null\n     * StringUtils.abbreviate(\"\", 0, 4)                  = \"\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", -1, 10) = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 0, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 1, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 4, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 5, 10)  = \"...fghi...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 6, 10)  = \"...ghij...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 8, 10)  = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 10, 10) = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 12, 10) = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghij\", 0, 3)        = IllegalArgumentException\n     * StringUtils.abbreviate(\"abcdefghij\", 5, 6)        = IllegalArgumentException\n     * 
      \n *\n * @param str the String to check, may be null\n * @param offset left edge of source String\n * @param maxWidth maximum length of result String, must be at least 4\n * @return abbreviated String, null if null String input\n * @throws IllegalArgumentException if the width is too small\n * @since 2.0\n */\n public static String abbreviate(final String str, int offset, final int maxWidth) {\n if (str == null) {\n return null;\n }\n if (maxWidth < 4) {\n throw new IllegalArgumentException(\"Minimum abbreviation width is 4\");\n }\n if (str.length() <= maxWidth) {\n return str;\n }\n if (offset > str.length()) {\n offset = str.length();\n }\n if (str.length() - offset < maxWidth - 3) {\n offset = str.length() - (maxWidth - 3);\n }\n if (offset <= 4) {\n return str.substring(0, maxWidth - 3) + \"...\";\n }\n if (maxWidth < 7) {\n throw new IllegalArgumentException(\"Minimum abbreviation width with offset is 7\");\n }\n if (offset + maxWidth - 3 < str.length()) {\n return \"...\" + StringUtils.abbreviate(str.substring(offset), maxWidth - 3);\n }\n return \"...\" + str.substring(str.length() - (maxWidth - 3));\n }\n\n /**\n *

      Abbreviates a String to the length passed, replacing the middle characters with the supplied\n * replacement String.

      \n *\n *

      This abbreviation only occurs if the following criteria is met:\n *

        \n *
      • Neither the String for abbreviation nor the replacement String are null or empty
      • \n *
      • The length to truncate to is less than the length of the supplied String
      • \n *
      • The length to truncate to is greater than 0
      • \n *
      • The abbreviated String will have enough room for the length supplied replacement String\n * and the first and last characters of the supplied String for abbreviation
      • \n *
      \n * Otherwise, the returned String will be the same as the supplied String for abbreviation.\n *

      \n *\n *
      \n     * StringUtils.abbreviateMiddle(null, null, 0)      = null\n     * StringUtils.abbreviateMiddle(\"abc\", null, 0)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abc\", \".\", 0)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abc\", \".\", 3)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abcdef\", \".\", 4)     = \"ab.f\"\n     * 
      \n *\n * @param str the String to abbreviate, may be null\n * @param middle the String to replace the middle characters with, may be null\n * @param length the length to abbreviate str to.\n * @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation.\n * @since 2.5\n */\n public static String abbreviateMiddle(final String str, final String middle, final int length) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(middle)) {\n return str;\n }\n if (length >= str.length() || length < middle.length() + 2) {\n return str;\n }\n int targetSting = length - middle.length();\n int startOffset = targetSting / 2 + targetSting % 2;\n int endOffset = str.length() - targetSting / 2;\n return str.substring(0, startOffset) + middle + str.substring(endOffset);\n }\n // Difference\n //-----------------------------------------------------------------------\n\n /**\n *

      Compares two Strings, and returns the portion where they differ.\n * (More precisely, return the remainder of the second String,\n * starting from where it's different from the first.)

      \n *\n *

      For example,\n * difference(\"i am a machine\", \"i am a robot\") -> \"robot\".

      \n *\n *
      \n     * StringUtils.difference(null, null) = null\n     * StringUtils.difference(\"\", \"\") = \"\"\n     * StringUtils.difference(\"\", \"abc\") = \"abc\"\n     * StringUtils.difference(\"abc\", \"\") = \"\"\n     * StringUtils.difference(\"abc\", \"abc\") = \"\"\n     * StringUtils.difference(\"ab\", \"abxyz\") = \"xyz\"\n     * StringUtils.difference(\"abcde\", \"abxyz\") = \"xyz\"\n     * StringUtils.difference(\"abcde\", \"xyz\") = \"xyz\"\n     * 
      \n *\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return the portion of str2 where it differs from str1; returns the\n * empty String if they are equal\n * @since 2.0\n */\n public static String difference(final String str1, final String str2) {\n if (str1 == null) {\n return str2;\n }\n if (str2 == null) {\n return str1;\n }\n int at = StringUtils.indexOfDifference(str1, str2);\n if (at == StringUtils.INDEX_NOT_FOUND) {\n return StringUtils.EMPTY;\n }\n return str2.substring(at);\n }\n\n /**\n *

      Compares two Strings, and returns the index at which the\n * Strings begin to differ.

      \n *\n *

      For example,\n * indexOfDifference(\"i am a machine\", \"i am a robot\") -> 7

      \n *\n *
      \n     * StringUtils.indexOfDifference(null, null) = -1\n     * StringUtils.indexOfDifference(\"\", \"\") = -1\n     * StringUtils.indexOfDifference(\"\", \"abc\") = 0\n     * StringUtils.indexOfDifference(\"abc\", \"\") = 0\n     * StringUtils.indexOfDifference(\"abc\", \"abc\") = -1\n     * StringUtils.indexOfDifference(\"ab\", \"abxyz\") = 2\n     * StringUtils.indexOfDifference(\"abcde\", \"abxyz\") = 2\n     * StringUtils.indexOfDifference(\"abcde\", \"xyz\") = 0\n     * 
      \n *\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return the index where str2 and str1 begin to differ; -1 if they are equal\n * @since 2.0\n */\n public static int indexOfDifference(final String str1, final String str2) {\n if (str1 != null && str1.equals(str2)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (str1 == null || str2 == null) {\n return 0;\n }\n int i;\n for (i = 0; i < str1.length() && i < str2.length(); ++i) {\n if (str1.charAt(i) != str2.charAt(i)) {\n break;\n }\n }\n if (i < str2.length() || i < str1.length()) {\n return i;\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

      Compares all Strings in an array and returns the index at which the\n * Strings begin to differ.

      \n *\n *

      For example,\n * indexOfDifference(new String[] {\"i am a machine\", \"i am a robot\"}) -> 7

      \n *\n *
      \n     * StringUtils.indexOfDifference(null) = -1\n     * StringUtils.indexOfDifference(new String[] {}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"abc\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {null, null}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"\", \"\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"\", null}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", null, null}) = 0\n     * StringUtils.indexOfDifference(new String[] {null, null, \"abc\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"\", \"abc\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"abc\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"a\"}) = 1\n     * StringUtils.indexOfDifference(new String[] {\"ab\", \"abxyz\"}) = 2\n     * StringUtils.indexOfDifference(new String[] {\"abcde\", \"abxyz\"}) = 2\n     * StringUtils.indexOfDifference(new String[] {\"abcde\", \"xyz\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"xyz\", \"abcde\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"i am a machine\", \"i am a robot\"}) = 7\n     * 
      \n *\n * @param strs array of strings, entries may be null\n * @return the index where the strings begin to differ; -1 if they are all equal\n * @since 2.4\n */\n public static int indexOfDifference(final String[] strs) {\n if (strs == null || strs.length <= 1) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n boolean anyStringNull = false;\n boolean allStringsNull = true;\n int arrayLen = strs.length;\n int shortestStrLen = Integer.MAX_VALUE;\n int longestStrLen = 0;\n // find the min and max string lengths; this avoids checking to make\n // sure we are not exceeding the length of the string each time through\n // the bottom loop.\n for (int i = 0; i < arrayLen; i++) {\n if (strs[i] == null) {\n anyStringNull = true;\n shortestStrLen = 0;\n } else {\n allStringsNull = false;\n shortestStrLen = Math.min(strs[i].length(), shortestStrLen);\n longestStrLen = Math.max(strs[i].length(), longestStrLen);\n }\n }\n // handle lists containing all nulls or all empty strings\n if (allStringsNull || longestStrLen == 0 && !anyStringNull) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n // handle lists containing some nulls or some empty strings\n if (shortestStrLen == 0) {\n return 0;\n }\n // find the position with the first difference across all strings\n int firstDiff = -1;\n for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {\n char comparisonChar = strs[0].charAt(stringPos);\n for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {\n if (strs[arrayPos].charAt(stringPos) != comparisonChar) {\n firstDiff = stringPos;\n break;\n }\n }\n if (firstDiff != -1) {\n break;\n }\n }\n if (firstDiff == -1 && shortestStrLen != longestStrLen) {\n // we compared all of the characters up to the length of the\n // shortest string and didn't find a match, but the string lengths\n // vary, so return the length of the shortest string.\n return shortestStrLen;\n }\n return firstDiff;\n }\n\n /**\n *

      Compares all Strings in an array and returns the initial sequence of\n * characters that is common to all of them.

      \n *\n *

      For example,\n * getCommonPrefix(new String[] {\"i am a machine\", \"i am a robot\"}) -> \"i am a \"

      \n *\n *
      \n     * StringUtils.getCommonPrefix(null) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\"}) = \"abc\"\n     * StringUtils.getCommonPrefix(new String[] {null, null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", \"\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", null, null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {null, null, \"abc\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", \"abc\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"abc\"}) = \"abc\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"a\"}) = \"a\"\n     * StringUtils.getCommonPrefix(new String[] {\"ab\", \"abxyz\"}) = \"ab\"\n     * StringUtils.getCommonPrefix(new String[] {\"abcde\", \"abxyz\"}) = \"ab\"\n     * StringUtils.getCommonPrefix(new String[] {\"abcde\", \"xyz\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"xyz\", \"abcde\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"i am a machine\", \"i am a robot\"}) = \"i am a \"\n     * 
      \n *\n * @param strs array of String objects, entries may be null\n * @return the initial sequence of characters that are common to all Strings\n * in the array; empty String if the array is null, the elements are all null\n * or if there is no common prefix.\n * @since 2.4\n */\n public static String getCommonPrefix(final String[] strs) {\n if (strs == null || strs.length == 0) {\n return StringUtils.EMPTY;\n }\n int smallestIndexOfDiff = StringUtils.indexOfDifference(strs);\n if (smallestIndexOfDiff == StringUtils.INDEX_NOT_FOUND) {\n // all strings were identical\n if (strs[0] == null) {\n return StringUtils.EMPTY;\n }\n return strs[0];\n } else if (smallestIndexOfDiff == 0) {\n // there were no common initial characters\n return StringUtils.EMPTY;\n } else {\n // we found a common initial character sequence\n return strs[0].substring(0, smallestIndexOfDiff);\n }\n }\n // Misc\n //-----------------------------------------------------------------------\n\n /**\n *

      Find the Levenshtein distance between two Strings.

      \n *\n *

      This is the number of changes needed to change one String into\n * another, where each change is a single character modification (deletion,\n * insertion or substitution).

      \n *\n *

      The previous implementation of the Levenshtein distance algorithm\n * was from http://www.merriampark.com/ld.htm

      \n *\n *

      Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError\n * which can occur when my Java implementation is used with very large strings.
      \n * This implementation of the Levenshtein distance algorithm\n * is from http://www.merriampark.com/ldjava.htm

      \n *\n *
      \n     * StringUtils.getLevenshteinDistance(null, *)             = IllegalArgumentException\n     * StringUtils.getLevenshteinDistance(*, null)             = IllegalArgumentException\n     * StringUtils.getLevenshteinDistance(\"\",\"\")               = 0\n     * StringUtils.getLevenshteinDistance(\"\",\"a\")              = 1\n     * StringUtils.getLevenshteinDistance(\"aaapppp\", \"\")       = 7\n     * StringUtils.getLevenshteinDistance(\"frog\", \"fog\")       = 1\n     * StringUtils.getLevenshteinDistance(\"fly\", \"ant\")        = 3\n     * StringUtils.getLevenshteinDistance(\"elephant\", \"hippo\") = 7\n     * StringUtils.getLevenshteinDistance(\"hippo\", \"elephant\") = 7\n     * StringUtils.getLevenshteinDistance(\"hippo\", \"zzzzzzzz\") = 8\n     * StringUtils.getLevenshteinDistance(\"hello\", \"hallo\")    = 1\n     * 
      \n *\n * @param s the first String, must not be null\n * @param t the second String, must not be null\n * @return result distance\n * @throws IllegalArgumentException if either String input null\n */\n public static int getLevenshteinDistance(String s, String t) {\n if (s == null || t == null) {\n throw new IllegalArgumentException(\"Strings must not be null\");\n }\n /*\n The difference between this impl. and the previous is that, rather\n than creating and retaining a matrix of size s.length()+1 by t.length()+1,\n we maintain two single-dimensional arrays of length s.length()+1. The first, d,\n is the 'current working' distance array that maintains the newest distance cost\n counts as we iterate through the characters of String s. Each time we increment\n the index of String t we are comparing, d is copied to p, the second int[]. Doing so\n allows us to retain the previous cost counts as required by the algorithm (taking\n the minimum of the cost count to the left, up one, and diagonally up and to the left\n of the current cost count being calculated). (Note that the arrays aren't really\n copied anymore, just switched...this is clearly much better than cloning an array\n or doing a System.arraycopy() each time through the outer loop.)\n\n Effectively, the difference between the two implementations is this one does not\n cause an out of memory condition when calculating the LD over two very large strings.\n */\n int n = s.length(); // length of s\n int m = t.length(); // length of t\n if (n == 0) {\n return m;\n } else if (m == 0) {\n return n;\n }\n if (n > m) {\n // swap the input strings to consume less memory\n String tmp = s;\n s = t;\n t = tmp;\n n = m;\n m = t.length();\n }\n int[] p = new int[n + 1]; //'previous' cost array, horizontally\n int[] d = new int[n + 1]; // cost array, horizontally\n int[] _d; //placeholder to assist in swapping p and d\n // indexes into strings s and t\n int i; // iterates through s\n int j; // iterates through t\n char t_j; // jth character of t\n int cost; // cost\n for (i = 0; i <= n; i++) {\n p[i] = i;\n }\n for (j = 1; j <= m; j++) {\n t_j = t.charAt(j - 1);\n d[0] = j;\n for (i = 1; i <= n; i++) {\n cost = s.charAt(i - 1) == t_j ? 0 : 1;\n // minimum of cell to the left+1, to the top+1, diagonally left and up +cost\n d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);\n }\n // copy current distance counts to 'previous row' distance counts\n _d = p;\n p = d;\n d = _d;\n }\n // our last action in the above loop was to switch d and p, so p now\n // actually has the most recent cost counts\n return p[n];\n }\n // startsWith\n //-----------------------------------------------------------------------\n\n /**\n *

      Check if a String starts with a specified prefix.

      \n *\n *

      nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

      \n *\n *
      \n     * StringUtils.startsWith(null, null)      = true\n     * StringUtils.startsWith(null, \"abc\")     = false\n     * StringUtils.startsWith(\"abcdef\", null)  = false\n     * StringUtils.startsWith(\"abcdef\", \"abc\") = true\n     * StringUtils.startsWith(\"ABCDEF\", \"abc\") = false\n     * 
      \n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @return true if the String starts with the prefix, case sensitive, or\n * both null\n * @since 2.4\n */\n public static boolean startsWith(final String str, final String prefix) {\n return StringUtils.startsWith(str, prefix, false);\n }\n\n /**\n *

      Case insensitive check if a String starts with a specified prefix.

      \n *\n *

      nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case insensitive.

      \n *\n *
      \n     * StringUtils.startsWithIgnoreCase(null, null)      = true\n     * StringUtils.startsWithIgnoreCase(null, \"abc\")     = false\n     * StringUtils.startsWithIgnoreCase(\"abcdef\", null)  = false\n     * StringUtils.startsWithIgnoreCase(\"abcdef\", \"abc\") = true\n     * StringUtils.startsWithIgnoreCase(\"ABCDEF\", \"abc\") = true\n     * 
      \n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @return true if the String starts with the prefix, case insensitive, or\n * both null\n * @since 2.4\n */\n public static boolean startsWithIgnoreCase(final String str, final String prefix) {\n return StringUtils.startsWith(str, prefix, true);\n }\n\n /**\n *

      Check if a String starts with a specified prefix (optionally case insensitive).

      \n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @param ignoreCase inidicates whether the compare should ignore case\n * (case insensitive) or not.\n * @return true if the String starts with the prefix or\n * both null\n */\n private static boolean startsWith(final String str, final String prefix, final boolean ignoreCase) {\n if (str == null || prefix == null) {\n return str == null && prefix == null;\n }\n if (prefix.length() > str.length()) {\n return false;\n }\n return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());\n }\n\n /**\n *

      Check if a String starts with any of an array of specified strings.

      \n *\n *
      \n     * StringUtils.startsWithAny(null, null)      = false\n     * StringUtils.startsWithAny(null, new String[] {\"abc\"})  = false\n     * StringUtils.startsWithAny(\"abcxyz\", null)     = false\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {\"\"}) = false\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {\"abc\"}) = true\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {null, \"xyz\", \"abc\"}) = true\n     * 
      \n *\n * @see #startsWith(String, String)\n * @param string the String to check, may be null\n * @param searchStrings the Strings to find, may be null or empty\n * @return true if the String starts with any of the the prefixes, case insensitive, or\n * both null\n * @since 2.5\n */\n public static boolean startsWithAny(final String string, final String[] searchStrings) {\n if (StringUtils.isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {\n return false;\n }\n for (String searchString : searchStrings) {\n if (StringUtils.startsWith(string, searchString)) {\n return true;\n }\n }\n return false;\n }\n // endsWith\n //-----------------------------------------------------------------------\n\n /**\n *

      Check if a String ends with a specified suffix.

      \n *\n *

      nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

      \n *\n *
      \n     * StringUtils.endsWith(null, null)      = true\n     * StringUtils.endsWith(null, \"def\")     = false\n     * StringUtils.endsWith(\"abcdef\", null)  = false\n     * StringUtils.endsWith(\"abcdef\", \"def\") = true\n     * StringUtils.endsWith(\"ABCDEF\", \"def\") = false\n     * StringUtils.endsWith(\"ABCDEF\", \"cde\") = false\n     * 
      \n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @return true if the String ends with the suffix, case sensitive, or\n * both null\n * @since 2.4\n */\n public static boolean endsWith(final String str, final String suffix) {\n return StringUtils.endsWith(str, suffix, false);\n }\n\n /**\n *

      Case insensitive check if a String ends with a specified suffix.

      \n *\n *

      nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case insensitive.

      \n *\n *
      \n     * StringUtils.endsWithIgnoreCase(null, null)      = true\n     * StringUtils.endsWithIgnoreCase(null, \"def\")     = false\n     * StringUtils.endsWithIgnoreCase(\"abcdef\", null)  = false\n     * StringUtils.endsWithIgnoreCase(\"abcdef\", \"def\") = true\n     * StringUtils.endsWithIgnoreCase(\"ABCDEF\", \"def\") = true\n     * StringUtils.endsWithIgnoreCase(\"ABCDEF\", \"cde\") = false\n     * 
      \n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @return true if the String ends with the suffix, case insensitive, or\n * both null\n * @since 2.4\n */\n public static boolean endsWithIgnoreCase(final String str, final String suffix) {\n return StringUtils.endsWith(str, suffix, true);\n }\n\n /**\n *

      Check if a String ends with a specified suffix (optionally case insensitive).

      \n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @param ignoreCase inidicates whether the compare should ignore case\n * (case insensitive) or not.\n * @return true if the String starts with the prefix or\n * both null\n */\n private static boolean endsWith(final String str, final String suffix, final boolean ignoreCase) {\n if (str == null || suffix == null) {\n return str == null && suffix == null;\n }\n if (suffix.length() > str.length()) {\n return false;\n }\n int strOffset = str.length() - suffix.length();\n return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());\n }\n\n /**\n *

      \n * Similar to http://www.w3.org/TR/xpath/#function-normalize\n * -space\n *

      \n *

      \n * The function returns the argument string with whitespace normalized by using\n * {@link #trim(String)} to remove leading and trailing whitespace\n * and then replacing sequences of whitespace characters by a single space.\n *

      \n * In XML Whitespace characters are the same as those allowed by the S production, which is S ::= (#x20 | #x9 | #xD | #xA)+\n *

      \n * See Java's {@link Character#isWhitespace(char)} for which characters are considered whitespace.\n *

      \n * The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also\n * normalize. Additonally {@link #trim(String)} removes control characters (char <= 32) from both\n * ends of this String.\n *

      \n *\n * @see Character#isWhitespace(char)\n * @see #trim(String)\n * @see \n * http://www.w3.org/TR/xpath/#function-normalize-space\n * @param str the source String to normalize whitespaces from, may be null\n * @return the modified string with whitespace normalized, null if null String input\n *\n * @since 2.6\n */\n public static String normalizeSpace(String str) {\n str = StringUtils.strip(str);\n if (str == null || str.length() <= 2) {\n return str;\n }\n StringBuilder b = new StringBuilder(str.length());\n for (int i = 0; i < str.length(); i++) {\n char c = str.charAt(i);\n if (Character.isWhitespace(c)) {\n if (i > 0 && !Character.isWhitespace(str.charAt(i - 1))) {\n b.append(' ');\n }\n } else {\n b.append(c);\n }\n }\n return b.toString();\n }\n\n /**\n *

      Check if a String ends with any of an array of specified strings.

      \n *\n *
      \n     * StringUtils.endsWithAny(null, null)      = false\n     * StringUtils.endsWithAny(null, new String[] {\"abc\"})  = false\n     * StringUtils.endsWithAny(\"abcxyz\", null)     = false\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {\"\"}) = true\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {\"xyz\"}) = true\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {null, \"xyz\", \"abc\"}) = true\n     * 
      \n *\n * @param string the String to check, may be null\n * @param searchStrings the Strings to find, may be null or empty\n * @return true if the String ends with any of the the prefixes, case insensitive, or\n * both null\n * @since 2.6\n */\n public static boolean endsWithAny(final String string, final String[] searchStrings) {\n if (StringUtils.isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {\n return false;\n }\n for (String searchString : searchStrings) {\n if (StringUtils.endsWith(string, searchString)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 转换首字母大写。\n *
      \n     * StringUtils.firstCharToUpperCase(null)      = null\n     * StringUtils.firstCharToUpperCase(\"\")        = \"\"\n     * StringUtils.firstCharToUpperCase(\"abc\")     = \"Abc\"\n     * StringUtils.firstCharToUpperCase(\"Abc\")     = \"Abc\"\n     * StringUtils.firstCharToUpperCase(\"ABC\")     = \"ABC\"\n     * 
      \n */\n public static String firstCharToUpperCase(final String value) {\n if (StringUtils.isBlank(value)) {\n return value;\n }\n StringBuilder sb = new StringBuilder(value);\n char firstChar = sb.charAt(0);\n sb.delete(0, 1);\n sb.insert(0, (char) (firstChar >= 97 ? firstChar - 32 : firstChar));\n return sb.toString();\n }\n\n /**\n * 转换首字母小写。\n *
      \n     * StringUtils.firstCharToLowerCase(null)      = null\n     * StringUtils.firstCharToLowerCase(\"\")        = \"\"\n     * StringUtils.firstCharToLowerCase(\"abc\")     = \"abc\"\n     * StringUtils.firstCharToLowerCase(\"Abc\")     = \"abc\"\n     * StringUtils.firstCharToLowerCase(\"ABC\")     = \"aBC\"\n     * 
      \n */\n public static String firstCharToLowerCase(final String value) {\n if (StringUtils.isBlank(value)) {\n return value;\n }\n StringBuilder sb = new StringBuilder(value);\n char firstChar = sb.charAt(0);\n sb.delete(0, 1);\n sb.insert(0, (char) (firstChar <= 90 ? firstChar + 32 : firstChar));\n return sb.toString();\n }\n\n /**\n * 执行字符串匹配。\n *
      \n     * StringUtils.equalsBlankIgnoreCase(null,\"\")         = true\n     * StringUtils.equalsBlankIgnoreCase(\"\",\"\")           = true\n     * StringUtils.equalsBlankIgnoreCase(\" \",\"\")          = true\n     * StringUtils.equalsBlankIgnoreCase(\" \",null)        = true\n     * StringUtils.equalsBlankIgnoreCase(\"bob\",\"\")        = false\n     * StringUtils.equalsBlankIgnoreCase(\"  bob  \",\"bob\") = true\n     * 
      \n */\n public static boolean equalsBlankIgnoreCase(final String str1, final String str2) {\n return StringUtils.equalsIgnoreCase(StringUtils.trimToEmpty(str1), StringUtils.trimToEmpty(str2));\n }\n\n /* ------------------------------------------------------------ */\n private static final char[] escapes = new char[32];\n\n static {\n Arrays.fill(escapes, (char) 0xFFFF);\n escapes['\\b'] = 'b';\n escapes['\\t'] = 't';\n escapes['\\n'] = 'n';\n escapes['\\f'] = 'f';\n escapes['\\r'] = 'r';\n }\n\n /** Quote a string into an Appendable.\n * The characters \", \\, \\n, \\r, \\t, \\f and \\b are escaped\n * @param input The String to quote.\n */\n public static String quote(String input) {\n StringBuilder buffer = new StringBuilder();\n quote(buffer, input);\n return buffer.toString();\n }\n\n public static void quote(Appendable buffer, String input) {\n try {\n buffer.append('\"');\n for (int i = 0; i < input.length(); ++i) {\n char c = input.charAt(i);\n if (c >= 32) {\n if (c == '\"' || c == '\\\\')\n buffer.append('\\\\');\n buffer.append(c);\n } else {\n char escape = escapes[c];\n if (escape == 0xFFFF) {\n // Unicode escape\n buffer.append('\\\\').append('u').append('0').append('0');\n if (c < 0x10)\n buffer.append('0');\n buffer.append(Integer.toString(c, 16));\n } else {\n buffer.append('\\\\').append(escape);\n }\n }\n }\n buffer.append('\"');\n } catch (IOException x) {\n throw new RuntimeException(x);\n }\n }\n\n /** Object to String ,when null object then null else return toString(); */\n public static String toString(Object object) {\n return (object == null) ? null : object.toString();\n }\n}", "file_name": "StringUtils.java", "human_label": "Return true if the given string has the specified prefix with optional cases which can be ignored,or both string and prefix are null.Otherwise return false. ", "level": "self_contained", "lineno": "5819", "name": "startsWith", "oracle_context": "{ \"apis\" : \"[length, regionMatches]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636766fe1a6d9265ec01781c", "all_context": "{ \"class_level\" : \"String CHAR_STRING;\\nString[] CHAR_STRING_ARRAY;\\nCharacter[] CHAR_ARRAY;\\nchar LF;\\nchar CR;\\nCharUtils();\\ntoCharacterObject(String str);\\ntoChar(Character ch);\\ntoChar(Character ch,char defaultValue);\\ntoChar(String str);\\ntoChar(String str,char defaultValue);\\ntoIntValue(char ch);\\ntoIntValue(char ch,int defaultValue);\\ntoIntValue(Character ch);\\ntoIntValue(Character ch,int defaultValue);\\ntoString(char ch);\\ntoString(Character ch);\\nunicodeEscaped(char ch);\\nunicodeEscaped(Character ch);\\nisAscii(char ch);\\nisAsciiPrintable(char ch);\\nisAsciiControl(char ch);\\nisAsciiAlpha(char ch);\\nisAsciiAlphaUpper(char ch);\\nisAsciiAlphaLower(char ch);\\nisAsciiNumeric(char ch);\\nisAsciiAlphanumeric(char ch);\\nisHighSurrogate(char ch);\\nisCharType(Class targetType);\\n\", \"repo_level\" : \"\" }", "class_name": "CharUtils", "code": "public static Character toCharacterObject(final char ch){\n if (ch < CharUtils.CHAR_ARRAY.length) {\n return CharUtils.CHAR_ARRAY[ch];\n }\n return new Character(ch);\n}\n", "docstring": "/** \n *

      Converts the character to a Character.

      For ASCII 7 bit characters, this uses a cache that will return the same Character object each time.

       CharUtils.toCharacterObject(' ')  = ' ' CharUtils.toCharacterObject('A')  = 'A' 
      \n * @param ch the character to convert\n * @return a Character of the specified character\n */\n", "end_lineno": "106", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\n/**\n *

      Operations on char primitives and Character objects.

      \n *\n *

      This class tries to handle null input gracefully.\n * An exception will not be thrown for a null input.\n * Each method documents its behaviour in more detail.

      \n *\n *

      #ThreadSafe#

      \n * @author Apache Software Foundation\n * @since 2.1\n * @version $Id: CharUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class CharUtils {\n private static final String CHAR_STRING = //\n \"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\" +//\n \"\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\" + //\n \"\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\" + //\n \"\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\" +//\n \"\\u0020\\u0021\\\"\\u0023\\u0024\\u0025\\u0026\\u0027\" + //\n \"\\u0028\\u0029\\u002a\\u002b\\u002c\\u002d\\u002e\\u002f\" + //\n \"\\u0030\\u0031\\u0032\\u0033\\u0034\\u0035\\u0036\\u0037\" + //\n \"\\u0038\\u0039\\u003a\\u003b\\u003c\\u003d\\u003e\\u003f\" + //\n \"\\u0040\\u0041\\u0042\\u0043\\u0044\\u0045\\u0046\\u0047\" + //\n \"\\u0048\\u0049\\u004a\\u004b\\u004c\\u004d\\u004e\\u004f\" + //\n \"\\u0050\\u0051\\u0052\\u0053\\u0054\\u0055\\u0056\\u0057\" +//\n \"\\u0058\\u0059\\u005a\\u005b\\\\\\u005d\\u005e\\u005f\" + //\n \"\\u0060\\u0061\\u0062\\u0063\\u0064\\u0065\\u0066\\u0067\" +//\n \"\\u0068\\u0069\\u006a\\u006b\\u006c\\u006d\\u006e\\u006f\" +//\n \"\\u0070\\u0071\\u0072\\u0073\\u0074\\u0075\\u0076\\u0077\" +//\n \"\\u0078\\u0079\\u007a\\u007b\\u007c\\u007d\\u007e\\u007f\";\n private static final String[] CHAR_STRING_ARRAY = new String[128];\n private static final Character[] CHAR_ARRAY = new Character[128];\n /**\n * \n linefeed LF ('\\n').\n *\n * @see JLF: Escape Sequences\n * for Character and String Literals\n * @since 2.2\n */\n public static final char LF = '\\n';\n /**\n * carriage return CR ('\\r').\n *\n * @see JLF: Escape Sequences\n * for Character and String Literals\n * @since 2.2\n */\n public static final char CR = '\\r';\n\n static {\n for (int i = 127; i >= 0; i--) {\n CharUtils.CHAR_STRING_ARRAY[i] = CharUtils.CHAR_STRING.substring(i, i + 1);\n CharUtils.CHAR_ARRAY[i] = new Character((char) i);\n }\n }\n\n /**\n *

      CharUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as CharUtils.toString('c');.

      \n *\n *

      This constructor i public to permit tools that require a JavaBean instance\n * to operate.

      \n */\n public CharUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the character to a Character.

      \n *\n *

      For ASCII 7 bit characters, this uses a cache that will return the\n * same Character object each time.

      \n *\n *
      \n     *   CharUtils.toCharacterObject(' ')  = ' '\n     *   CharUtils.toCharacterObject('A')  = 'A'\n     * 
      \n *\n * @param ch the character to convert\n * @return a Character of the specified character\n */\n public static Character toCharacterObject(final char ch) {\n if (ch < CharUtils.CHAR_ARRAY.length) {\n return CharUtils.CHAR_ARRAY[ch];\n }\n return new Character(ch);\n }\n\n /**\n *

      Converts the String to a Character using the first character, returning\n * null for empty Strings.

      \n *\n *

      For ASCII 7 bit characters, this uses a cache that will return the\n * same Character object each time.

      \n *\n *
      \n     *   CharUtils.toCharacterObject(null) = null\n     *   CharUtils.toCharacterObject(\"\")   = null\n     *   CharUtils.toCharacterObject(\"A\")  = 'A'\n     *   CharUtils.toCharacterObject(\"BA\") = 'B'\n     * 
      \n *\n * @param str the character to convert\n * @return the Character value of the first letter of the String\n */\n public static Character toCharacterObject(final String str) {\n if (StringUtils.isEmpty(str)) {\n return null;\n }\n return CharUtils.toCharacterObject(str.charAt(0));\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the Character to a char throwing an exception for null.

      \n *\n *
      \n     *   CharUtils.toChar(null) = IllegalArgumentException\n     *   CharUtils.toChar(' ')  = ' '\n     *   CharUtils.toChar('A')  = 'A'\n     * 
      \n *\n * @param ch the character to convert\n * @return the char value of the Character\n * @throws IllegalArgumentException if the Character is null\n */\n public static char toChar(final Character ch) {\n if (ch == null) {\n throw new IllegalArgumentException(\"The Character must not be null\");\n }\n return ch.charValue();\n }\n\n /**\n *

      Converts the Character to a char handling null.

      \n *\n *
      \n     *   CharUtils.toChar(null, 'X') = 'X'\n     *   CharUtils.toChar(' ', 'X')  = ' '\n     *   CharUtils.toChar('A', 'X')  = 'A'\n     * 
      \n *\n * @param ch the character to convert\n * @param defaultValue the value to use if the Character is null\n * @return the char value of the Character or the default if null\n */\n public static char toChar(final Character ch, final char defaultValue) {\n if (ch == null) {\n return defaultValue;\n }\n return ch.charValue();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the String to a char using the first character, throwing\n * an exception on empty Strings.

      \n *\n *
      \n     *   CharUtils.toChar(null) = IllegalArgumentException\n     *   CharUtils.toChar(\"\")   = IllegalArgumentException\n     *   CharUtils.toChar(\"A\")  = 'A'\n     *   CharUtils.toChar(\"BA\") = 'B'\n     * 
      \n *\n * @param str the character to convert\n * @return the char value of the first letter of the String\n * @throws IllegalArgumentException if the String is empty\n */\n public static char toChar(final String str) {\n if (StringUtils.isEmpty(str)) {\n throw new IllegalArgumentException(\"The String must not be empty\");\n }\n return str.charAt(0);\n }\n\n /**\n *

      Converts the String to a char using the first character, defaulting\n * the value on empty Strings.

      \n *\n *
      \n     *   CharUtils.toChar(null, 'X') = 'X'\n     *   CharUtils.toChar(\"\", 'X')   = 'X'\n     *   CharUtils.toChar(\"A\", 'X')  = 'A'\n     *   CharUtils.toChar(\"BA\", 'X') = 'B'\n     * 
      \n *\n * @param str the character to convert\n * @param defaultValue the value to use if the Character is null\n * @return the char value of the first letter of the String or the default if null\n */\n public static char toChar(final String str, final char defaultValue) {\n if (StringUtils.isEmpty(str)) {\n return defaultValue;\n }\n return str.charAt(0);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

      \n *\n *

      This method coverts the char '1' to the int 1 and so on.

      \n *\n *
      \n     *   CharUtils.toIntValue('3')  = 3\n     *   CharUtils.toIntValue('A')  = IllegalArgumentException\n     * 
      \n *\n * @param ch the character to convert\n * @return the int value of the character\n * @throws IllegalArgumentException if the character is not ASCII numeric\n */\n public static int toIntValue(final char ch) {\n if (CharUtils.isAsciiNumeric(ch) == false) {\n throw new IllegalArgumentException(\"The character \" + ch + \" is not in the range '0' - '9'\");\n }\n return ch - 48;\n }\n\n /**\n *

      Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

      \n *\n *

      This method coverts the char '1' to the int 1 and so on.

      \n *\n *
      \n     *   CharUtils.toIntValue('3', -1)  = 3\n     *   CharUtils.toIntValue('A', -1)  = -1\n     * 
      \n *\n * @param ch the character to convert\n * @param defaultValue the default value to use if the character is not numeric\n * @return the int value of the character\n */\n public static int toIntValue(final char ch, final int defaultValue) {\n if (CharUtils.isAsciiNumeric(ch) == false) {\n return defaultValue;\n }\n return ch - 48;\n }\n\n /**\n *

      Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

      \n *\n *

      This method coverts the char '1' to the int 1 and so on.

      \n *\n *
      \n     *   CharUtils.toIntValue(null) = IllegalArgumentException\n     *   CharUtils.toIntValue('3')  = 3\n     *   CharUtils.toIntValue('A')  = IllegalArgumentException\n     * 
      \n *\n * @param ch the character to convert, not null\n * @return the int value of the character\n * @throws IllegalArgumentException if the Character is not ASCII numeric or is null\n */\n public static int toIntValue(final Character ch) {\n if (ch == null) {\n throw new IllegalArgumentException(\"The character must not be null\");\n }\n return CharUtils.toIntValue(ch.charValue());\n }\n\n /**\n *

      Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

      \n *\n *

      This method coverts the char '1' to the int 1 and so on.

      \n *\n *
      \n     *   CharUtils.toIntValue(null, -1) = -1\n     *   CharUtils.toIntValue('3', -1)  = 3\n     *   CharUtils.toIntValue('A', -1)  = -1\n     * 
      \n *\n * @param ch the character to convert\n * @param defaultValue the default value to use if the character is not numeric\n * @return the int value of the character\n */\n public static int toIntValue(final Character ch, final int defaultValue) {\n if (ch == null) {\n return defaultValue;\n }\n return CharUtils.toIntValue(ch.charValue(), defaultValue);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the character to a String that contains the one character.

      \n *\n *

      For ASCII 7 bit characters, this uses a cache that will return the\n * same String object each time.

      \n *\n *
      \n     *   CharUtils.toString(' ')  = \" \"\n     *   CharUtils.toString('A')  = \"A\"\n     * 
      \n *\n * @param ch the character to convert\n * @return a String containing the one specified character\n */\n public static String toString(final char ch) {\n if (ch < 128) {\n return CharUtils.CHAR_STRING_ARRAY[ch];\n }\n return new String(new char[] { ch });\n }\n\n /**\n *

      Converts the character to a String that contains the one character.

      \n *\n *

      For ASCII 7 bit characters, this uses a cache that will return the\n * same String object each time.

      \n *\n *

      If null is passed in, null will be returned.

      \n *\n *
      \n     *   CharUtils.toString(null) = null\n     *   CharUtils.toString(' ')  = \" \"\n     *   CharUtils.toString('A')  = \"A\"\n     * 
      \n *\n * @param ch the character to convert\n * @return a String containing the one specified character\n */\n public static String toString(final Character ch) {\n if (ch == null) {\n return null;\n }\n return CharUtils.toString(ch.charValue());\n }\n //--------------------------------------------------------------------------\n\n /**\n *

      Converts the string to the unicode format '\\u0020'.

      \n *\n *

      This format is the Java source code format.

      \n *\n *
      \n     *   CharUtils.unicodeEscaped(' ') = \"\\u0020\"\n     *   CharUtils.unicodeEscaped('A') = \"\\u0041\"\n     * 
      \n *\n * @param ch the character to convert\n * @return the escaped unicode string\n */\n public static String unicodeEscaped(final char ch) {\n if (ch < 0x10) {\n return \"\\\\u000\" + Integer.toHexString(ch);\n } else if (ch < 0x100) {\n return \"\\\\u00\" + Integer.toHexString(ch);\n } else if (ch < 0x1000) {\n return \"\\\\u0\" + Integer.toHexString(ch);\n }\n return \"\\\\u\" + Integer.toHexString(ch);\n }\n\n /**\n *

      Converts the string to the unicode format '\\u0020'.

      \n *\n *

      This format is the Java source code format.

      \n *\n *

      If null is passed in, null will be returned.

      \n *\n *
      \n     *   CharUtils.unicodeEscaped(null) = null\n     *   CharUtils.unicodeEscaped(' ')  = \"\\u0020\"\n     *   CharUtils.unicodeEscaped('A')  = \"\\u0041\"\n     * 
      \n *\n * @param ch the character to convert, may be null\n * @return the escaped unicode string, null if null input\n */\n public static String unicodeEscaped(final Character ch) {\n if (ch == null) {\n return null;\n }\n return CharUtils.unicodeEscaped(ch.charValue());\n }\n //--------------------------------------------------------------------------\n\n /**\n *

      Checks whether the character is ASCII 7 bit.

      \n *\n *
      \n     *   CharUtils.isAscii('a')  = true\n     *   CharUtils.isAscii('A')  = true\n     *   CharUtils.isAscii('3')  = true\n     *   CharUtils.isAscii('-')  = true\n     *   CharUtils.isAscii('\\n') = true\n     *   CharUtils.isAscii('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if less than 128\n */\n public static boolean isAscii(final char ch) {\n return ch < 128;\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit printable.

      \n *\n *
      \n     *   CharUtils.isAsciiPrintable('a')  = true\n     *   CharUtils.isAsciiPrintable('A')  = true\n     *   CharUtils.isAsciiPrintable('3')  = true\n     *   CharUtils.isAsciiPrintable('-')  = true\n     *   CharUtils.isAsciiPrintable('\\n') = false\n     *   CharUtils.isAsciiPrintable('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 32 and 126 inclusive\n */\n public static boolean isAsciiPrintable(final char ch) {\n return ch >= 32 && ch < 127;\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit control.

      \n *\n *
      \n     *   CharUtils.isAsciiControl('a')  = false\n     *   CharUtils.isAsciiControl('A')  = false\n     *   CharUtils.isAsciiControl('3')  = false\n     *   CharUtils.isAsciiControl('-')  = false\n     *   CharUtils.isAsciiControl('\\n') = true\n     *   CharUtils.isAsciiControl('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if less than 32 or equals 127\n */\n public static boolean isAsciiControl(final char ch) {\n return ch < 32 || ch == 127;\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit alphabetic.

      \n *\n *
      \n     *   CharUtils.isAsciiAlpha('a')  = true\n     *   CharUtils.isAsciiAlpha('A')  = true\n     *   CharUtils.isAsciiAlpha('3')  = false\n     *   CharUtils.isAsciiAlpha('-')  = false\n     *   CharUtils.isAsciiAlpha('\\n') = false\n     *   CharUtils.isAsciiAlpha('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 65 and 90 or 97 and 122 inclusive\n */\n public static boolean isAsciiAlpha(final char ch) {\n return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z';\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit alphabetic upper case.

      \n *\n *
      \n     *   CharUtils.isAsciiAlphaUpper('a')  = false\n     *   CharUtils.isAsciiAlphaUpper('A')  = true\n     *   CharUtils.isAsciiAlphaUpper('3')  = false\n     *   CharUtils.isAsciiAlphaUpper('-')  = false\n     *   CharUtils.isAsciiAlphaUpper('\\n') = false\n     *   CharUtils.isAsciiAlphaUpper('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 65 and 90 inclusive\n */\n public static boolean isAsciiAlphaUpper(final char ch) {\n return ch >= 'A' && ch <= 'Z';\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit alphabetic lower case.

      \n *\n *
      \n     *   CharUtils.isAsciiAlphaLower('a')  = true\n     *   CharUtils.isAsciiAlphaLower('A')  = false\n     *   CharUtils.isAsciiAlphaLower('3')  = false\n     *   CharUtils.isAsciiAlphaLower('-')  = false\n     *   CharUtils.isAsciiAlphaLower('\\n') = false\n     *   CharUtils.isAsciiAlphaLower('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 97 and 122 inclusive\n */\n public static boolean isAsciiAlphaLower(final char ch) {\n return ch >= 'a' && ch <= 'z';\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit numeric.

      \n *\n *
      \n     *   CharUtils.isAsciiNumeric('a')  = false\n     *   CharUtils.isAsciiNumeric('A')  = false\n     *   CharUtils.isAsciiNumeric('3')  = true\n     *   CharUtils.isAsciiNumeric('-')  = false\n     *   CharUtils.isAsciiNumeric('\\n') = false\n     *   CharUtils.isAsciiNumeric('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 48 and 57 inclusive\n */\n public static boolean isAsciiNumeric(final char ch) {\n return ch >= '0' && ch <= '9';\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit numeric.

      \n *\n *
      \n     *   CharUtils.isAsciiAlphanumeric('a')  = true\n     *   CharUtils.isAsciiAlphanumeric('A')  = true\n     *   CharUtils.isAsciiAlphanumeric('3')  = true\n     *   CharUtils.isAsciiAlphanumeric('-')  = false\n     *   CharUtils.isAsciiAlphanumeric('\\n') = false\n     *   CharUtils.isAsciiAlphanumeric('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive\n */\n public static boolean isAsciiAlphanumeric(final char ch) {\n return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9';\n }\n // ----------------- Following code copied from Apache Harmony (Character class)\n\n /**\n * Indicates whether {@code ch} is a high- (or leading-) surrogate code unit\n * that is used for representing supplementary characters in UTF-16\n * encoding.\n *\n * @param ch\n * the character to test.\n * @return {@code true} if {@code ch} is a high-surrogate code unit;\n * {@code false} otherwise.\n */\n static boolean isHighSurrogate(final char ch) {\n return '\\uD800' <= ch && '\\uDBFF' >= ch;\n }\n\n //\n public static boolean isCharType(Class targetType) {\n return targetType.equals(Character.class) || targetType.equals(Character.TYPE);\n }\n}\n", "file_name": "CharUtils.java", "human_label": "Return the Character object converted from the given character.", "level": "class_runnable", "lineno": "87", "name": "toCharacterObject", "oracle_context": "{ \"apis\" : \"[CharUtils]\", \"classes\" : \"[CharUtils.CHAR_ARRAY, CharUtils]\", \"vars\" : \"[length, CHAR_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636766fb1a6d9265ec0177c1", "all_context": "{ \"class_level\" : \"String CHAR_STRING;\\nString[] CHAR_STRING_ARRAY;\\nCharacter[] CHAR_ARRAY;\\nchar LF;\\nchar CR;\\nCharUtils();\\ntoCharacterObject(String str);\\ntoChar(Character ch);\\ntoChar(Character ch,char defaultValue);\\ntoChar(String str);\\ntoChar(String str,char defaultValue);\\ntoIntValue(char ch);\\ntoIntValue(char ch,int defaultValue);\\ntoIntValue(Character ch);\\ntoIntValue(Character ch,int defaultValue);\\ntoString(char ch);\\ntoString(Character ch);\\nunicodeEscaped(char ch);\\nunicodeEscaped(Character ch);\\nisAscii(char ch);\\nisAsciiPrintable(char ch);\\nisAsciiControl(char ch);\\nisAsciiAlpha(char ch);\\nisAsciiAlphaUpper(char ch);\\nisAsciiAlphaLower(char ch);\\nisAsciiNumeric(char ch);\\nisAsciiAlphanumeric(char ch);\\nisHighSurrogate(char ch);\\nisCharType(Class targetType);\\ntoCharacterObject(char ch);\\n\", \"repo_level\" : \"\" }", "class_name": "CharUtils", "code": "public static boolean isAsciiAlphaUpper(final char ch){\n return ch >= 'A' && ch <= 'Z';\n}\n", "docstring": "/** \n *

      Checks whether the character is ASCII 7 bit alphabetic upper case.

       CharUtils.isAsciiAlphaUpper('a')  = false CharUtils.isAsciiAlphaUpper('A')  = true CharUtils.isAsciiAlphaUpper('3')  = false CharUtils.isAsciiAlphaUpper('-')  = false CharUtils.isAsciiAlphaUpper('\\n') = false CharUtils.isAsciiAlphaUpper('©') = false 
      \n * @param ch the character to check\n * @return true if between 65 and 90 inclusive\n */\n", "end_lineno": "497", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\n/**\n *

      Operations on char primitives and Character objects.

      \n *\n *

      This class tries to handle null input gracefully.\n * An exception will not be thrown for a null input.\n * Each method documents its behaviour in more detail.

      \n *\n *

      #ThreadSafe#

      \n * @author Apache Software Foundation\n * @since 2.1\n * @version $Id: CharUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class CharUtils {\n private static final String CHAR_STRING = //\n \"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\" +//\n \"\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\" + //\n \"\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\" + //\n \"\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\" +//\n \"\\u0020\\u0021\\\"\\u0023\\u0024\\u0025\\u0026\\u0027\" + //\n \"\\u0028\\u0029\\u002a\\u002b\\u002c\\u002d\\u002e\\u002f\" + //\n \"\\u0030\\u0031\\u0032\\u0033\\u0034\\u0035\\u0036\\u0037\" + //\n \"\\u0038\\u0039\\u003a\\u003b\\u003c\\u003d\\u003e\\u003f\" + //\n \"\\u0040\\u0041\\u0042\\u0043\\u0044\\u0045\\u0046\\u0047\" + //\n \"\\u0048\\u0049\\u004a\\u004b\\u004c\\u004d\\u004e\\u004f\" + //\n \"\\u0050\\u0051\\u0052\\u0053\\u0054\\u0055\\u0056\\u0057\" +//\n \"\\u0058\\u0059\\u005a\\u005b\\\\\\u005d\\u005e\\u005f\" + //\n \"\\u0060\\u0061\\u0062\\u0063\\u0064\\u0065\\u0066\\u0067\" +//\n \"\\u0068\\u0069\\u006a\\u006b\\u006c\\u006d\\u006e\\u006f\" +//\n \"\\u0070\\u0071\\u0072\\u0073\\u0074\\u0075\\u0076\\u0077\" +//\n \"\\u0078\\u0079\\u007a\\u007b\\u007c\\u007d\\u007e\\u007f\";\n private static final String[] CHAR_STRING_ARRAY = new String[128];\n private static final Character[] CHAR_ARRAY = new Character[128];\n /**\n * \n linefeed LF ('\\n').\n *\n * @see JLF: Escape Sequences\n * for Character and String Literals\n * @since 2.2\n */\n public static final char LF = '\\n';\n /**\n * carriage return CR ('\\r').\n *\n * @see JLF: Escape Sequences\n * for Character and String Literals\n * @since 2.2\n */\n public static final char CR = '\\r';\n\n static {\n for (int i = 127; i >= 0; i--) {\n CharUtils.CHAR_STRING_ARRAY[i] = CharUtils.CHAR_STRING.substring(i, i + 1);\n CharUtils.CHAR_ARRAY[i] = new Character((char) i);\n }\n }\n\n /**\n *

      CharUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as CharUtils.toString('c');.

      \n *\n *

      This constructor i public to permit tools that require a JavaBean instance\n * to operate.

      \n */\n public CharUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the character to a Character.

      \n *\n *

      For ASCII 7 bit characters, this uses a cache that will return the\n * same Character object each time.

      \n *\n *
      \n     *   CharUtils.toCharacterObject(' ')  = ' '\n     *   CharUtils.toCharacterObject('A')  = 'A'\n     * 
      \n *\n * @param ch the character to convert\n * @return a Character of the specified character\n */\n public static Character toCharacterObject(final char ch) {\n if (ch < CharUtils.CHAR_ARRAY.length) {\n return CharUtils.CHAR_ARRAY[ch];\n }\n return new Character(ch);\n }\n\n /**\n *

      Converts the String to a Character using the first character, returning\n * null for empty Strings.

      \n *\n *

      For ASCII 7 bit characters, this uses a cache that will return the\n * same Character object each time.

      \n *\n *
      \n     *   CharUtils.toCharacterObject(null) = null\n     *   CharUtils.toCharacterObject(\"\")   = null\n     *   CharUtils.toCharacterObject(\"A\")  = 'A'\n     *   CharUtils.toCharacterObject(\"BA\") = 'B'\n     * 
      \n *\n * @param str the character to convert\n * @return the Character value of the first letter of the String\n */\n public static Character toCharacterObject(final String str) {\n if (StringUtils.isEmpty(str)) {\n return null;\n }\n return CharUtils.toCharacterObject(str.charAt(0));\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the Character to a char throwing an exception for null.

      \n *\n *
      \n     *   CharUtils.toChar(null) = IllegalArgumentException\n     *   CharUtils.toChar(' ')  = ' '\n     *   CharUtils.toChar('A')  = 'A'\n     * 
      \n *\n * @param ch the character to convert\n * @return the char value of the Character\n * @throws IllegalArgumentException if the Character is null\n */\n public static char toChar(final Character ch) {\n if (ch == null) {\n throw new IllegalArgumentException(\"The Character must not be null\");\n }\n return ch.charValue();\n }\n\n /**\n *

      Converts the Character to a char handling null.

      \n *\n *
      \n     *   CharUtils.toChar(null, 'X') = 'X'\n     *   CharUtils.toChar(' ', 'X')  = ' '\n     *   CharUtils.toChar('A', 'X')  = 'A'\n     * 
      \n *\n * @param ch the character to convert\n * @param defaultValue the value to use if the Character is null\n * @return the char value of the Character or the default if null\n */\n public static char toChar(final Character ch, final char defaultValue) {\n if (ch == null) {\n return defaultValue;\n }\n return ch.charValue();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the String to a char using the first character, throwing\n * an exception on empty Strings.

      \n *\n *
      \n     *   CharUtils.toChar(null) = IllegalArgumentException\n     *   CharUtils.toChar(\"\")   = IllegalArgumentException\n     *   CharUtils.toChar(\"A\")  = 'A'\n     *   CharUtils.toChar(\"BA\") = 'B'\n     * 
      \n *\n * @param str the character to convert\n * @return the char value of the first letter of the String\n * @throws IllegalArgumentException if the String is empty\n */\n public static char toChar(final String str) {\n if (StringUtils.isEmpty(str)) {\n throw new IllegalArgumentException(\"The String must not be empty\");\n }\n return str.charAt(0);\n }\n\n /**\n *

      Converts the String to a char using the first character, defaulting\n * the value on empty Strings.

      \n *\n *
      \n     *   CharUtils.toChar(null, 'X') = 'X'\n     *   CharUtils.toChar(\"\", 'X')   = 'X'\n     *   CharUtils.toChar(\"A\", 'X')  = 'A'\n     *   CharUtils.toChar(\"BA\", 'X') = 'B'\n     * 
      \n *\n * @param str the character to convert\n * @param defaultValue the value to use if the Character is null\n * @return the char value of the first letter of the String or the default if null\n */\n public static char toChar(final String str, final char defaultValue) {\n if (StringUtils.isEmpty(str)) {\n return defaultValue;\n }\n return str.charAt(0);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

      \n *\n *

      This method coverts the char '1' to the int 1 and so on.

      \n *\n *
      \n     *   CharUtils.toIntValue('3')  = 3\n     *   CharUtils.toIntValue('A')  = IllegalArgumentException\n     * 
      \n *\n * @param ch the character to convert\n * @return the int value of the character\n * @throws IllegalArgumentException if the character is not ASCII numeric\n */\n public static int toIntValue(final char ch) {\n if (CharUtils.isAsciiNumeric(ch) == false) {\n throw new IllegalArgumentException(\"The character \" + ch + \" is not in the range '0' - '9'\");\n }\n return ch - 48;\n }\n\n /**\n *

      Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

      \n *\n *

      This method coverts the char '1' to the int 1 and so on.

      \n *\n *
      \n     *   CharUtils.toIntValue('3', -1)  = 3\n     *   CharUtils.toIntValue('A', -1)  = -1\n     * 
      \n *\n * @param ch the character to convert\n * @param defaultValue the default value to use if the character is not numeric\n * @return the int value of the character\n */\n public static int toIntValue(final char ch, final int defaultValue) {\n if (CharUtils.isAsciiNumeric(ch) == false) {\n return defaultValue;\n }\n return ch - 48;\n }\n\n /**\n *

      Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

      \n *\n *

      This method coverts the char '1' to the int 1 and so on.

      \n *\n *
      \n     *   CharUtils.toIntValue(null) = IllegalArgumentException\n     *   CharUtils.toIntValue('3')  = 3\n     *   CharUtils.toIntValue('A')  = IllegalArgumentException\n     * 
      \n *\n * @param ch the character to convert, not null\n * @return the int value of the character\n * @throws IllegalArgumentException if the Character is not ASCII numeric or is null\n */\n public static int toIntValue(final Character ch) {\n if (ch == null) {\n throw new IllegalArgumentException(\"The character must not be null\");\n }\n return CharUtils.toIntValue(ch.charValue());\n }\n\n /**\n *

      Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

      \n *\n *

      This method coverts the char '1' to the int 1 and so on.

      \n *\n *
      \n     *   CharUtils.toIntValue(null, -1) = -1\n     *   CharUtils.toIntValue('3', -1)  = 3\n     *   CharUtils.toIntValue('A', -1)  = -1\n     * 
      \n *\n * @param ch the character to convert\n * @param defaultValue the default value to use if the character is not numeric\n * @return the int value of the character\n */\n public static int toIntValue(final Character ch, final int defaultValue) {\n if (ch == null) {\n return defaultValue;\n }\n return CharUtils.toIntValue(ch.charValue(), defaultValue);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

      Converts the character to a String that contains the one character.

      \n *\n *

      For ASCII 7 bit characters, this uses a cache that will return the\n * same String object each time.

      \n *\n *
      \n     *   CharUtils.toString(' ')  = \" \"\n     *   CharUtils.toString('A')  = \"A\"\n     * 
      \n *\n * @param ch the character to convert\n * @return a String containing the one specified character\n */\n public static String toString(final char ch) {\n if (ch < 128) {\n return CharUtils.CHAR_STRING_ARRAY[ch];\n }\n return new String(new char[] { ch });\n }\n\n /**\n *

      Converts the character to a String that contains the one character.

      \n *\n *

      For ASCII 7 bit characters, this uses a cache that will return the\n * same String object each time.

      \n *\n *

      If null is passed in, null will be returned.

      \n *\n *
      \n     *   CharUtils.toString(null) = null\n     *   CharUtils.toString(' ')  = \" \"\n     *   CharUtils.toString('A')  = \"A\"\n     * 
      \n *\n * @param ch the character to convert\n * @return a String containing the one specified character\n */\n public static String toString(final Character ch) {\n if (ch == null) {\n return null;\n }\n return CharUtils.toString(ch.charValue());\n }\n //--------------------------------------------------------------------------\n\n /**\n *

      Converts the string to the unicode format '\\u0020'.

      \n *\n *

      This format is the Java source code format.

      \n *\n *
      \n     *   CharUtils.unicodeEscaped(' ') = \"\\u0020\"\n     *   CharUtils.unicodeEscaped('A') = \"\\u0041\"\n     * 
      \n *\n * @param ch the character to convert\n * @return the escaped unicode string\n */\n public static String unicodeEscaped(final char ch) {\n if (ch < 0x10) {\n return \"\\\\u000\" + Integer.toHexString(ch);\n } else if (ch < 0x100) {\n return \"\\\\u00\" + Integer.toHexString(ch);\n } else if (ch < 0x1000) {\n return \"\\\\u0\" + Integer.toHexString(ch);\n }\n return \"\\\\u\" + Integer.toHexString(ch);\n }\n\n /**\n *

      Converts the string to the unicode format '\\u0020'.

      \n *\n *

      This format is the Java source code format.

      \n *\n *

      If null is passed in, null will be returned.

      \n *\n *
      \n     *   CharUtils.unicodeEscaped(null) = null\n     *   CharUtils.unicodeEscaped(' ')  = \"\\u0020\"\n     *   CharUtils.unicodeEscaped('A')  = \"\\u0041\"\n     * 
      \n *\n * @param ch the character to convert, may be null\n * @return the escaped unicode string, null if null input\n */\n public static String unicodeEscaped(final Character ch) {\n if (ch == null) {\n return null;\n }\n return CharUtils.unicodeEscaped(ch.charValue());\n }\n //--------------------------------------------------------------------------\n\n /**\n *

      Checks whether the character is ASCII 7 bit.

      \n *\n *
      \n     *   CharUtils.isAscii('a')  = true\n     *   CharUtils.isAscii('A')  = true\n     *   CharUtils.isAscii('3')  = true\n     *   CharUtils.isAscii('-')  = true\n     *   CharUtils.isAscii('\\n') = true\n     *   CharUtils.isAscii('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if less than 128\n */\n public static boolean isAscii(final char ch) {\n return ch < 128;\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit printable.

      \n *\n *
      \n     *   CharUtils.isAsciiPrintable('a')  = true\n     *   CharUtils.isAsciiPrintable('A')  = true\n     *   CharUtils.isAsciiPrintable('3')  = true\n     *   CharUtils.isAsciiPrintable('-')  = true\n     *   CharUtils.isAsciiPrintable('\\n') = false\n     *   CharUtils.isAsciiPrintable('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 32 and 126 inclusive\n */\n public static boolean isAsciiPrintable(final char ch) {\n return ch >= 32 && ch < 127;\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit control.

      \n *\n *
      \n     *   CharUtils.isAsciiControl('a')  = false\n     *   CharUtils.isAsciiControl('A')  = false\n     *   CharUtils.isAsciiControl('3')  = false\n     *   CharUtils.isAsciiControl('-')  = false\n     *   CharUtils.isAsciiControl('\\n') = true\n     *   CharUtils.isAsciiControl('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if less than 32 or equals 127\n */\n public static boolean isAsciiControl(final char ch) {\n return ch < 32 || ch == 127;\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit alphabetic.

      \n *\n *
      \n     *   CharUtils.isAsciiAlpha('a')  = true\n     *   CharUtils.isAsciiAlpha('A')  = true\n     *   CharUtils.isAsciiAlpha('3')  = false\n     *   CharUtils.isAsciiAlpha('-')  = false\n     *   CharUtils.isAsciiAlpha('\\n') = false\n     *   CharUtils.isAsciiAlpha('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 65 and 90 or 97 and 122 inclusive\n */\n public static boolean isAsciiAlpha(final char ch) {\n return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z';\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit alphabetic upper case.

      \n *\n *
      \n     *   CharUtils.isAsciiAlphaUpper('a')  = false\n     *   CharUtils.isAsciiAlphaUpper('A')  = true\n     *   CharUtils.isAsciiAlphaUpper('3')  = false\n     *   CharUtils.isAsciiAlphaUpper('-')  = false\n     *   CharUtils.isAsciiAlphaUpper('\\n') = false\n     *   CharUtils.isAsciiAlphaUpper('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 65 and 90 inclusive\n */\n public static boolean isAsciiAlphaUpper(final char ch) {\n return ch >= 'A' && ch <= 'Z';\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit alphabetic lower case.

      \n *\n *
      \n     *   CharUtils.isAsciiAlphaLower('a')  = true\n     *   CharUtils.isAsciiAlphaLower('A')  = false\n     *   CharUtils.isAsciiAlphaLower('3')  = false\n     *   CharUtils.isAsciiAlphaLower('-')  = false\n     *   CharUtils.isAsciiAlphaLower('\\n') = false\n     *   CharUtils.isAsciiAlphaLower('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 97 and 122 inclusive\n */\n public static boolean isAsciiAlphaLower(final char ch) {\n return ch >= 'a' && ch <= 'z';\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit numeric.

      \n *\n *
      \n     *   CharUtils.isAsciiNumeric('a')  = false\n     *   CharUtils.isAsciiNumeric('A')  = false\n     *   CharUtils.isAsciiNumeric('3')  = true\n     *   CharUtils.isAsciiNumeric('-')  = false\n     *   CharUtils.isAsciiNumeric('\\n') = false\n     *   CharUtils.isAsciiNumeric('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 48 and 57 inclusive\n */\n public static boolean isAsciiNumeric(final char ch) {\n return ch >= '0' && ch <= '9';\n }\n\n /**\n *

      Checks whether the character is ASCII 7 bit numeric.

      \n *\n *
      \n     *   CharUtils.isAsciiAlphanumeric('a')  = true\n     *   CharUtils.isAsciiAlphanumeric('A')  = true\n     *   CharUtils.isAsciiAlphanumeric('3')  = true\n     *   CharUtils.isAsciiAlphanumeric('-')  = false\n     *   CharUtils.isAsciiAlphanumeric('\\n') = false\n     *   CharUtils.isAsciiAlphanumeric('©') = false\n     * 
      \n *\n * @param ch the character to check\n * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive\n */\n public static boolean isAsciiAlphanumeric(final char ch) {\n return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9';\n }\n // ----------------- Following code copied from Apache Harmony (Character class)\n\n /**\n * Indicates whether {@code ch} is a high- (or leading-) surrogate code unit\n * that is used for representing supplementary characters in UTF-16\n * encoding.\n *\n * @param ch\n * the character to test.\n * @return {@code true} if {@code ch} is a high-surrogate code unit;\n * {@code false} otherwise.\n */\n static boolean isHighSurrogate(final char ch) {\n return '\\uD800' <= ch && '\\uDBFF' >= ch;\n }\n\n //\n public static boolean isCharType(Class targetType) {\n return targetType.equals(Character.class) || targetType.equals(Character.TYPE);\n }\n}\n", "file_name": "CharUtils.java", "human_label": "Return true if the character is ASCII alphabetic upper case.Otherwise return false.", "level": "self_contained", "lineno": "480", "name": "isAsciiAlphaUpper", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636767781a6d9265ec018250", "all_context": "{ \"class_level\" : \"import org.apache.log4j.spi.Filter;\\nimport org.apache.log4j.spi.LoggingEvent;\\nimport org.apache.log4j.helpers.OptionConverter;\\nString STRING_TO_MATCH_OPTION;\\nString ACCEPT_ON_MATCH_OPTION;\\nboolean acceptOnMatch;\\nString stringToMatch;\\ngetOptionStrings();\\nsetOption(String key,String value);\\nsetStringToMatch(String s);\\ngetStringToMatch();\\nsetAcceptOnMatch(boolean acceptOnMatch);\\ngetAcceptOnMatch();\\n\", \"repo_level\" : \"public interface Filter {public void activateOptions();\\npublic int decide(LoggingEvent event);\\npublic void setNext(Filter next);\\npublic Filter getNext();\\n }\\npublic interface LoggingEvent {public LocationInfo getLocationInformation();\\npublic Level getLevel();\\npublic String getLoggerName();\\npublic Category getLogger();\\npublic Object getMessage();\\npublic String getNDC();\\npublic Object getMDC(String key);\\npublic void getMDCCopy();\\npublic String getRenderedMessage();\\nstatic long getStartTime();\\npublic String getThreadName();\\npublic ThrowableInformation getThrowableInformation();\\npublic String[] getThrowableStrRep();\\nfinal void setProperty(String propName,String propValue);\\nfinal String getProperty(String key);\\nfinal boolean locationInformationExists();\\nfinal long getTimeStamp();\\npublic Set getPropertyKeySet();\\npublic Map getProperties();\\npublic String getFQNOfLoggerClass();\\npublic Object removeProperty(String propName);\\n }\\npublic interface OptionConverter {static String[] concatanateArrays(String[] l,String[] r);\\nstatic String convertSpecialChars(String s);\\nstatic String getSystemProperty(String key,String def);\\nstatic Object instantiateByKey(Properties props,String key,Class superClass,Object defaultValue);\\nstatic boolean toBoolean(String value,boolean dEfault);\\nstatic int toInt(String value,int dEfault);\\nstatic Level toLevel(String value,Level defaultValue);\\nstatic long toFileSize(String value,long dEfault);\\nstatic String findAndSubst(String key,Properties props);\\nstatic Object instantiateByClassName(String className,Class superClass,Object defaultValue);\\nstatic String substVars(String val,Properties props);\\npublic void selectAndConfigure(InputStream inputStream,String clazz,LoggerRepository hierarchy);\\npublic void selectAndConfigure(URL url,String clazz,LoggerRepository hierarchy);\\n }\\n\" }", "class_name": "StringMatchFilter", "code": "public int decide(LoggingEvent event){\n String msg=event.getRenderedMessage();\n if (msg == null || stringToMatch == null) return Filter.NEUTRAL;\n if (msg.indexOf(stringToMatch) == -1) {\n return Filter.NEUTRAL;\n }\n else {\n if (acceptOnMatch) {\n return Filter.ACCEPT;\n }\n else {\n return Filter.DENY;\n }\n }\n}\n", "docstring": "/** \n * Returns {@link Filter#NEUTRAL} is there is no string match.\n */\n", "end_lineno": "120", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.log4j.varia;\n\nimport org.apache.log4j.spi.Filter;\nimport org.apache.log4j.spi.LoggingEvent;\nimport org.apache.log4j.helpers.OptionConverter;\n\n/**\n * This is a very simple filter based on string matching.\n *\n *

      The filter admits two options StringToMatch and\n * AcceptOnMatch. If there is a match between the value of the\n * StringToMatch option and the message of the {@link org.apache.log4j.spi.LoggingEvent},\n * then the {@link #decide(LoggingEvent)} method returns {@link org.apache.log4j.spi.Filter#ACCEPT} if\n * the AcceptOnMatch option value is true, if it is false then\n * {@link org.apache.log4j.spi.Filter#DENY} is returned. If there is no match, {@link\n * org.apache.log4j.spi.Filter#NEUTRAL} is returned.\n *\n * @author Ceki Gülcü\n * @since 0.9.0 \n */\npublic class StringMatchFilter extends Filter {\n \n /**\n @deprecated Options are now handled using the JavaBeans paradigm.\n This constant is not longer needed and will be removed in the\n near term.\n */\n public static final String STRING_TO_MATCH_OPTION = \"StringToMatch\";\n\n /**\n @deprecated Options are now handled using the JavaBeans paradigm.\n This constant is not longer needed and will be removed in the\n near term.\n */\n public static final String ACCEPT_ON_MATCH_OPTION = \"AcceptOnMatch\";\n \n boolean acceptOnMatch = true;\n String stringToMatch;\n \n /**\n @deprecated We now use JavaBeans introspection to configure\n components. Options strings are no longer needed.\n */\n public\n String[] getOptionStrings() {\n return new String[] {STRING_TO_MATCH_OPTION, ACCEPT_ON_MATCH_OPTION};\n }\n\n /**\n @deprecated Use the setter method for the option directly instead\n of the generic setOption method. \n */\n public\n void setOption(String key, String value) { \n \n if(key.equalsIgnoreCase(STRING_TO_MATCH_OPTION)) {\n stringToMatch = value;\n } else if (key.equalsIgnoreCase(ACCEPT_ON_MATCH_OPTION)) {\n acceptOnMatch = OptionConverter.toBoolean(value, acceptOnMatch);\n }\n }\n \n public\n void setStringToMatch(String s) {\n stringToMatch = s;\n }\n \n public\n String getStringToMatch() {\n return stringToMatch;\n }\n \n public\n void setAcceptOnMatch(boolean acceptOnMatch) {\n this.acceptOnMatch = acceptOnMatch;\n }\n \n public\n boolean getAcceptOnMatch() {\n return acceptOnMatch;\n }\n\n /**\n Returns {@link Filter#NEUTRAL} is there is no string match.\n */\n public\n int decide(LoggingEvent event) {\n String msg = event.getRenderedMessage();\n\n if(msg == null || stringToMatch == null)\n return Filter.NEUTRAL;\n \n\n if( msg.indexOf(stringToMatch) == -1 ) {\n return Filter.NEUTRAL;\n } else { // we've got a match\n if(acceptOnMatch) {\n\treturn Filter.ACCEPT;\n } else {\n\treturn Filter.DENY;\n }\n }\n }\n}\n", "file_name": "StringMatchFilter.java", "human_label": "Return a decision based on the message generated by the event and whether the given string is matched.", "level": "project_runnable", "lineno": "100", "name": "decide", "oracle_context": "{ \"apis\" : \"[getRenderedMessage, indexOf]\", \"classes\" : \"[String, Filter]\", \"vars\" : \"[NEUTRAL, ACCEPT, DENY, stringToMatch, acceptOnMatch]\" }", "package": "org.apache.log4j.varia", "project": "logging-log4j1-main" }, { "_id": "636766861a6d9265ec017553", "all_context": "{ \"class_level\" : \"import java.util.Collections;\\nimport java.util.Comparator;\\nimport java.util.HashMap;\\nimport java.util.List;\\nimport java.util.Map;\\nimport java.util.regex.Matcher;\\nimport java.util.regex.Pattern;\\nimport java.util.regex.PatternSyntaxException;\\nComparator COMPARATOR;\\nPattern TEMPLATE_NAMES_PATTERN;\\nUriTemplate EMPTY;\\nString template;\\nString normalizedTemplate;\\nUriPattern pattern;\\nboolean endsWithSlash;\\nList templateVariables;\\nint numOfExplicitRegexes;\\nint numOfCharacters;\\ncompare(UriTemplate o1,UriTemplate o2);\\nUriTemplate();\\nUriTemplate(String template);\\nUriTemplate(UriTemplateParser templateParser);\\ndestroy();\\ngetTemplate();\\ngetPattern();\\nendsWithSlash();\\ngetTemplateVariables();\\nisTemplateVariablePresent(String name);\\ngetNumberOfExplicitRegexes();\\ngetNumberOfExplicitCharacters();\\ngetNumberOfTemplateVariables();\\nmatch(CharSequence uri,Map templateVariableToValue);\\nmatch(CharSequence uri,List groupValues);\\ncreateURI(Map values);\\ncreateURI(String values);\\ncreateURI(String[] values,int offset,int length);\\ntoString();\\nhashCode();\\nequals(Object o);\\ncreateURI(String scheme,String userInfo,String host,String port,String path,String query,String fragment,Map values,boolean encode);\\ncreateURI(String scheme,String authority,String userInfo,String host,String port,String path,String query,String fragment,Map values,boolean encode);\\ncreateURIWithStringValues(String scheme,String userInfo,String host,String port,String path,String query,String fragment,Map values,boolean encode);\\ncreateURIWithStringValues(String scheme,String authority,String userInfo,String host,String port,String path,String query,String fragment,Map values,boolean encode);\\ncreateURIComponent(Type t,String template,Map values,boolean encode,StringBuilder b);\\ncreateURI(String scheme,String userInfo,String host,String port,String path,String query,String fragment,Object[] values,boolean encode);\\ncreateURI(String scheme,String authority,String userInfo,String host,String port,String path,String query,String fragment,Object[] values,boolean encode);\\ncreateURIWithStringValues(String scheme,String userInfo,String host,String port,String path,String query,String fragment,String[] values,boolean encode);\\ncreateURIWithStringValues(String scheme,String authority,String userInfo,String host,String port,String path,String query,String fragment,String[] values,boolean encode);\\ncreateURIComponent(Type t,String template,String[] values,int offset,boolean encode,Map mapValues,StringBuilder b);\\ntemplateVariableHasNoValue(String tVariable);\\ncreateUriPattern(UriTemplateParser templateParser);\\n\", \"repo_level\" : \"\" }", "class_name": "UriTemplate", "code": "public final boolean isTemplateVariablePresent(String name){\n for ( String s : templateVariables) {\n if (s.equals(name)) return true;\n }\n return false;\n}\n", "docstring": "/** \n * Ascertain if a template variable is a member of this template.\n * @param name name The template variable.\n * @return true if the template variable is a member of the template, otherwisefalse.\n */\n", "end_lineno": "301", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * Copyright (c) 2010-2018 Oracle and/or its affiliates. All rights reserved.\n *\n * The contents of this file are subject to the terms of either the GNU\n * General Public License Version 2 only (\"GPL\") or the Common Development\n * and Distribution License(\"CDDL\") (collectively, the \"License\"). You\n * may not use this file except in compliance with the License. You can\n * obtain a copy of the License at\n * http://glassfish.java.net/public/CDDL+GPL_1_1.html\n * or packager/legal/LICENSE.txt. See the License for the specific\n * language governing permissions and limitations under the License.\n *\n * When distributing the software, include this License Header Notice in each\n * file and include the License file at packager/legal/LICENSE.txt.\n *\n * GPL Classpath Exception:\n * Oracle designates this particular file as subject to the \"Classpath\"\n * exception as provided by Oracle in the GPL Version 2 section of the License\n * file that accompanied this code.\n *\n * Modifications:\n * If applicable, add the following below the License Header, with the fields\n * enclosed by brackets [] replaced by your own identifying information:\n * \"Portions Copyright [year] [name of copyright owner]\"\n *\n * Contributor(s):\n * If you wish your version of this file to be governed by only the CDDL or\n * only the GPL Version 2, indicate your decision by adding \"[Contributor]\n * elects to include this software in this distribution under the [CDDL or GPL\n * Version 2] license.\" If you don't indicate a single choice of license, a\n * recipient has the option to distribute your version of this file under\n * either the CDDL, the GPL Version 2 or to extend the choice of license to\n * its licensees as provided above. However, if you add GPL Version 2 code\n * and therefore, elected the GPL Version 2 license, then the option applies\n * only if the new code is made subject to such option by the copyright\n * holder.\n */\n\npackage org.atmosphere.util.uri;\n\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport java.util.regex.PatternSyntaxException;\n\n\n/**\n * A URI template.\n *\n * @author Paul.Sandoz@Sun.Com\n */\npublic class UriTemplate {\n /**\n * Order the templates according according to JAX-RS.\n *

      \n * Sort the set of matching resource classes using the number of \n * characters in the regular expression not resulting from template \n * variables as the primary key, the number of matching groups\n * as a secondary key, and the number of explicit regular expression\n * declarations as the tertiary key.\n */\n static public final Comparator COMPARATOR = new Comparator() {\n public int compare(UriTemplate o1, UriTemplate o2) {\n if (o1 == null && o2 == null)\n return 0;\n if (o1 == null)\n return 1;\n if (o2 == null)\n return -1;\n \n if (o1 == EMPTY && o2 == EMPTY)\n return 0;\n if (o1 == EMPTY)\n return 1;\n if (o2 == EMPTY)\n return -1;\n\n // Compare the number of explicit characters\n // Note that it is important that o2 is compared against o1\n // so that a regular expression with say 10 explicit characters\n // is less than a regular expression with say 5 explicit characters.\n int i = o2.getNumberOfExplicitCharacters() - o1.getNumberOfExplicitCharacters();\n if (i != 0) return i;\n\n // If the number of explicit characters is equal\n // compare the number of template variables\n // Note that it is important that o2 is compared against o1\n // so that a regular expression with say 10 template variables\n // is less than a regular expression with say 5 template variables.\n i = o2.getNumberOfTemplateVariables() - o1.getNumberOfTemplateVariables();\n if (i != 0) return i;\n\n // If the number of template variables is equal\n // compare the number of explicit regexes\n i = o2.getNumberOfExplicitRegexes() - o1.getNumberOfExplicitRegexes();\n if (i != 0) return i;\n \n // If the number of explicit characters and template variables\n // are equal then comapre the regexes\n // The order does not matter as long as templates with different\n // explicit characters are distinguishable\n return o2.pattern.getRegex().compareTo(o1.pattern.getRegex());\n }\n };\n \n /**\n * The regular expression for matching URI templates and names.\n */\n private static final Pattern TEMPLATE_NAMES_PATTERN = Pattern.compile(\"\\\\{(\\\\w[-\\\\w.]*)}\");\n \n /**\n * The empty URI template that matches the null or empty URI path\n */\n public static final UriTemplate EMPTY = new UriTemplate();\n \n /**\n * The URI template.\n */\n private final String template;\n \n /**\n * The normalized URI template. Any explicit regex are removed to leave\n * the template variables.\n */\n private final String normalizedTemplate;\n\n /**\n * The pattern generated from the template\n */\n private final UriPattern pattern;\n \n /**\n * True if the URI template ends in a '/' character.\n */\n private final boolean endsWithSlash;\n \n /**\n * The template variables in the URI template.\n */\n private final List templateVariables;\n\n /**\n * The number of explicit regular expressions declared for template\n * variables.\n */\n private final int numOfExplicitRegexes;\n\n /**\n * The number of characters in the regular expression not resulting\n * from conversion of template variables.\n */\n private final int numOfCharacters;\n\n /**\n * Constructor for NULL template\n */\n private UriTemplate() {\n this.template = this.normalizedTemplate = \"\";\n this.pattern = UriPattern.EMPTY;\n this.endsWithSlash = false;\n this.templateVariables = Collections.emptyList();\n this.numOfExplicitRegexes = this.numOfCharacters = 0;\n }\n \n /**\n * Construct a new URI template.\n *

      \n * The template will be parsed to extract template variables.\n *

      \n * A specific regular expression will be generated from the template\n * to match URIs according to the template and map template variables to\n * template values.\n *

      \n * @param template the template.\n * @throws java.util.regex.PatternSyntaxException if the specified\n * regular expression could not be generated\n * @throws IllegalArgumentException if the template is null or\n * an empty string.\n */\n public UriTemplate(String template) throws\n PatternSyntaxException, IllegalArgumentException {\n this(new UriTemplateParser(template));\n }\n\n /**\n * Construct a new URI template.\n *

      \n * The template will be parsed to extract template variables.\n *

      \n * A specific regular expression will be generated from the template\n * to match URIs according to the template and map template variables to\n * template values.\n *

      \n * @param templateParser the parser to parse the template.\n * @throws java.util.regex.PatternSyntaxException if the specified\n * regular expression could not be generated\n * @throws IllegalArgumentException if the template is null or\n * an empty string.\n */\n protected UriTemplate(UriTemplateParser templateParser) throws \n PatternSyntaxException, IllegalArgumentException {\n this.template = templateParser.getTemplate();\n \n this.normalizedTemplate = templateParser.getNormalizedTemplate();\n\n this.pattern = createUriPattern(templateParser);\n\n this.numOfExplicitRegexes = templateParser.getNumberOfExplicitRegexes();\n \n this.numOfCharacters = templateParser.getNumberOfLiteralCharacters();\n\n this.endsWithSlash = template.charAt(template.length() - 1) == '/';\n\n this.templateVariables = templateParser.getNames();\n\n templateParser.destroy();\n }\n\n public UriTemplate destroy() {\n templateVariables.clear();\n return this;\n }\n\n /**\n * Create the URI pattern from a URI template parser.\n *\n * @param templateParser the URI template parser.\n * @return the URI pattern.\n */\n protected UriPattern createUriPattern(UriTemplateParser templateParser) {\n return new UriPattern(templateParser.getPattern(), templateParser.getGroupIndexes()); \n }\n \n /**\n * Get the URI template as a String.\n * @return the URI template.\n */\n public final String getTemplate() {\n return template;\n }\n\n /**\n * Get the URI pattern.\n * \n * @return the URI pattern.\n */\n public final UriPattern getPattern() {\n return pattern;\n }\n \n /**\n * @return true if the template ends in a '/', otherwise false.\n */\n public final boolean endsWithSlash() {\n return endsWithSlash;\n }\n \n /**\n * Get the list of template variables for the template.\n * @return the list of template variables.\n */\n public final List getTemplateVariables() {\n return templateVariables;\n }\n \n /**\n * Ascertain if a template variable is a member of this\n * template.\n * @param name name The template variable.\n * @return true if the template variable is a member of the template, otherwise\n * false.\n */\n public final boolean isTemplateVariablePresent(String name) {\n for (String s : templateVariables) {\n if (s.equals(name))\n return true;\n }\n \n return false;\n }\n\n /**\n * Get the number of explicit regexes declared in template variables.\n * \n * @return the number of explicit regexes.\n */\n public final int getNumberOfExplicitRegexes() {\n return numOfExplicitRegexes;\n }\n\n /** \n * Get the number of characters in the regular expression not resulting\n * from conversion of template variables.\n * \n * @return the number of explicit characters\n */\n public final int getNumberOfExplicitCharacters() {\n return numOfCharacters;\n }\n\n /**\n * Get the number of template variables.\n * @return the number of template variables.\n */\n public final int getNumberOfTemplateVariables() {\n return templateVariables.size();\n }\n\n /**\n * Match a URI against the template.\n *

      \n * If the URI matches against the pattern then the template variable to value \n * map will be filled with template variables as keys and template values as \n * values.\n *

      \n * \n * @param uri the uri to match against the template.\n * @param templateVariableToValue the map where to put template variables (as keys)\n * and template values (as values). The map is cleared before any\n * entries are put.\n * @return true if the URI matches the template, otherwise false.\n * @throws IllegalArgumentException if the uri or\n * templateVariableToValue is null.\n */\n public final boolean match(CharSequence uri, Map templateVariableToValue) throws\n IllegalArgumentException {\n if (templateVariableToValue == null) \n throw new IllegalArgumentException();\n\n return pattern.match(uri, templateVariables, templateVariableToValue);\n }\n \n /**\n * Match a URI against the template.\n *

      \n * If the URI matches against the pattern then the template variable to value \n * map will be filled with template variables as keys and template values as \n * values.\n *

      \n * \n * @param uri the uri to match against the template.\n * @param groupValues the list to store the values of a pattern's \n * capturing groups is matching is successful. The values are stored \n * in the same order as the pattern's capturing groups.\n * @return true if the URI matches the template, otherwise false.\n * @throws IllegalArgumentException if the uri or\n * templateVariableToValue is null.\n */\n public final boolean match(CharSequence uri, List groupValues) throws\n IllegalArgumentException {\n if (groupValues == null) \n throw new IllegalArgumentException();\n\n return pattern.match(uri, groupValues);\n }\n \n /**\n * Create a URI by substituting any template variables\n * for corresponding template values.\n *

      \n * A URI template variable without a value will be substituted by the \n * empty string.\n *\n * @param values the map of template variables to template values.\n * @return the URI.\n */\n public final String createURI(Map values) {\n StringBuilder b = new StringBuilder();\n // Find all template variables\n Matcher m = TEMPLATE_NAMES_PATTERN.matcher(normalizedTemplate);\n int i = 0;\n while(m.find()) {\n b.append(normalizedTemplate, i, m.start());\n String tValue = values.get(m.group(1));\n if (tValue != null) b.append(tValue);\n i = m.end();\n }\n b.append(normalizedTemplate, i, normalizedTemplate.length());\n return b.toString();\n }\n \n /**\n * Create a URI by substituting any template variables\n * for corresponding template values.\n *

      \n * A URI template varibale without a value will be substituted by the \n * empty string.\n *\n * @param values the array of template values. The values will be \n * substituted in order of occurence of unique template variables.\n * @return the URI.\n */\n public final String createURI(String... values) {\n return createURI(values, 0, values.length);\n }\n \n /**\n * Create a URI by substituting any template variables\n * for corresponding template values.\n *

      \n * A URI template variable without a value will be substituted by the \n * empty string.\n *\n * @param values the array of template values. The values will be \n * substituted in order of occurence of unique template variables.\n * @param offset the offset into the array\n * @param length the length of the array\n * @return the URI.\n */\n public final String createURI(String[] values, int offset, int length) {\n Map mapValues = new HashMap<>();\n StringBuilder b = new StringBuilder();\n // Find all template variables\n Matcher m = TEMPLATE_NAMES_PATTERN.matcher(normalizedTemplate);\n int v = offset;\n length += offset;\n int i = 0;\n while(m.find()) {\n b.append(normalizedTemplate, i, m.start());\n String tVariable = m.group(1);\n // Check if a template variable has already occurred\n // If so use the value to ensure that two or more declarations of \n // a template variable have the same value\n String tValue = mapValues.get(tVariable);\n if (tValue != null) {\n b.append(tValue);\n } else {\n if (v < length) {\n tValue = values[v++];\n if (tValue != null) {\n mapValues.put(tVariable, tValue);\n b.append(tValue);\n }\n }\n }\n i = m.end();\n }\n b.append(normalizedTemplate, i, normalizedTemplate.length());\n return b.toString();\n }\n \n @Override\n public final String toString() {\n return pattern.toString();\n }\n \n /**\n * Hashcode is calculated from String of the regular expression \n * generated from the template.\n * @return the hash code.\n */\n @Override\n public final int hashCode() {\n return pattern.hashCode();\n }\n\n /**\n * Equality is calculated from the String of the regular expression \n * generated from the templates.\n * @param o the reference object with which to compare.\n * @return true if equals, otherwise false.\n */\n @Override\n public final boolean equals(Object o) {\n if (o instanceof UriTemplate) {\n UriTemplate that = (UriTemplate)o;\n return this.pattern.equals(that.pattern);\n } else {\n return false;\n }\n }\n \n /**\n * Construct a URI from the component parts each of which may contain \n * template variables.\n *

      \n * A template values is an Object instance MUST support the toString() \n * method to convert the template value to a String instance.\n *\n * @param scheme the URI scheme component\n * @param userInfo the URI user info component\n * @param host the URI host component\n * @param port the URI port component\n * @param path the URI path component\n * @param query the URI query componnet\n * @param fragment the URI fragment component\n * @param values the template variable to value map\n * @param encode if true encode a template value according to the correspond\n * component type of the associated template variable, otherwise\n * contextually encode the template value\n * @return a URI\n */\n public static String createURI(final String scheme,\n final String userInfo, final String host, final String port,\n final String path, final String query, final String fragment,\n final Map values, final boolean encode) {\n return createURI(scheme, null, userInfo, host, port, path, query, fragment,\n values, encode);\n }\n \n /**\n * Construct a URI from the component parts each of which may contain\n * template variables.\n *

      \n * A template values is an Object instance MUST support the toString()\n * method to convert the template value to a String instance.\n *\n * @param scheme the URI scheme component\n * @param authority the URI authority component\n * @param userInfo the URI user info component\n * @param host the URI host component\n * @param port the URI port component\n * @param path the URI path component\n * @param query the URI query componnet\n * @param fragment the URI fragment component\n * @param values the template variable to value map\n * @param encode if true encode a template value according to the correspond\n * component type of the associated template variable, otherwise\n * contextually encode the template value\n * @return a URI\n */\n public final static String createURI(\n final String scheme, String authority,\n final String userInfo, final String host, final String port,\n final String path, final String query, final String fragment,\n final Map values, final boolean encode) {\n Map stringValues = new HashMap<>();\n for (Map.Entry e : values.entrySet()) {\n if (e.getValue() != null)\n stringValues.put(e.getKey(), e.getValue().toString());\n }\n\n return createURIWithStringValues(scheme, authority,\n userInfo, host, port, path, query, fragment,\n stringValues, encode);\n }\n\n /**\n * Construct a URI from the component parts each of which may contain \n * template variables.\n *

      \n * A template value is an Object instance that MUST support the toString() \n * method to convert the template value to a String instance.\n *\n * @param scheme the URI scheme component\n * @param userInfo the URI user info component\n * @param host the URI host component\n * @param port the URI port component\n * @param path the URI path component\n * @param query the URI query componnet\n * @param fragment the URI fragment component\n * @param values the template variable to value map\n * @param encode if true encode a template value according to the correspond\n * component type of the associated template variable, otherwise\n * contextually encode the template value\n * @return a URI\n */\n public final static String createURIWithStringValues(final String scheme,\n final String userInfo, final String host, final String port,\n final String path, final String query, final String fragment,\n final Map values, final boolean encode) {\n return createURIWithStringValues(scheme, null,\n userInfo, host, port, path, query, fragment,\n values, encode);\n }\n \n /**\n * Construct a URI from the component parts each of which may contain\n * template variables.\n *

      \n * A template value is an Object instance that MUST support the toString()\n * method to convert the template value to a String instance.\n *\n * @param scheme the URI scheme component\n * @param authority the URI authority info component\n * @param userInfo the URI user info component\n * @param host the URI host component\n * @param port the URI port component\n * @param path the URI path component\n * @param query the URI query componnet\n * @param fragment the URI fragment component\n * @param values the template variable to value map\n * @param encode if true encode a template value according to the correspond\n * component type of the associated template variable, otherwise\n * contextually encode the template value\n * @return a URI\n */\n public static String createURIWithStringValues(\n final String scheme, final String authority,\n final String userInfo, final String host, final String port,\n final String path, final String query, final String fragment,\n final Map values, final boolean encode) {\n\n StringBuilder sb = new StringBuilder();\n\n if (scheme != null)\n createURIComponent(UriComponent.Type.SCHEME, scheme, values, false, sb).\n append(':');\n\n if (userInfo != null || host != null || port != null) {\n sb.append(\"//\");\n\n if (userInfo != null && userInfo.length() > 0)\n createURIComponent(UriComponent.Type.USER_INFO, userInfo, values, encode, sb).\n append('@');\n\n if (host != null) {\n // TODO check IPv6 address\n createURIComponent(UriComponent.Type.HOST, host, values, encode, sb);\n }\n\n if (port != null && port.length() > 0) {\n sb.append(':');\n createURIComponent(UriComponent.Type.PORT, port, values, false, sb);\n }\n } else if (authority != null) {\n sb.append(\"//\");\n \n createURIComponent(UriComponent.Type.AUTHORITY, authority, values, encode, sb);\n }\n\n if (path != null)\n createURIComponent(UriComponent.Type.PATH, path, values, encode, sb);\n\n if (query != null && query.length() > 0) {\n sb.append('?');\n createURIComponent(UriComponent.Type.QUERY_PARAM, query, values, encode, sb);\n }\n\n if (fragment != null && fragment.length() > 0) {\n sb.append('#');\n createURIComponent(UriComponent.Type.FRAGMENT, fragment, values, encode, sb);\n }\n return sb.toString();\n }\n\n private static StringBuilder createURIComponent(final UriComponent.Type t, \n String template,\n final Map values,\n final boolean encode, \n final StringBuilder b) {\n if (template.indexOf('{') == -1) {\n b.append(template);\n return b;\n }\n \n // Find all template variables\n template = new UriTemplateParser(template).getNormalizedTemplate();\n final Matcher m = TEMPLATE_NAMES_PATTERN.matcher(template);\n\n int i = 0;\n while(m.find()) {\n b.append(template, i, m.start());\n Object tValue = values.get(m.group(1));\n if (tValue != null) {\n if (encode)\n tValue = UriComponent.encode(tValue.toString(), t);\n else\n tValue =UriComponent.contextualEncode(tValue.toString(), t);\n b.append(tValue);\n } else {\n throw templateVariableHasNoValue(m.group(1));\n }\n i = m.end();\n }\n b.append(template, i, template.length());\n return b;\n }\n \n /**\n * Construct a URI from the component parts each of which may contain \n * template variables.\n *

      \n * The template values are an array of Object and each Object instance\n * MUST support the toString() method to convert the template value to\n * a String instance.\n * \n * @param scheme the URI scheme component\n * @param userInfo the URI user info component\n * @param host the URI host component\n * @param port the URI port component\n * @param path the URI path component\n * @param query the URI query componnet\n * @param fragment the URI fragment component\n * @param values the array of template values\n * @param encode if true encode a template value according to the correspond\n * component type of the associated template variable, otherwise\n * contextually encode the template value\n * @return a URI\n */\n public static String createURI(final String scheme,\n final String userInfo, final String host, final String port,\n final String path, final String query, final String fragment,\n final Object[] values, final boolean encode) {\n return createURI(scheme, null,\n userInfo, host, port, path, query, fragment,\n values, encode);\n }\n \n /**\n * Construct a URI from the component parts each of which may contain\n * template variables.\n *

      \n * The template values are an array of Object and each Object instance\n * MUST support the toString() method to convert the template value to\n * a String instance.\n *\n * @param scheme the URI scheme component\n * @param authority the URI authority component\n * @param userInfo the URI user info component\n * @param host the URI host component\n * @param port the URI port component\n * @param path the URI path component\n * @param query the URI query componnet\n * @param fragment the URI fragment component\n * @param values the array of template values\n * @param encode if true encode a template value according to the correspond\n * component type of the associated template variable, otherwise\n * contextually encode the template value\n * @return a URI\n */\n public static String createURI(\n final String scheme, String authority,\n final String userInfo, final String host, final String port,\n final String path, final String query, final String fragment,\n final Object[] values, final boolean encode) {\n\n String[] stringValues = new String[values.length];\n for (int i = 0; i < values.length; i++) {\n if (values[i] != null)\n stringValues[i] = values[i].toString();\n }\n\n return createURIWithStringValues(\n scheme, authority,\n userInfo, host, port, path, query, fragment,\n stringValues, encode);\n }\n\n /**\n * Construct a URI from the component parts each of which may contain \n * template variables.\n *\n * @param scheme the URI scheme component\n * @param userInfo the URI user info component\n * @param host the URI host component\n * @param port the URI port component\n * @param path the URI path component\n * @param query the URI query componnet\n * @param fragment the URI fragment component\n * @param values the array of template values\n * @param encode if true encode a template value according to the correspond\n * component type of the associated template variable, otherwise\n * contextually encode the template value\n * @return a URI\n */\n public static String createURIWithStringValues(final String scheme,\n final String userInfo, final String host, final String port,\n final String path, final String query, final String fragment,\n final String[] values, final boolean encode) {\n return createURIWithStringValues(\n scheme, null,\n userInfo, host, port, path, query, fragment,\n values, encode);\n }\n \n /**\n * Construct a URI from the component parts each of which may contain\n * template variables.\n *\n * @param scheme the URI scheme component\n * @param authority the URI authority component\n * @param userInfo the URI user info component\n * @param host the URI host component\n * @param port the URI port component\n * @param path the URI path component\n * @param query the URI query componnet\n * @param fragment the URI fragment component\n * @param values the array of template values\n * @param encode if true encode a template value according to the correspond\n * component type of the associated template variable, otherwise\n * contextually encode the template value\n * @return a URI\n */\n public static String createURIWithStringValues(\n final String scheme, final String authority,\n final String userInfo, final String host, final String port,\n final String path, final String query, final String fragment,\n final String[] values, final boolean encode) {\n\n final Map mapValues = new HashMap<>();\n final StringBuilder sb = new StringBuilder();\n int offset = 0;\n\n if (scheme != null) {\n offset = createURIComponent(UriComponent.Type.SCHEME, scheme, values,\n offset, false, mapValues, sb);\n sb.append(':');\n }\n\n if (userInfo != null || host != null || port != null) {\n sb.append(\"//\");\n\n if (userInfo != null && userInfo.length() > 0) {\n offset = createURIComponent(UriComponent.Type.USER_INFO, userInfo, values,\n offset, encode, mapValues, sb);\n sb.append('@');\n }\n\n if (host != null) {\n // TODO check IPv6 address\n offset = createURIComponent(UriComponent.Type.HOST, host, values,\n offset, encode, mapValues, sb);\n }\n\n if (port != null && port.length() > 0) {\n sb.append(':');\n offset = createURIComponent(UriComponent.Type.PORT, port, values,\n offset, false, mapValues, sb);\n }\n } else if (authority != null) {\n sb.append(\"//\");\n \n offset = createURIComponent(UriComponent.Type.AUTHORITY, authority, values,\n offset, encode, mapValues, sb);\n }\n\n if (path != null)\n offset = createURIComponent(UriComponent.Type.PATH, path, values,\n offset, encode, mapValues, sb);\n\n if (query != null && query.length() > 0) {\n sb.append('?');\n offset = createURIComponent(UriComponent.Type.QUERY_PARAM, query, values,\n offset, encode, mapValues, sb);\n }\n\n if (fragment != null && fragment.length() > 0) {\n sb.append('#');\n offset = createURIComponent(UriComponent.Type.FRAGMENT, fragment, values,\n offset, encode, mapValues, sb);\n }\n return sb.toString();\n }\n\n private static int createURIComponent(final UriComponent.Type t, \n String template,\n final String[] values, final int offset,\n final boolean encode, \n final Map mapValues,\n final StringBuilder b) {\n if (template.indexOf('{') == -1) {\n b.append(template);\n return offset;\n }\n\n // Find all template variables\n template = new UriTemplateParser(template).getNormalizedTemplate();\n final Matcher m = TEMPLATE_NAMES_PATTERN.matcher(template);\n int v = offset;\n int i = 0;\n while(m.find()) {\n b.append(template, i, m.start());\n final String tVariable = m.group(1);\n // Check if a template variable has already occurred\n // If so use the value to ensure that two or more declarations of \n // a template variable have the same value\n String tValue = mapValues.get(tVariable);\n if (tValue != null) {\n b.append(tValue);\n } else if (v < values.length) {\n tValue = values[v++];\n if (tValue != null) {\n if (encode)\n tValue = UriComponent.encode(tValue, t);\n else\n tValue = UriComponent.contextualEncode(tValue, t);\n mapValues.put(tVariable, tValue);\n b.append(tValue);\n } else {\n throw templateVariableHasNoValue(tVariable);\n }\n } else {\n throw templateVariableHasNoValue(tVariable);\n }\n i = m.end();\n }\n b.append(template, i, template.length());\n return v;\n }\n\n private static IllegalArgumentException templateVariableHasNoValue(String tVariable) {\n return new IllegalArgumentException(\"The template variable, \" +\n tVariable + \", has no value\");\n }\n}\n", "file_name": "UriTemplate.java", "human_label": "Return true if the given name is a member variable of this template,otherwise return false.", "level": "class_runnable", "lineno": "287", "name": "isTemplateVariablePresent", "oracle_context": "{ \"apis\" : \"[equals]\", \"classes\" : \"[]\", \"vars\" : \"[templateVariables]\" }", "package": "org.atmosphere.util.uri", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767071a6d9265ec017962", "all_context": "{ \"class_level\" : \"import net.hasor.utils.BeanUtils;\\nimport java.beans.BeanInfo;\\nimport java.beans.IntrospectionException;\\nimport java.beans.Introspector;\\nimport java.beans.PropertyDescriptor;\\nimport java.lang.reflect.Constructor;\\nimport java.lang.reflect.InvocationTargetException;\\nimport java.lang.reflect.Method;\\nimport java.util.*;\\nObject bean;\\nMap readMethods;\\nMap writeMethods;\\nMap> types;\\nObject[] NULL_ARGUMENTS;\\nMap,Transformer> typeTransformers;\\nBeanMap owner;\\ncreateTypeTransformers();\\nBeanMap();\\nBeanMap(Object bean);\\nclone();\\nputAllWriteable(BeanMap map);\\nclear();\\ncontainsKey(Object name);\\ncontainsValue(Object value);\\nget(Object name);\\nput(String name,Object value);\\nsize();\\nkeySet();\\nentrySet();\\niterator();\\nvalues();\\ngetType(String name);\\nkeyIterator();\\nvalueIterator();\\nhasNext();\\nnext();\\nremove();\\nentryIterator();\\ngetBean();\\nsetBean(Object newBean);\\ngetReadMethod(String name);\\ngetWriteMethod(String name);\\ngetReadMethod(Object name);\\ngetWriteMethod(Object name);\\nreinitialise();\\ninitialise();\\nfirePropertyChange(Object key,Object oldValue,Object newValue);\\nEntry(BeanMap owner,String key,Object value);\\nsetValue(Object value);\\ncreateWriteMethodArguments(Method method,Object value);\\nconvertType(Class newType,Object value);\\ngetTypeTransformer(Class aType);\\nlogInfo(Exception ex);\\nlogWarn(Exception ex);\\ntoString();\\n\", \"repo_level\" : \"public interface BeanUtils {static Object getDefaultValue(Class returnType);\\nstatic Object[] getDefaultValue(Class[] paramArray);\\nstatic Object invokeMethod(Object target,String methodName,Object objects);\\nstatic List findALLFields(Class target);\\nstatic List findALLMethods(Class target);\\nstatic List getFields(Class type);\\nstatic List getMethods(Class type);\\nstatic Field getField(String fieldName,Class type);\\nstatic Method getMethod(Class atClass,String name,Class[] paramType);\\nstatic List getPropertiesAndFields(Class target);\\nstatic List getProperties(Class target);\\nstatic PropertyDescriptor[] getPropertyDescriptors(Class defineType);\\nstatic Method getReadMethod(String property,Class target);\\nstatic Method getWriteMethod(String property,Class target);\\nstatic boolean hasProperty(String propertyName,Class target);\\nstatic boolean hasField(String propertyName,Class target);\\nstatic boolean hasPropertyOrField(String name,Class target);\\nstatic boolean canReadProperty(String propertyName,Class target);\\nstatic boolean canReadPropertyOrField(String propertyName,Class target);\\nstatic boolean canWriteProperty(String propertyName,Class target);\\nstatic boolean canWriteField(String propertyName,Class target);\\nstatic boolean canWritePropertyOrField(String propertyName,Class target);\\nstatic boolean writeProperty(Object object,String attName,Object value);\\nstatic boolean writeField(Object object,String fieldName,Object value);\\nstatic boolean writePropertyOrField(Object object,String attName,Object value);\\nstatic Object readProperty(Object object,String attName);\\nstatic Object readField(Object object,String fieldName);\\nstatic Object readPropertyOrField(Object object,String attName);\\nstatic Class getPropertyType(Class defineType,String attName);\\nstatic Class getFieldType(Class defineType,String attName);\\nstatic Class getPropertyOrFieldType(Class defineType,String attName);\\nstatic void copyProperties(Object dest,Object orig);\\nstatic void copyProperty(Object dest,Object orig,String propertyName);\\n }\\n\" }", "class_name": "BeanMap", "code": "public void putAllWriteable(BeanMap map){\n Iterator readableKeys=map.readMethods.keySet().iterator();\n while (readableKeys.hasNext()) {\n String key=readableKeys.next();\n if (getWriteMethod(key) != null) {\n this.put(key,map.get(key));\n }\n }\n}\n", "docstring": "/** \n * Puts all of the writable properties from the given BeanMap into this BeanMap. Read-only and Write-only properties will be ignored.\n * @param map the BeanMap whose properties to put\n */\n", "end_lineno": "166", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.ref;\nimport net.hasor.utils.BeanUtils;\n\nimport java.beans.BeanInfo;\nimport java.beans.IntrospectionException;\nimport java.beans.Introspector;\nimport java.beans.PropertyDescriptor;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.*;\n\n/**\n * An implementation of Map for JavaBeans which uses introspection to\n * get and put properties in the bean.\n *

      \n * If an exception occurs during attempts to get or set a property then the\n * property is considered non existent in the Map\n *\n * @version $Revision: 812176 $ $Date: 2009-09-07 15:59:25 +0100 (Mon, 07 Sep 2009) $\n *\n * @author James Strachan\n * @author Stephen Colebourne\n */\npublic class BeanMap extends AbstractMap implements Cloneable {\n private transient Object bean;\n private transient Map readMethods = new LinkedHashMap<>();\n private transient Map writeMethods = new LinkedHashMap<>();\n private transient Map> types = new LinkedHashMap<>();\n /** An empty array. Used to invoke accessors via reflection. */\n public static final Object[] NULL_ARGUMENTS = {};\n /**\n * Maps primitive Class types to transformers. The transformer\n * transform strings into the appropriate primitive wrapper.\n * N.B. private & unmodifiable replacement for the (public & static) defaultTransformers instance.\n */\n private static final Map, Transformer> typeTransformers = Collections.unmodifiableMap(createTypeTransformers());\n\n private static Map, Transformer> createTypeTransformers() {\n Map, Transformer> defaultTransformers = new HashMap<>();\n defaultTransformers.put(Boolean.TYPE, input -> Boolean.valueOf(input.toString()));\n defaultTransformers.put(Character.TYPE, input -> input.toString().charAt(0));\n defaultTransformers.put(Byte.TYPE, input -> Byte.valueOf(input.toString()));\n defaultTransformers.put(Short.TYPE, input -> Short.valueOf(input.toString()));\n defaultTransformers.put(Integer.TYPE, input -> Integer.valueOf(input.toString()));\n defaultTransformers.put(Long.TYPE, input -> Long.valueOf(input.toString()));\n defaultTransformers.put(Float.TYPE, input -> Float.valueOf(input.toString()));\n defaultTransformers.put(Double.TYPE, input -> Double.valueOf(input.toString()));\n return defaultTransformers;\n }\n // Constructors\n //-------------------------------------------------------------------------\n\n /** Constructs a new empty BeanMap. */\n public BeanMap() {\n }\n\n /**\n * Constructs a new BeanMap that operates on the specified bean.\n * If the given bean is null, then this map will be empty.\n * @param bean the bean for this map to operate on\n */\n public BeanMap(Object bean) {\n this.bean = bean;\n initialise();\n }\n // Map interface\n //-------------------------------------------------------------------------\n\n /**\n * Renders a string representation of this object.\n * @return a String representation of this object\n */\n public String toString() {\n return \"BeanMap<\" + bean + \">\";\n }\n\n /**\n * Clone this bean map using the following process: \n *

        \n *
      • If there is no underlying bean, return a cloned BeanMap without a bean.\n *\n *
      • Since there is an underlying bean, try to instantiate a new bean of\n * the same type using Class.newInstance().\n *\n *
      • If the instantiation fails, throw a CloneNotSupportedException\n *\n *
      • Clone the bean map and set the newly instantiated bean as the\n * underlying bean for the bean map.\n *\n *
      • Copy each property that is both readable and writable from the\n * existing object to a cloned bean map. \n *\n *
      • If anything fails along the way, throw a CloneNotSupportedException.\n *
          \n *\n * @return a cloned instance of this bean map\n * @throws CloneNotSupportedException if the underlying bean cannot be cloned\n */\n public Object clone() throws CloneNotSupportedException {\n BeanMap newMap = (BeanMap) super.clone();\n if (bean == null) {\n // no bean, just an empty bean map at the moment. return a newly\n // cloned and empty bean map.\n return newMap;\n }\n Object newBean = null;\n Class beanClass = bean.getClass(); // Cannot throw Exception\n try {\n newBean = beanClass.newInstance();\n } catch (Exception e) {\n // unable to instantiate\n throw new CloneNotSupportedException(\"Unable to instantiate the underlying bean \\\"\" + beanClass.getName() + \"\\\": \" + e);\n }\n try {\n newMap.setBean(newBean);\n } catch (Exception exception) {\n throw new CloneNotSupportedException(\"Unable to set bean in the cloned bean map: \" + exception);\n }\n try {\n // copy only properties that are readable and writable. If its\n // not readable, we can't get the value from the old map. If\n // its not writable, we can't write a value into the new map.\n Iterator readableKeys = readMethods.keySet().iterator();\n while (readableKeys.hasNext()) {\n String key = readableKeys.next();\n if (getWriteMethod(key) != null) {\n newMap.put(key, get(key));\n }\n }\n } catch (Exception exception) {\n throw new CloneNotSupportedException(\"Unable to copy bean values to cloned bean map: \" + exception);\n }\n return newMap;\n }\n\n /**\n * Puts all of the writable properties from the given BeanMap into this\n * BeanMap. Read-only and Write-only properties will be ignored.\n * @param map the BeanMap whose properties to put\n */\n public void putAllWriteable(BeanMap map) {\n Iterator readableKeys = map.readMethods.keySet().iterator();\n while (readableKeys.hasNext()) {\n String key = readableKeys.next();\n if (getWriteMethod(key) != null) {\n this.put(key, map.get(key));\n }\n }\n }\n\n /**\n * This method reinitializes the bean map to have default values for the\n * bean's properties. This is accomplished by constructing a new instance\n * of the bean which the map uses as its underlying data source.\n * This behavior for clear() differs from the Map contract in that\n * the mappings are not actually removed from the map (the mappings for a BeanMap are fixed).\n */\n public void clear() {\n if (bean == null) {\n return;\n }\n Class beanClass = null;\n try {\n beanClass = bean.getClass();\n bean = beanClass.newInstance();\n } catch (Exception e) {\n throw new UnsupportedOperationException(\"Could not create new instance of class: \" + beanClass);\n }\n }\n\n /**\n * Returns true if the bean defines a property with the given name.

          \n * The given name must be a String; if not, this method\n * returns false. This method will also return false if the bean\n * does not define a property with that name.

          \n * Write-only properties will not be matched as the test operates against property read methods.\n *\n * @param name the name of the property to check\n * @return false if the given name is null or is not a String;\n * false if the bean does not define a property with that name; or\n * true if the bean does define a property with that name\n */\n public boolean containsKey(Object name) {\n Method method = getReadMethod(name);\n return method != null;\n }\n\n /**\n * Returns true if the bean defines a property whose current value is the given object.\n * @param value the value to check\n * @return false true if the bean has at least one property whose current value is that object, false otherwise\n */\n public boolean containsValue(Object value) {\n // use default implementation\n return super.containsValue(value);\n }\n\n /**\n * Returns the value of the bean's property with the given name.

          \n * The given name must be a {@link String} and must not be \n * null; otherwise, this method returns null.\n * If the bean defines a property with the given name, the value of\n * that property is returned. Otherwise, null is returned.

          \n * Write-only properties will not be matched as the test operates against property read methods.\n *\n * @param name the name of the property whose value to return\n * @return the value of the property with that name\n */\n public Object get(Object name) {\n if (bean != null) {\n Method method = getReadMethod(name);\n if (method != null) {\n try {\n return method.invoke(bean, NULL_ARGUMENTS);\n } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NullPointerException e) {\n logWarn(e);\n }\n }\n }\n return null;\n }\n\n /**\n * Sets the bean property with the given name to the given value.\n * @param name the name of the property to set\n * @param value the value to set that property to\n * @return the previous value of that property\n * @throws IllegalArgumentException if the given name is null; \n * if the given name is not a {@link String}; if the bean doesn't\n * define a property with that name; or if the bean property with that name is read-only\n * @throws ClassCastException if an error occurs creating the method args\n */\n public Object put(String name, Object value) throws IllegalArgumentException, ClassCastException {\n if (bean != null) {\n Object oldValue = get(name);\n Method method = getWriteMethod(name);\n if (method == null) {\n throw new IllegalArgumentException(\"The bean of type: \" + bean.getClass().getName() + \" has no property called: \" + name);\n }\n try {\n Object[] arguments = createWriteMethodArguments(method, value);\n method.invoke(bean, arguments);\n Object newValue = get(name);\n firePropertyChange(name, oldValue, newValue);\n } catch (InvocationTargetException | IllegalAccessException e) {\n logInfo(e);\n throw new IllegalArgumentException(e.getMessage());\n }\n return oldValue;\n }\n return null;\n }\n\n /**\n * Returns the number of properties defined by the bean.\n * @return the number of properties defined by the bean\n */\n public int size() {\n return readMethods.size();\n }\n\n /**\n * Get the keys for this BeanMap.

          \n * Write-only properties are not included in the returned set of\n * property names, although it is possible to set their value and to get their type.\n * @return BeanMap keys. The Set returned by this method is not modifiable.\n */\n public Set keySet() {\n return Collections.unmodifiableSet(readMethods.keySet());\n }\n\n /**\n * Gets a Set of MapEntry objects that are the mappings for this BeanMap.

          \n * Each MapEntry can be set but not removed.\n * @return the unmodifiable set of mappings\n */\n public Set> entrySet() {\n return Collections.unmodifiableSet(new AbstractSet>() {\n public Iterator> iterator() {\n return entryIterator();\n }\n\n public int size() {\n return BeanMap.this.readMethods.size();\n }\n });\n }\n\n /**\n * Returns the values for the BeanMap.\n * @return values for the BeanMap. The returned collection is not modifiable.\n */\n public Collection values() {\n ArrayList answer = new ArrayList<>(readMethods.size());\n for (Iterator iter = valueIterator(); iter.hasNext(); ) {\n answer.add(iter.next());\n }\n return Collections.unmodifiableList(answer);\n }\n // Helper methods\n //-------------------------------------------------------------------------\n\n /**\n * Returns the type of the property with the given name.\n * @param name the name of the property\n * @return the type of the property, or null if no such property exists\n */\n public Class getType(String name) {\n return types.get(name);\n }\n\n /**\n * Convenience method for getting an iterator over the keys.

          \n * Write-only properties will not be returned in the iterator.\n * @return an iterator over the keys\n */\n public Iterator keyIterator() {\n return readMethods.keySet().iterator();\n }\n\n /**\n * Convenience method for getting an iterator over the values.\n * @return an iterator over the values\n */\n public Iterator valueIterator() {\n final Iterator iter = keyIterator();\n return new Iterator() {\n public boolean hasNext() {\n return iter.hasNext();\n }\n\n public Object next() {\n Object key = iter.next();\n return get(key);\n }\n\n public void remove() {\n throw new UnsupportedOperationException(\"remove() not supported for BeanMap\");\n }\n };\n }\n\n /**\n * Convenience method for getting an iterator over the entries.\n * @return an iterator over the entries\n */\n public Iterator> entryIterator() {\n final Iterator iter = keyIterator();\n return new Iterator>() {\n public boolean hasNext() {\n return iter.hasNext();\n }\n\n public Map.Entry next() {\n String key = iter.next();\n Object value = get(key);\n return new Entry(BeanMap.this, key, value);\n }\n\n public void remove() {\n throw new UnsupportedOperationException(\"remove() not supported for BeanMap\");\n }\n };\n }\n // Properties\n //-------------------------------------------------------------------------\n\n /**\n * Returns the bean currently being operated on. The return value may be null if this map is empty.\n * @return the bean being operated on by this map\n */\n public Object getBean() {\n return bean;\n }\n\n /**\n * Sets the bean to be operated on by this map. The given value may be null, in which case this map will be empty.\n * @param newBean the new bean to operate on\n */\n public void setBean(Object newBean) {\n bean = newBean;\n reinitialise();\n }\n\n /**\n * Returns the accessor for the property with the given name.\n * @param name the name of the property \n * @return the accessor method for the property, or null\n */\n public Method getReadMethod(String name) {\n return readMethods.get(name);\n }\n\n /**\n * Returns the mutator for the property with the given name.\n * @param name the name of the property\n * @return the mutator method for the property, or null\n */\n public Method getWriteMethod(String name) {\n return writeMethods.get(name);\n }\n // Implementation methods\n //-------------------------------------------------------------------------\n\n /**\n * Returns the accessor for the property with the given name.\n * @param name the name of the property \n * @return null if the name is null; null if the name is not a {@link String};\n * null if no such property exists; or the accessor method for that property\n */\n protected Method getReadMethod(Object name) {\n return readMethods.get(name);\n }\n\n /**\n * Returns the mutator for the property with the given name.\n * @param name the name of the \n * @return null if the name is null; null if the name is not a {@link String};\n * null if no such property exists; null if the property is read-only; or the mutator method for that property\n */\n protected Method getWriteMethod(Object name) {\n return writeMethods.get(name);\n }\n\n /** Reinitializes this bean. Called during {@link #setBean(Object)}. Does introspection to find properties. */\n protected void reinitialise() {\n readMethods.clear();\n writeMethods.clear();\n types.clear();\n initialise();\n }\n\n private void initialise() {\n if (getBean() == null) {\n return;\n }\n Class beanClass = getBean().getClass();\n try {\n Map pd = new LinkedHashMap<>();\n // 为了有序\n BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);\n PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();\n BeanUtils.getProperties(beanClass).forEach(s -> pd.put(s, null));\n if (propertyDescriptors != null) {\n for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {\n pd.put(propertyDescriptor.getName(), propertyDescriptor);\n }\n }\n // 为了有序\n pd.forEach((name, propertyDescriptor) -> {\n if (propertyDescriptor == null) {\n return;\n }\n Method readMethod = propertyDescriptor.getReadMethod();\n Method writeMethod = propertyDescriptor.getWriteMethod();\n Class aType = propertyDescriptor.getPropertyType();\n if (readMethod != null) {\n readMethods.put(name, readMethod);\n }\n if (writeMethod != null) {\n writeMethods.put(name, writeMethod);\n }\n types.put(name, aType);\n });\n } catch (IntrospectionException e) {\n logWarn(e);\n }\n }\n\n /**\n * Called during a successful {@link #put(String, Object)} operation.\n * Default implementation does nothing. Override to be notified of\n * property changes in the bean caused by this map.\n *\n * @param key the name of the property that changed\n * @param oldValue the old value for that property\n * @param newValue the new value for that property\n */\n protected void firePropertyChange(Object key, Object oldValue, Object newValue) {\n }\n // Implementation classes\n //-------------------------------------------------------------------------\n\n /** Map entry used by {@link BeanMap}. */\n protected static class Entry extends AbstractMapEntry {\n private BeanMap owner;\n\n /**\n * Constructs a new Entry.\n * @param owner the BeanMap this entry belongs to\n * @param key the key for this entry\n * @param value the value for this entry\n */\n protected Entry(BeanMap owner, String key, Object value) {\n super(key, value);\n this.owner = owner;\n }\n\n /**\n * Sets the value.\n * @param value the new value for the entry\n * @return the old value for the entry\n */\n public Object setValue(Object value) {\n String key = getKey();\n Object oldValue = owner.get(key);\n owner.put(key, value);\n super.value = owner.get(key);\n return oldValue;\n }\n }\n\n /**\n * Creates an array of parameters to pass to the given mutator method.\n * If the given object is not the right type to pass to the method \n * directly, it will be converted using {@link #convertType(Class, Object)}.\n *\n * @param method the mutator method\n * @param value the value to pass to the mutator method\n * @return an array containing one object that is either the given value or a transformed value\n * @throws IllegalAccessException if {@link #convertType(Class, Object)} raises it\n * @throws IllegalArgumentException if any other exception is raised by {@link #convertType(Class, Object)}\n * @throws ClassCastException if an error occurs creating the method args\n */\n protected Object[] createWriteMethodArguments(Method method, Object value) throws IllegalAccessException, ClassCastException {\n try {\n if (value != null) {\n Class[] types = method.getParameterTypes();\n if (types != null && types.length > 0) {\n Class paramType = types[0];\n if (!paramType.isAssignableFrom(value.getClass())) {\n value = convertType(paramType, value);\n }\n }\n }\n Object[] answer = { value };\n return answer;\n } catch (InvocationTargetException | InstantiationException e) {\n logInfo(e);\n throw new IllegalArgumentException(e.getMessage());\n }\n }\n\n /**\n * Converts the given value to the given type. First, reflection is\n * is used to find a public constructor declared by the given class \n * that takes one argument, which must be the precise type of the \n * given value. If such a constructor is found, a new object is\n * created by passing the given value to that constructor, and the\n * newly constructed object is returned.

          \n *\n * If no such constructor exists, and the given type is a primitive\n * type, then the given value is converted to a string using its \n * {@link Object#toString() toString()} method, and that string is\n * parsed into the correct primitive type using, for instance, \n * {@link Integer#valueOf(String)} to convert the string into an\n * int.

          \n *\n * If no special constructor exists and the given type is not a \n * primitive type, this method returns the original value.\n *\n * @param newType the type to convert the value to\n * @param value the value to convert\n * @return the converted value\n * @throws NumberFormatException if newType is a primitive type, and \n * the string representation of the given value cannot be converted to that type\n * @throws InstantiationException if the constructor found with \n * reflection raises it\n * @throws InvocationTargetException if the constructor found with\n * reflection raises it\n * @throws IllegalAccessException never\n * @throws IllegalArgumentException never\n */\n protected Object convertType(Class newType, Object value) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {\n // try call constructor\n Class[] types = { value.getClass() };\n try {\n Constructor constructor = newType.getConstructor(types);\n Object[] arguments = { value };\n return constructor.newInstance(arguments);\n } catch (NoSuchMethodException e) {\n // try using the transformers\n Transformer transformer = getTypeTransformer(newType);\n if (transformer != null) {\n return transformer.transform(value);\n }\n return value;\n }\n }\n\n /**\n * Returns a transformer for the given primitive type.\n *\n * @param aType the primitive type whose transformer to return\n * @return a transformer that will convert strings into that type,\n * or null if the given type is not a primitive type\n */\n protected Transformer getTypeTransformer(Class aType) {\n return typeTransformers.get(aType);\n }\n\n /**\n * Logs the given exception to System.out. Used to display\n * warnings while accessing/mutating the bean.\n *\n * @param ex the exception to log\n */\n protected void logInfo(Exception ex) {\n // Deliberately do not use LOG4J or Commons Logging to avoid dependencies\n System.out.println(\"INFO: Exception: \" + ex);\n }\n\n /**\n * Logs the given exception to System.err. Used to display\n * errors while accessing/mutating the bean.\n *\n * @param ex the exception to log\n */\n protected void logWarn(Exception ex) {\n // Deliberately do not use LOG4J or Commons Logging to avoid dependencies\n System.out.println(\"WARN: Exception: \" + ex);\n ex.printStackTrace();\n }\n}\n", "file_name": "BeanMap.java", "human_label": "Put all of the both readable and writable methods from the given map to this map.", "level": "class_runnable", "lineno": "153", "name": "putAllWriteable", "oracle_context": "{ \"apis\" : \"[iterator, keySet, hasNext, next, getWriteMethod, put, get, BeanMap]\", \"classes\" : \"[Iterator, String]\", \"vars\" : \"[readMethods]\" }", "package": "net.hasor.utils.ref", "project": "hasor-master" }, { "_id": "6367670a1a6d9265ec0179d9", "all_context": "{ \"class_level\" : \"import java.io.IOException;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.List;\\nimport java.util.Locale;\\nString EMPTY;\\nint INDEX_NOT_FOUND;\\nint PAD_LIMIT;\\nchar[] escapes;\\nStringUtils();\\nisNotEmpty(String str);\\nisBlank(String str);\\nisNotBlank(String str);\\ntrim(String str);\\ntrimToNull(String str);\\ntrimToEmpty(String str);\\nstrip(String str);\\nstripToNull(String str);\\nstripToEmpty(String str);\\nstrip(String str,String stripChars);\\nstripStart(String str,String stripChars);\\nstripEnd(String str,String stripChars);\\nstripAll(String[] strs);\\nstripAll(String[] strs,String stripChars);\\nequals(String str1,String str2);\\nequalsIgnoreCase(String str1,String str2);\\nindexOf(String str,char searchChar);\\nindexOf(String str,char searchChar,int startPos);\\nindexOf(String str,String searchStr);\\nordinalIndexOf(String str,String searchStr,int ordinal);\\nordinalIndexOf(String str,String searchStr,int ordinal,boolean lastIndex);\\nindexOf(String str,String searchStr,int startPos);\\nindexOfIgnoreCase(String str,String searchStr);\\nindexOfIgnoreCase(String str,String searchStr,int startPos);\\nlastIndexOf(String str,char searchChar);\\nlastIndexOf(String str,char searchChar,int startPos);\\nlastIndexOf(String str,String searchStr);\\nlastOrdinalIndexOf(String str,String searchStr,int ordinal);\\nlastIndexOf(String str,String searchStr,int startPos);\\nlastIndexOfIgnoreCase(String str,String searchStr);\\nlastIndexOfIgnoreCase(String str,String searchStr,int startPos);\\ncontains(String str,char searchChar);\\ncontains(String str,String searchStr);\\ncontainsIgnoreCase(String str,String searchStr);\\nindexOfAny(String str,char[] searchChars);\\nindexOfAny(String str,String searchChars);\\ncontainsAny(String str,char[] searchChars);\\ncontainsAny(String str,String searchChars);\\nindexOfAnyBut(String str,char[] searchChars);\\nindexOfAnyBut(String str,String searchChars);\\ncontainsOnly(String str,char[] valid);\\ncontainsOnly(String str,String validChars);\\ncontainsNone(String str,char[] searchChars);\\ncontainsNone(String str,String invalidChars);\\nindexOfAny(String str,String[] searchStrs);\\nlastIndexOfAny(String str,String[] searchStrs);\\nsubstring(String str,int start);\\nsubstring(String str,int start,int end);\\nleft(String str,int len);\\nright(String str,int len);\\nmid(String str,int pos,int len);\\nsubstringBefore(String str,String separator);\\nsubstringAfter(String str,String separator);\\nsubstringBeforeLast(String str,String separator);\\nsubstringAfterLast(String str,String separator);\\nsubstringBetween(String str,String tag);\\nsubstringBetween(String str,String open,String close);\\nsubstringsBetween(String str,String open,String close);\\nsplitKeep(String str,char separatorChar);\\nsplitKeep(String str,String separatorStr);\\nsplit(String str);\\nsplit(String str,char separatorChar);\\nsplit(String str,String separatorChars);\\nsplit(String str,String separatorChars,int max);\\nsplitByWholeSeparator(String str,String separator);\\nsplitByWholeSeparator(String str,String separator,int max);\\nsplitByWholeSeparatorPreserveAllTokens(String str,String separator);\\nsplitByWholeSeparatorPreserveAllTokens(String str,String separator,int max);\\nsplitByWholeSeparatorWorker(String str,String separator,int max,boolean preserveAllTokens);\\nsplitPreserveAllTokens(String str);\\nsplitPreserveAllTokens(String str,char separatorChar);\\nsplitWorker(String str,char separatorChar,boolean preserveAllTokens);\\nsplitPreserveAllTokens(String str,String separatorChars);\\nsplitPreserveAllTokens(String str,String separatorChars,int max);\\nsplitWorker(String str,String separatorChars,int max,boolean preserveAllTokens);\\nsplitByCharacterType(String str);\\nsplitByCharacterTypeCamelCase(String str);\\nsplitByCharacterType(String str,boolean camelCase);\\njoin(Object[] array);\\njoin(Object[] array,char separator);\\njoin(Object[] array,char separator,int startIndex,int endIndex);\\njoin(Object[] array,String separator);\\njoin(Object[] array,String separator,int startIndex,int endIndex);\\ndeleteWhitespace(String str);\\nremoveStart(String str,String remove);\\nremoveStartIgnoreCase(String str,String remove);\\nremoveEnd(String str,String remove);\\nremoveEndIgnoreCase(String str,String remove);\\nremove(String str,String remove);\\nremove(String str,char remove);\\nreplaceOnce(String text,String searchString,String replacement);\\nreplace(String text,String searchString,String replacement);\\nreplace(String text,String searchString,String replacement,int max);\\nreplaceEach(String text,String[] searchList,String[] replacementList);\\nreplaceEachRepeatedly(String text,String[] searchList,String[] replacementList);\\nreplaceEach(String text,String[] searchList,String[] replacementList,boolean repeat,int timeToLive);\\nreplaceChars(String str,char searchChar,char replaceChar);\\nreplaceChars(String str,String searchChars,String replaceChars);\\noverlay(String str,String overlay,int start,int end);\\nchomp(String str);\\nchomp(String str,String separator);\\nchop(String str);\\nrepeat(char character,int repeat);\\nrepeat(String str,int repeat);\\nrepeat(String str,String separator,int repeat);\\npadding(int repeat,char padChar);\\nrightPad(String str,int size);\\nrightPad(String str,int size,char padChar);\\nrightPad(String str,int size,String padStr);\\nleftPad(String str,int size);\\nleftPad(String str,int size,char padChar);\\nleftPad(String str,int size,String padStr);\\nlength(String str);\\ncenter(String str,int size);\\ncenter(String str,int size,char padChar);\\ncenter(String str,int size,String padStr);\\nupperCase(String str);\\nupperCase(String str,Locale locale);\\nlowerCase(String str);\\nlowerCase(String str,Locale locale);\\ncapitalize(String str);\\nuncapitalize(String str);\\nswapCase(String str);\\ncountMatches(String str,String sub);\\nisAlpha(String str);\\nisAlphaSpace(String str);\\nisAlphanumeric(String str);\\nisAlphanumericSpace(String str);\\nisAsciiPrintable(String str);\\nisNumeric(String str);\\nisNumericSpace(String str);\\nisWhitespace(String str);\\nisAllLowerCase(String str);\\nisAllUpperCase(String str);\\ndefaultString(String str);\\ndefaultString(String str,String defaultStr);\\ndefaultIfBlank(String str,String defaultStr);\\ndefaultIfEmpty(String str,String defaultStr);\\nreverse(String str);\\nreverseDelimited(String str,char separatorChar);\\nabbreviate(String str,int maxWidth);\\nabbreviate(String str,int offset,int maxWidth);\\nabbreviateMiddle(String str,String middle,int length);\\ndifference(String str1,String str2);\\nindexOfDifference(String str1,String str2);\\nindexOfDifference(String[] strs);\\ngetCommonPrefix(String[] strs);\\ngetLevenshteinDistance(String s,String t);\\nstartsWith(String str,String prefix);\\nstartsWithIgnoreCase(String str,String prefix);\\nstartsWith(String str,String prefix,boolean ignoreCase);\\nstartsWithAny(String string,String[] searchStrings);\\nendsWith(String str,String suffix);\\nendsWithIgnoreCase(String str,String suffix);\\nendsWith(String str,String suffix,boolean ignoreCase);\\nnormalizeSpace(String str);\\nendsWithAny(String string,String[] searchStrings);\\nfirstCharToUpperCase(String value);\\nfirstCharToLowerCase(String value);\\nequalsBlankIgnoreCase(String str1,String str2);\\nquote(String input);\\nquote(Appendable buffer,String input);\\ntoString(Object object);\\nisEmpty(String str);\\n\", \"repo_level\" : \"\" }", "class_name": "StringUtils", "code": "public static int length(final String str){\n return str == null ? 0 : str.length();\n}\n", "docstring": "/** \n * Gets a String's length or 0 if the String is null.\n * @param str a String or null\n * @return String length or 0 if the String is null.\n * @since 2.4\n */\n", "end_lineno": "4484", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Locale;\n\n/**\n *

          Operations on {@link String} that are\n * null safe.

          \n *\n *
            \n *
          • IsEmpty/IsBlank\n * - checks if a String contains text
          • \n *
          • Trim/Strip\n * - removes leading and trailing whitespace
          • \n *
          • Equals\n * - compares two strings null-safe
          • \n *
          • startsWith\n * - check if a String starts with a prefix null-safe
          • \n *
          • endsWith\n * - check if a String ends with a suffix null-safe
          • \n *
          • IndexOf/LastIndexOf/Contains\n * - null-safe index-of checks\n *
          • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut\n * - index-of any of a set of Strings
          • \n *
          • ContainsOnly/ContainsNone/ContainsAny\n * - does String contains only/none/any of these characters
          • \n *
          • Substring/Left/Right/Mid\n * - null-safe substring extractions
          • \n *
          • SubstringBefore/SubstringAfter/SubstringBetween\n * - substring extraction relative to other strings
          • \n *
          • Split/Join\n * - splits a String into an array of substrings and vice versa
          • \n *
          • Remove/Delete\n * - removes part of a String
          • \n *
          • Replace/Overlay\n * - Searches a String and replaces one String with another
          • \n *
          • Chomp/Chop\n * - removes the last part of a String
          • \n *
          • LeftPad/RightPad/Center/Repeat\n * - pads a String
          • \n *
          • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize\n * - changes the case of a String
          • \n *
          • CountMatches\n * - counts the number of occurrences of one String in another
          • \n *
          • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable\n * - checks the characters in a String
          • \n *
          • DefaultString\n * - protects against a null input String
          • \n *
          • Reverse/ReverseDelimited\n * - reverses a String
          • \n *
          • Abbreviate\n * - abbreviates a string using ellipsis
          • \n *
          • Difference\n * - compares Strings and reports on their differences
          • \n *
          • LevensteinDistance\n * - the number of changes needed to change one String into another
          • \n *
          \n *\n *

          The StringUtils class defines certain words related to\n * String handling.

          \n *\n *
            \n *
          • null - null
          • \n *
          • empty - a zero-length string (\"\")
          • \n *
          • space - the space character (' ', char 32)
          • \n *
          • whitespace - the characters defined by {@link Character#isWhitespace(char)}
          • \n *
          • trim - the characters <= 32 as in {@link String#trim()}
          • \n *
          \n *\n *

          StringUtils handles null input Strings quietly.\n * That is to say that a null input will return null.\n * Where a boolean or int is being returned\n * details vary by method.

          \n *\n *

          A side effect of the null handling is that a\n * NullPointerException should be considered a bug in\n * StringUtils (except for deprecated methods).

          \n *\n *

          Methods in this class give sample code to explain their operation.\n * The symbol * is used to indicate any input including null.

          \n *\n *

          #ThreadSafe#

          \n * @see String\n * @author Apache Software Foundation\n * @author Apache Jakarta Turbine\n * @author Jon S. Stevens\n * @author Daniel L. Rall\n * @author Greg Coladonato\n * @author Ed Korthof\n * @author Rand McNeely\n * @author Fredrik Westermarck\n * @author Holger Krauth\n * @author Alexander Day Chaffee\n * @author Henning P. Schmiedehausen\n * @author Arun Mammen Thomas\n * @author Gary Gregory\n * @author Phil Steitz\n * @author Al Chou\n * @author Michael Davey\n * @author Reuben Sivan\n * @author Chris Hyzer\n * @author Scott Johnson\n * @since 1.0\n * @version $Id: StringUtils.java 1058365 2011-01-13 00:04:49Z niallp $\n */\n//@Immutable\npublic class StringUtils {\n // Performance testing notes (JDK 1.4, Jul03, scolebourne)\n // Whitespace:\n // Character.isWhitespace() is faster than WHITESPACE.indexOf()\n // where WHITESPACE is a string of all whitespace characters\n //\n // Character access:\n // String.charAt(n) versus toCharArray(), then array[n]\n // String.charAt(n) is about 15% worse for a 10K string\n // They are about equal for a length 50 string\n // String.charAt(n) is about 4 times better for a length 3 string\n // String.charAt(n) is best bet overall\n //\n // Append:\n // String.concat about twice as fast as StringBuffer.append\n // (not sure who tested this)\n /**\n * The empty String \"\".\n * @since 2.0\n */\n public static final String EMPTY = \"\";\n /**\n * Represents a failed index search.\n * @since 2.1\n */\n public static final int INDEX_NOT_FOUND = -1;\n /**\n *

          The maximum size to which the padding constant(s) can expand.

          \n */\n private static final int PAD_LIMIT = 8192;\n\n /**\n *

          StringUtils instances should NOT be constructed in\n * standard programming. Instead, the class should be used as\n * StringUtils.trim(\" foo \");.

          \n *\n *

          This constructor is public to permit tools that require a JavaBean\n * instance to operate.

          \n */\n public StringUtils() {\n super();\n }\n // Empty checks\n //-----------------------------------------------------------------------\n\n /**\n *

          Checks if a String is empty (\"\") or null.

          \n *\n *
          \n     * StringUtils.isEmpty(null)      = true\n     * StringUtils.isEmpty(\"\")        = true\n     * StringUtils.isEmpty(\" \")       = false\n     * StringUtils.isEmpty(\"bob\")     = false\n     * StringUtils.isEmpty(\"  bob  \") = false\n     * 
          \n *\n *

          NOTE: This method changed in Lang version 2.0.\n * It no longer trims the String.\n * That functionality is available in isBlank().

          \n *\n * @param str the String to check, may be null\n * @return true if the String is empty or null\n */\n public static boolean isEmpty(final String str) {\n return str == null || str.length() == 0;\n }\n\n /**\n *

          Checks if a String is not empty (\"\") and not null.

          \n *\n *
          \n     * StringUtils.isNotEmpty(null)      = false\n     * StringUtils.isNotEmpty(\"\")        = false\n     * StringUtils.isNotEmpty(\" \")       = true\n     * StringUtils.isNotEmpty(\"bob\")     = true\n     * StringUtils.isNotEmpty(\"  bob  \") = true\n     * 
          \n *\n * @param str the String to check, may be null\n * @return true if the String is not empty and not null\n */\n public static boolean isNotEmpty(final String str) {\n return !StringUtils.isEmpty(str);\n }\n\n /**\n *

          Checks if a String is whitespace, empty (\"\") or null.

          \n *\n *
          \n     * StringUtils.isBlank(null)      = true\n     * StringUtils.isBlank(\"\")        = true\n     * StringUtils.isBlank(\" \")       = true\n     * StringUtils.isBlank(\"bob\")     = false\n     * StringUtils.isBlank(\"  bob  \") = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @return true if the String is null, empty or whitespace\n * @since 2.0\n */\n public static boolean isBlank(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return true;\n }\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i)) == false) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

          Checks if a String is not empty (\"\"), not null and not whitespace only.

          \n *\n *
          \n     * StringUtils.isNotBlank(null)      = false\n     * StringUtils.isNotBlank(\"\")        = false\n     * StringUtils.isNotBlank(\" \")       = false\n     * StringUtils.isNotBlank(\"bob\")     = true\n     * StringUtils.isNotBlank(\"  bob  \") = true\n     * 
          \n *\n * @param str the String to check, may be null\n * @return true if the String is\n * not empty and not null and not whitespace\n * @since 2.0\n */\n public static boolean isNotBlank(final String str) {\n return !StringUtils.isBlank(str);\n }\n // Trim\n //-----------------------------------------------------------------------\n\n /**\n *

          Removes control characters (char <= 32) from both\n * ends of this String, handling null by returning\n * null.

          \n *\n *

          The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #strip(String)}.

          \n *\n *

          To trim your choice of characters, use the\n * {@link #strip(String, String)} methods.

          \n *\n *
          \n     * StringUtils.trim(null)          = null\n     * StringUtils.trim(\"\")            = \"\"\n     * StringUtils.trim(\"     \")       = \"\"\n     * StringUtils.trim(\"abc\")         = \"abc\"\n     * StringUtils.trim(\"    abc    \") = \"abc\"\n     * 
          \n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed string, null if null String input\n */\n public static String trim(final String str) {\n return str == null ? null : str.trim();\n }\n\n /**\n *

          Removes control characters (char <= 32) from both\n * ends of this String returning null if the String is\n * empty (\"\") after the trim or if it is null.\n *\n *

          The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #stripToNull(String)}.

          \n *\n *
          \n     * StringUtils.trimToNull(null)          = null\n     * StringUtils.trimToNull(\"\")            = null\n     * StringUtils.trimToNull(\"     \")       = null\n     * StringUtils.trimToNull(\"abc\")         = \"abc\"\n     * StringUtils.trimToNull(\"    abc    \") = \"abc\"\n     * 
          \n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed String,\n * null if only chars <= 32, empty or null String input\n * @since 2.0\n */\n public static String trimToNull(final String str) {\n String ts = StringUtils.trim(str);\n return StringUtils.isEmpty(ts) ? null : ts;\n }\n\n /**\n *

          Removes control characters (char <= 32) from both\n * ends of this String returning an empty String (\"\") if the String\n * is empty (\"\") after the trim or if it is null.\n *\n *

          The String is trimmed using {@link String#trim()}.\n * Trim removes start and end characters <= 32.\n * To strip whitespace use {@link #stripToEmpty(String)}.

          \n *\n *
          \n     * StringUtils.trimToEmpty(null)          = \"\"\n     * StringUtils.trimToEmpty(\"\")            = \"\"\n     * StringUtils.trimToEmpty(\"     \")       = \"\"\n     * StringUtils.trimToEmpty(\"abc\")         = \"abc\"\n     * StringUtils.trimToEmpty(\"    abc    \") = \"abc\"\n     * 
          \n *\n * @param str the String to be trimmed, may be null\n * @return the trimmed String, or an empty String if null input\n * @since 2.0\n */\n public static String trimToEmpty(final String str) {\n return str == null ? StringUtils.EMPTY : str.trim();\n }\n // Stripping\n //-----------------------------------------------------------------------\n\n /**\n *

          Strips whitespace from the start and end of a String.

          \n *\n *

          This is similar to {@link #trim(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

          \n *\n *

          A null input String returns null.

          \n *\n *
          \n     * StringUtils.strip(null)     = null\n     * StringUtils.strip(\"\")       = \"\"\n     * StringUtils.strip(\"   \")    = \"\"\n     * StringUtils.strip(\"abc\")    = \"abc\"\n     * StringUtils.strip(\"  abc\")  = \"abc\"\n     * StringUtils.strip(\"abc  \")  = \"abc\"\n     * StringUtils.strip(\" abc \")  = \"abc\"\n     * StringUtils.strip(\" ab c \") = \"ab c\"\n     * 
          \n *\n * @param str the String to remove whitespace from, may be null\n * @return the stripped String, null if null String input\n */\n public static String strip(final String str) {\n return StringUtils.strip(str, null);\n }\n\n /**\n *

          Strips whitespace from the start and end of a String returning\n * null if the String is empty (\"\") after the strip.

          \n *\n *

          This is similar to {@link #trimToNull(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

          \n *\n *
          \n     * StringUtils.stripToNull(null)     = null\n     * StringUtils.stripToNull(\"\")       = null\n     * StringUtils.stripToNull(\"   \")    = null\n     * StringUtils.stripToNull(\"abc\")    = \"abc\"\n     * StringUtils.stripToNull(\"  abc\")  = \"abc\"\n     * StringUtils.stripToNull(\"abc  \")  = \"abc\"\n     * StringUtils.stripToNull(\" abc \")  = \"abc\"\n     * StringUtils.stripToNull(\" ab c \") = \"ab c\"\n     * 
          \n *\n * @param str the String to be stripped, may be null\n * @return the stripped String,\n * null if whitespace, empty or null String input\n * @since 2.0\n */\n public static String stripToNull(String str) {\n if (str == null) {\n return null;\n }\n str = StringUtils.strip(str, null);\n return str.length() == 0 ? null : str;\n }\n\n /**\n *

          Strips whitespace from the start and end of a String returning\n * an empty String if null input.

          \n *\n *

          This is similar to {@link #trimToEmpty(String)} but removes whitespace.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

          \n *\n *
          \n     * StringUtils.stripToEmpty(null)     = \"\"\n     * StringUtils.stripToEmpty(\"\")       = \"\"\n     * StringUtils.stripToEmpty(\"   \")    = \"\"\n     * StringUtils.stripToEmpty(\"abc\")    = \"abc\"\n     * StringUtils.stripToEmpty(\"  abc\")  = \"abc\"\n     * StringUtils.stripToEmpty(\"abc  \")  = \"abc\"\n     * StringUtils.stripToEmpty(\" abc \")  = \"abc\"\n     * StringUtils.stripToEmpty(\" ab c \") = \"ab c\"\n     * 
          \n *\n * @param str the String to be stripped, may be null\n * @return the trimmed String, or an empty String if null input\n * @since 2.0\n */\n public static String stripToEmpty(final String str) {\n return str == null ? StringUtils.EMPTY : StringUtils.strip(str, null);\n }\n\n /**\n *

          Strips any of a set of characters from the start and end of a String.\n * This is similar to {@link String#trim()} but allows the characters\n * to be stripped to be controlled.

          \n *\n *

          A null input String returns null.\n * An empty string (\"\") input returns the empty string.

          \n *\n *

          If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.\n * Alternatively use {@link #strip(String)}.

          \n *\n *
          \n     * StringUtils.strip(null, *)          = null\n     * StringUtils.strip(\"\", *)            = \"\"\n     * StringUtils.strip(\"abc\", null)      = \"abc\"\n     * StringUtils.strip(\"  abc\", null)    = \"abc\"\n     * StringUtils.strip(\"abc  \", null)    = \"abc\"\n     * StringUtils.strip(\" abc \", null)    = \"abc\"\n     * StringUtils.strip(\"  abcyx\", \"xyz\") = \"  abc\"\n     * 
          \n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String strip(String str, final String stripChars) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n str = StringUtils.stripStart(str, stripChars);\n return StringUtils.stripEnd(str, stripChars);\n }\n\n /**\n *

          Strips any of a set of characters from the start of a String.

          \n *\n *

          A null input String returns null.\n * An empty string (\"\") input returns the empty string.

          \n *\n *

          If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.

          \n *\n *
          \n     * StringUtils.stripStart(null, *)          = null\n     * StringUtils.stripStart(\"\", *)            = \"\"\n     * StringUtils.stripStart(\"abc\", \"\")        = \"abc\"\n     * StringUtils.stripStart(\"abc\", null)      = \"abc\"\n     * StringUtils.stripStart(\"  abc\", null)    = \"abc\"\n     * StringUtils.stripStart(\"abc  \", null)    = \"abc  \"\n     * StringUtils.stripStart(\" abc \", null)    = \"abc \"\n     * StringUtils.stripStart(\"yxabc  \", \"xyz\") = \"abc  \"\n     * 
          \n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String stripStart(final String str, final String stripChars) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n int start = 0;\n if (stripChars == null) {\n while (start != strLen && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n } else if (stripChars.length() == 0) {\n return str;\n } else {\n while (start != strLen && stripChars.indexOf(str.charAt(start)) != StringUtils.INDEX_NOT_FOUND) {\n start++;\n }\n }\n return str.substring(start);\n }\n\n /**\n *

          Strips any of a set of characters from the end of a String.

          \n *\n *

          A null input String returns null.\n * An empty string (\"\") input returns the empty string.

          \n *\n *

          If the stripChars String is null, whitespace is\n * stripped as defined by {@link Character#isWhitespace(char)}.

          \n *\n *
          \n     * StringUtils.stripEnd(null, *)          = null\n     * StringUtils.stripEnd(\"\", *)            = \"\"\n     * StringUtils.stripEnd(\"abc\", \"\")        = \"abc\"\n     * StringUtils.stripEnd(\"abc\", null)      = \"abc\"\n     * StringUtils.stripEnd(\"  abc\", null)    = \"  abc\"\n     * StringUtils.stripEnd(\"abc  \", null)    = \"abc\"\n     * StringUtils.stripEnd(\" abc \", null)    = \" abc\"\n     * StringUtils.stripEnd(\"  abcyx\", \"xyz\") = \"  abc\"\n     * StringUtils.stripEnd(\"120.00\", \".0\")   = \"12\"\n     * 
          \n *\n * @param str the String to remove characters from, may be null\n * @param stripChars the set of characters to remove, null treated as whitespace\n * @return the stripped String, null if null String input\n */\n public static String stripEnd(final String str, final String stripChars) {\n int end;\n if (str == null || (end = str.length()) == 0) {\n return str;\n }\n if (stripChars == null) {\n while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n } else if (stripChars.length() == 0) {\n return str;\n } else {\n while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != StringUtils.INDEX_NOT_FOUND) {\n end--;\n }\n }\n return str.substring(0, end);\n }\n // StripAll\n //-----------------------------------------------------------------------\n\n /**\n *

          Strips whitespace from the start and end of every String in an array.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

          \n *\n *

          A new array is returned each time, except for length zero.\n * A null array will return null.\n * An empty array will return itself.\n * A null array entry will be ignored.

          \n *\n *
          \n     * StringUtils.stripAll(null)             = null\n     * StringUtils.stripAll([])               = []\n     * StringUtils.stripAll([\"abc\", \"  abc\"]) = [\"abc\", \"abc\"]\n     * StringUtils.stripAll([\"abc  \", null])  = [\"abc\", null]\n     * 
          \n *\n * @param strs the array to remove whitespace from, may be null\n * @return the stripped Strings, null if null array input\n */\n public static String[] stripAll(final String[] strs) {\n return StringUtils.stripAll(strs, null);\n }\n\n /**\n *

          Strips any of a set of characters from the start and end of every\n * String in an array.

          \n * Whitespace is defined by {@link Character#isWhitespace(char)}.

          \n *\n *

          A new array is returned each time, except for length zero.\n * A null array will return null.\n * An empty array will return itself.\n * A null array entry will be ignored.\n * A null stripChars will strip whitespace as defined by\n * {@link Character#isWhitespace(char)}.

          \n *\n *
          \n     * StringUtils.stripAll(null, *)                = null\n     * StringUtils.stripAll([], *)                  = []\n     * StringUtils.stripAll([\"abc\", \"  abc\"], null) = [\"abc\", \"abc\"]\n     * StringUtils.stripAll([\"abc  \", null], null)  = [\"abc\", null]\n     * StringUtils.stripAll([\"abc  \", null], \"yz\")  = [\"abc  \", null]\n     * StringUtils.stripAll([\"yabcz\", null], \"yz\")  = [\"abc\", null]\n     * 
          \n *\n * @param strs the array to remove characters from, may be null\n * @param stripChars the characters to remove, null treated as whitespace\n * @return the stripped Strings, null if null array input\n */\n public static String[] stripAll(final String[] strs, final String stripChars) {\n int strsLen;\n if (strs == null || (strsLen = strs.length) == 0) {\n return strs;\n }\n String[] newArr = new String[strsLen];\n for (int i = 0; i < strsLen; i++) {\n newArr[i] = StringUtils.strip(strs[i], stripChars);\n }\n return newArr;\n }\n // Equals\n //-----------------------------------------------------------------------\n\n /**\n *

          Compares two Strings, returning true if they are equal.

          \n *\n *

          nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

          \n *\n *
          \n     * StringUtils.equals(null, null)   = true\n     * StringUtils.equals(null, \"abc\")  = false\n     * StringUtils.equals(\"abc\", null)  = false\n     * StringUtils.equals(\"abc\", \"abc\") = true\n     * StringUtils.equals(\"abc\", \"ABC\") = false\n     * 
          \n *\n * @see String#equals(Object)\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return true if the Strings are equal, case sensitive, or\n * both null\n */\n public static boolean equals(final String str1, final String str2) {\n return str1 == null ? str2 == null : str1.equals(str2);\n }\n\n /**\n *

          Compares two Strings, returning true if they are equal ignoring\n * the case.

          \n *\n *

          nulls are handled without exceptions. Two null\n * references are considered equal. Comparison is case insensitive.

          \n *\n *
          \n     * StringUtils.equalsIgnoreCase(null, null)   = true\n     * StringUtils.equalsIgnoreCase(null, \"abc\")  = false\n     * StringUtils.equalsIgnoreCase(\"abc\", null)  = false\n     * StringUtils.equalsIgnoreCase(\"abc\", \"abc\") = true\n     * StringUtils.equalsIgnoreCase(\"abc\", \"ABC\") = true\n     * 
          \n *\n * @see String#equalsIgnoreCase(String)\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return true if the Strings are equal, case insensitive, or\n * both null\n */\n public static boolean equalsIgnoreCase(final String str1, final String str2) {\n return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);\n }\n // IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(int)}.

          \n *\n *

          A null or empty (\"\") String will return INDEX_NOT_FOUND (-1).

          \n *\n *
          \n     * StringUtils.indexOf(null, *)         = -1\n     * StringUtils.indexOf(\"\", *)           = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'a') = 0\n     * StringUtils.indexOf(\"aabaabaa\", 'b') = 2\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return the first index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchChar);\n }\n\n /**\n *

          Finds the first index within a String from a start position,\n * handling null.\n * This method uses {@link String#indexOf(int, int)}.

          \n *\n *

          A null or empty (\"\") String will return (INDEX_NOT_FOUND) -1.\n * A negative start position is treated as zero.\n * A start position greater than the string length returns -1.

          \n *\n *
          \n     * StringUtils.indexOf(null, *, *)          = -1\n     * StringUtils.indexOf(\"\", *, *)            = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 0)  = 2\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 3)  = 5\n     * StringUtils.indexOf(\"aabaabaa\", 'b', 9)  = -1\n     * StringUtils.indexOf(\"aabaabaa\", 'b', -1) = 2\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final char searchChar, final int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchChar, startPos);\n }\n\n /**\n *

          Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

          \n *\n *

          A null String will return -1.

          \n *\n *
          \n     * StringUtils.indexOf(null, *)          = -1\n     * StringUtils.indexOf(*, null)          = -1\n     * StringUtils.indexOf(\"\", \"\")           = 0\n     * StringUtils.indexOf(\"\", *)            = -1 (except when * = \"\")\n     * StringUtils.indexOf(\"aabaabaa\", \"a\")  = 0\n     * StringUtils.indexOf(\"aabaabaa\", \"b\")  = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"ab\") = 1\n     * StringUtils.indexOf(\"aabaabaa\", \"\")   = 0\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr);\n }\n\n /**\n *

          Finds the n-th index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

          \n *\n *

          A null String will return -1.

          \n *\n *
          \n     * StringUtils.ordinalIndexOf(null, *, *)          = -1\n     * StringUtils.ordinalIndexOf(*, null, *)          = -1\n     * StringUtils.ordinalIndexOf(\"\", \"\", *)           = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"a\", 1)  = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"a\", 2)  = 1\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"b\", 1)  = 2\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"b\", 2)  = 5\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"ab\", 1) = 1\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"ab\", 2) = 4\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"\", 1)   = 0\n     * StringUtils.ordinalIndexOf(\"aabaabaa\", \"\", 2)   = 0\n     * 
          \n *\n *

          Note that 'head(String str, int n)' may be implemented as:

          \n *\n *
          \n     *   str.substring(0, lastOrdinalIndexOf(str, \"\\n\", n))\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th searchStr to find\n * @return the n-th index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n * @since 2.1\n */\n public static int ordinalIndexOf(final String str, final String searchStr, final int ordinal) {\n return StringUtils.ordinalIndexOf(str, searchStr, ordinal, false);\n }\n\n /**\n *

          Finds the n-th index within a String, handling null.\n * This method uses {@link String#indexOf(String)}.

          \n *\n *

          A null String will return -1.

          \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th searchStr to find\n * @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf()\n * @return the n-th index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n */\n // Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int)\n private static int ordinalIndexOf(final String str, final String searchStr, final int ordinal, final boolean lastIndex) {\n if (str == null || searchStr == null || ordinal <= 0) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return lastIndex ? str.length() : 0;\n }\n int found = 0;\n int index = lastIndex ? str.length() : StringUtils.INDEX_NOT_FOUND;\n do {\n if (lastIndex) {\n index = str.lastIndexOf(searchStr, index - 1);\n } else {\n index = str.indexOf(searchStr, index + 1);\n }\n if (index < 0) {\n return index;\n }\n found++;\n } while (found < ordinal);\n return index;\n }\n\n /**\n *

          Finds the first index within a String, handling null.\n * This method uses {@link String#indexOf(String, int)}.

          \n *\n *

          A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

          \n *\n *
          \n     * StringUtils.indexOf(null, *, *)          = -1\n     * StringUtils.indexOf(*, null, *)          = -1\n     * StringUtils.indexOf(\"\", \"\", 0)           = 0\n     * StringUtils.indexOf(\"\", *, 0)            = -1 (except when * = \"\")\n     * StringUtils.indexOf(\"aabaabaa\", \"a\", 0)  = 0\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 0)  = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"ab\", 0) = 1\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 3)  = 5\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", 9)  = -1\n     * StringUtils.indexOf(\"aabaabaa\", \"b\", -1) = 2\n     * StringUtils.indexOf(\"aabaabaa\", \"\", 2)   = 2\n     * StringUtils.indexOf(\"abc\", \"\", 9)        = 3\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int indexOf(final String str, final String searchStr, final int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n // JDK1.2/JDK1.3 have a bug, when startPos > str.length for \"\", hence\n if (searchStr.length() == 0 && startPos >= str.length()) {\n return str.length();\n }\n return str.indexOf(searchStr, startPos);\n }\n\n /**\n *

          Case in-sensitive find of the first index within a String.

          \n *\n *

          A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

          \n *\n *
          \n     * StringUtils.indexOfIgnoreCase(null, *)          = -1\n     * StringUtils.indexOfIgnoreCase(*, null)          = -1\n     * StringUtils.indexOfIgnoreCase(\"\", \"\")           = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"a\")  = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"b\")  = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"ab\") = 1\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int indexOfIgnoreCase(final String str, final String searchStr) {\n return StringUtils.indexOfIgnoreCase(str, searchStr, 0);\n }\n\n /**\n *

          Case in-sensitive find of the first index within a String\n * from the specified position.

          \n *\n *

          A null String will return -1.\n * A negative start position is treated as zero.\n * An empty (\"\") search String always matches.\n * A start position greater than the string length only matches\n * an empty search String.

          \n *\n *
          \n     * StringUtils.indexOfIgnoreCase(null, *, *)          = -1\n     * StringUtils.indexOfIgnoreCase(*, null, *)          = -1\n     * StringUtils.indexOfIgnoreCase(\"\", \"\", 0)           = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"A\", 0)  = 0\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 0)  = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"AB\", 0) = 1\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 3)  = 5\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", 9)  = -1\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"B\", -1) = 2\n     * StringUtils.indexOfIgnoreCase(\"aabaabaa\", \"\", 2)   = 2\n     * StringUtils.indexOfIgnoreCase(\"abc\", \"\", 9)        = 3\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int indexOfIgnoreCase(final String str, final String searchStr, int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (startPos < 0) {\n startPos = 0;\n }\n int endLimit = str.length() - searchStr.length() + 1;\n if (startPos > endLimit) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return startPos;\n }\n for (int i = startPos; i < endLimit; i++) {\n if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {\n return i;\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // LastIndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(int)}.

          \n *\n *

          A null or empty (\"\") String will return -1.

          \n *\n *
          \n     * StringUtils.lastIndexOf(null, *)         = -1\n     * StringUtils.lastIndexOf(\"\", *)           = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'a') = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b') = 5\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return the last index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar);\n }\n\n /**\n *

          Finds the last index within a String from a start position,\n * handling null.\n * This method uses {@link String#lastIndexOf(int, int)}.

          \n *\n *

          A null or empty (\"\") String will return -1.\n * A negative start position returns -1.\n * A start position greater than the string length searches the whole string.

          \n *\n *
          \n     * StringUtils.lastIndexOf(null, *, *)          = -1\n     * StringUtils.lastIndexOf(\"\", *,  *)           = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 8)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 4)  = 2\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 0)  = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', 9)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'b', -1) = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", 'a', 0)  = 0\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @param startPos the start position\n * @return the last index of the search character,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final char searchChar, final int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar, startPos);\n }\n\n /**\n *

          Finds the last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String)}.

          \n *\n *

          A null String will return -1.

          \n *\n *
          \n     * StringUtils.lastIndexOf(null, *)          = -1\n     * StringUtils.lastIndexOf(*, null)          = -1\n     * StringUtils.lastIndexOf(\"\", \"\")           = 0\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\")  = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\")  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"ab\") = 4\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"\")   = 8\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the last index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr);\n }\n\n /**\n *

          Finds the n-th last index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String)}.

          \n *\n *

          A null String will return -1.

          \n *\n *
          \n     * StringUtils.lastOrdinalIndexOf(null, *, *)          = -1\n     * StringUtils.lastOrdinalIndexOf(*, null, *)          = -1\n     * StringUtils.lastOrdinalIndexOf(\"\", \"\", *)           = 0\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"a\", 1)  = 7\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"a\", 2)  = 6\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"b\", 1)  = 5\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"b\", 2)  = 2\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"ab\", 1) = 4\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"ab\", 2) = 1\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"\", 1)   = 8\n     * StringUtils.lastOrdinalIndexOf(\"aabaabaa\", \"\", 2)   = 8\n     * 
          \n *\n *

          Note that 'tail(String str, int n)' may be implemented as:

          \n *\n *
          \n     *   str.substring(lastOrdinalIndexOf(str, \"\\n\", n) + 1)\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param ordinal the n-th last searchStr to find\n * @return the n-th last index of the search String,\n * -1 (INDEX_NOT_FOUND) if no match or null string input\n * @since 2.5\n */\n public static int lastOrdinalIndexOf(final String str, final String searchStr, final int ordinal) {\n return StringUtils.ordinalIndexOf(str, searchStr, ordinal, true);\n }\n\n /**\n *

          Finds the first index within a String, handling null.\n * This method uses {@link String#lastIndexOf(String, int)}.

          \n *\n *

          A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

          \n *\n *
          \n     * StringUtils.lastIndexOf(null, *, *)          = -1\n     * StringUtils.lastIndexOf(*, null, *)          = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\", 8)  = 7\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 8)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"ab\", 8) = 4\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 9)  = 5\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", -1) = -1\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"a\", 0)  = 0\n     * StringUtils.lastIndexOf(\"aabaabaa\", \"b\", 0)  = -1\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position, negative treated as zero\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.0\n */\n public static int lastIndexOf(final String str, final String searchStr, final int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr, startPos);\n }\n\n /**\n *

          Case in-sensitive find of the last index within a String.

          \n *\n *

          A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

          \n *\n *
          \n     * StringUtils.lastIndexOfIgnoreCase(null, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(*, null)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\")  = 7\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\")  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"AB\") = 4\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int lastIndexOfIgnoreCase(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return StringUtils.lastIndexOfIgnoreCase(str, searchStr, str.length());\n }\n\n /**\n *

          Case in-sensitive find of the last index within a String\n * from the specified position.

          \n *\n *

          A null String will return -1.\n * A negative start position returns -1.\n * An empty (\"\") search String always matches unless the start position is negative.\n * A start position greater than the string length searches the whole string.

          \n *\n *
          \n     * StringUtils.lastIndexOfIgnoreCase(null, *, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(*, null, *)          = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\", 8)  = 7\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 8)  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"AB\", 8) = 4\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 9)  = 5\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", -1) = -1\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"A\", 0)  = 0\n     * StringUtils.lastIndexOfIgnoreCase(\"aabaabaa\", \"B\", 0)  = -1\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @param startPos the start position\n * @return the first index of the search String,\n * -1 if no match or null string input\n * @since 2.5\n */\n public static int lastIndexOfIgnoreCase(final String str, final String searchStr, int startPos) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (startPos > str.length() - searchStr.length()) {\n startPos = str.length() - searchStr.length();\n }\n if (startPos < 0) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (searchStr.length() == 0) {\n return startPos;\n }\n for (int i = startPos; i >= 0; i--) {\n if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) {\n return i;\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // Contains\n //-----------------------------------------------------------------------\n\n /**\n *

          Checks if String contains a search character, handling null.\n * This method uses {@link String#indexOf(int)}.

          \n *\n *

          A null or empty (\"\") String will return false.

          \n *\n *
          \n     * StringUtils.contains(null, *)    = false\n     * StringUtils.contains(\"\", *)      = false\n     * StringUtils.contains(\"abc\", 'a') = true\n     * StringUtils.contains(\"abc\", 'z') = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchChar the character to find\n * @return true if the String contains the search character,\n * false if not or null string input\n * @since 2.0\n */\n public static boolean contains(final String str, final char searchChar) {\n if (StringUtils.isEmpty(str)) {\n return false;\n }\n return str.indexOf(searchChar) >= 0;\n }\n\n /**\n *

          Checks if String contains a search String, handling null.\n * This method uses {@link String#indexOf(String)}.

          \n *\n *

          A null String will return false.

          \n *\n *
          \n     * StringUtils.contains(null, *)     = false\n     * StringUtils.contains(*, null)     = false\n     * StringUtils.contains(\"\", \"\")      = true\n     * StringUtils.contains(\"abc\", \"\")   = true\n     * StringUtils.contains(\"abc\", \"a\")  = true\n     * StringUtils.contains(\"abc\", \"z\")  = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return true if the String contains the search String,\n * false if not or null string input\n * @since 2.0\n */\n public static boolean contains(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n return str.contains(searchStr);\n }\n\n /**\n *

          Checks if String contains a search String irrespective of case,\n * handling null. Case-insensitivity is defined as by\n * {@link String#equalsIgnoreCase(String)}.\n *\n *

          A null String will return false.

          \n *\n *
          \n     * StringUtils.contains(null, *) = false\n     * StringUtils.contains(*, null) = false\n     * StringUtils.contains(\"\", \"\") = true\n     * StringUtils.contains(\"abc\", \"\") = true\n     * StringUtils.contains(\"abc\", \"a\") = true\n     * StringUtils.contains(\"abc\", \"z\") = false\n     * StringUtils.contains(\"abc\", \"A\") = true\n     * StringUtils.contains(\"abc\", \"Z\") = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStr the String to find, may be null\n * @return true if the String contains the search String irrespective of\n * case or false if not or null string input\n */\n public static boolean containsIgnoreCase(final String str, final String searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n int len = searchStr.length();\n int max = str.length() - len;\n for (int i = 0; i <= max; i++) {\n if (str.regionMatches(true, i, searchStr, 0, len)) {\n return true;\n }\n }\n return false;\n }\n // IndexOfAny chars\n //-----------------------------------------------------------------------\n\n /**\n *

          Search a String to find the first index of any\n * character in the given set of characters.

          \n *\n *

          A null String will return -1.\n * A null or zero length search array will return -1.

          \n *\n *
          \n     * StringUtils.indexOfAny(null, *)                = -1\n     * StringUtils.indexOfAny(\"\", *)                  = -1\n     * StringUtils.indexOfAny(*, null)                = -1\n     * StringUtils.indexOfAny(*, [])                  = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\",['z','a']) = 0\n     * StringUtils.indexOfAny(\"zzabyycdxx\",['b','y']) = 3\n     * StringUtils.indexOfAny(\"aba\", ['z'])           = -1\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAny(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) {\n // ch is a supplementary character\n if (searchChars[j + 1] == str.charAt(i + 1)) {\n return i;\n }\n } else {\n return i;\n }\n }\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Search a String to find the first index of any\n * character in the given set of characters.

          \n *\n *

          A null String will return -1.\n * A null search string will return -1.

          \n *\n *
          \n     * StringUtils.indexOfAny(null, *)            = -1\n     * StringUtils.indexOfAny(\"\", *)              = -1\n     * StringUtils.indexOfAny(*, null)            = -1\n     * StringUtils.indexOfAny(*, \"\")              = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", \"za\") = 0\n     * StringUtils.indexOfAny(\"zzabyycdxx\", \"by\") = 3\n     * StringUtils.indexOfAny(\"aba\",\"z\")          = -1\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAny(final String str, final String searchChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return StringUtils.indexOfAny(str, searchChars.toCharArray());\n }\n // ContainsAny\n //-----------------------------------------------------------------------\n\n /**\n *

          Checks if the String contains any character in the given\n * set of characters.

          \n *\n *

          A null String will return false.\n * A null or zero length search array will return false.

          \n *\n *
          \n     * StringUtils.containsAny(null, *)                = false\n     * StringUtils.containsAny(\"\", *)                  = false\n     * StringUtils.containsAny(*, null)                = false\n     * StringUtils.containsAny(*, [])                  = false\n     * StringUtils.containsAny(\"zzabyycdxx\",['z','a']) = true\n     * StringUtils.containsAny(\"zzabyycdxx\",['b','y']) = true\n     * StringUtils.containsAny(\"aba\", ['z'])           = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the true if any of the chars are found,\n * false if no match or null input\n * @since 2.4\n */\n public static boolean containsAny(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return false;\n }\n int csLength = str.length();\n int searchLength = searchChars.length;\n int csLast = csLength - 1;\n int searchLast = searchLength - 1;\n for (int i = 0; i < csLength; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLength; j++) {\n if (searchChars[j] == ch) {\n if (CharUtils.isHighSurrogate(ch)) {\n if (j == searchLast) {\n // missing low surrogate, fine, like String.indexOf(String)\n return true;\n }\n if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) {\n return true;\n }\n } else {\n // ch is in the Basic Multilingual Plane\n return true;\n }\n }\n }\n }\n return false;\n }\n\n /**\n *

          \n * Checks if the String contains any character in the given set of characters.\n *

          \n *\n *

          \n * A null String will return false. A null search string will return\n * false.\n *

          \n *\n *
          \n     * StringUtils.containsAny(null, *)            = false\n     * StringUtils.containsAny(\"\", *)              = false\n     * StringUtils.containsAny(*, null)            = false\n     * StringUtils.containsAny(*, \"\")              = false\n     * StringUtils.containsAny(\"zzabyycdxx\", \"za\") = true\n     * StringUtils.containsAny(\"zzabyycdxx\", \"by\") = true\n     * StringUtils.containsAny(\"aba\",\"z\")          = false\n     * 
          \n *\n * @param str\n * the String to check, may be null\n * @param searchChars\n * the chars to search for, may be null\n * @return the true if any of the chars are found, false if no match or null input\n * @since 2.4\n */\n public static boolean containsAny(final String str, final String searchChars) {\n if (searchChars == null) {\n return false;\n }\n return StringUtils.containsAny(str, searchChars.toCharArray());\n }\n // IndexOfAnyBut chars\n //-----------------------------------------------------------------------\n\n /**\n *

          Search a String to find the first index of any\n * character not in the given set of characters.

          \n *\n *

          A null String will return -1.\n * A null or zero length search array will return -1.

          \n *\n *
          \n     * StringUtils.indexOfAnyBut(null, *)                              = -1\n     * StringUtils.indexOfAnyBut(\"\", *)                                = -1\n     * StringUtils.indexOfAnyBut(*, null)                              = -1\n     * StringUtils.indexOfAnyBut(*, [])                                = -1\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", new char[] {'z', 'a'} ) = 3\n     * StringUtils.indexOfAnyBut(\"aba\", new char[] {'z'} )             = 0\n     * StringUtils.indexOfAnyBut(\"aba\", new char[] {'a', 'b'} )        = -1\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAnyBut(final String str, final char[] searchChars) {\n if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n outer:\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) {\n if (searchChars[j + 1] == str.charAt(i + 1)) {\n continue outer;\n }\n } else {\n continue outer;\n }\n }\n }\n return i;\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Search a String to find the first index of any\n * character not in the given set of characters.

          \n *\n *

          A null String will return -1.\n * A null or empty search string will return -1.

          \n *\n *
          \n     * StringUtils.indexOfAnyBut(null, *)            = -1\n     * StringUtils.indexOfAnyBut(\"\", *)              = -1\n     * StringUtils.indexOfAnyBut(*, null)            = -1\n     * StringUtils.indexOfAnyBut(*, \"\")              = -1\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", \"za\") = 3\n     * StringUtils.indexOfAnyBut(\"zzabyycdxx\", \"\")   = -1\n     * StringUtils.indexOfAnyBut(\"aba\",\"ab\")         = -1\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchChars the chars to search for, may be null\n * @return the index of any of the chars, -1 if no match or null input\n * @since 2.0\n */\n public static int indexOfAnyBut(final String str, final String searchChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n char ch = str.charAt(i);\n boolean chFound = searchChars.indexOf(ch) >= 0;\n if (i + 1 < strLen && CharUtils.isHighSurrogate(ch)) {\n char ch2 = str.charAt(i + 1);\n if (chFound && searchChars.indexOf(ch2) < 0) {\n return i;\n }\n } else {\n if (!chFound) {\n return i;\n }\n }\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n // ContainsOnly\n //-----------------------------------------------------------------------\n\n /**\n *

          Checks if the String contains only certain characters.

          \n *\n *

          A null String will return false.\n * A null valid character array will return false.\n * An empty String (length()=0) always returns true.

          \n *\n *
          \n     * StringUtils.containsOnly(null, *)       = false\n     * StringUtils.containsOnly(*, null)       = false\n     * StringUtils.containsOnly(\"\", *)         = true\n     * StringUtils.containsOnly(\"ab\", '')      = false\n     * StringUtils.containsOnly(\"abab\", 'abc') = true\n     * StringUtils.containsOnly(\"ab1\", 'abc')  = false\n     * StringUtils.containsOnly(\"abz\", 'abc')  = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @param valid an array of valid chars, may be null\n * @return true if it only contains valid chars and is non-null\n */\n public static boolean containsOnly(final String str, final char[] valid) {\n // All these pre-checks are to maintain API with an older version\n if (valid == null || str == null) {\n return false;\n }\n if (str.length() == 0) {\n return true;\n }\n if (valid.length == 0) {\n return false;\n }\n return StringUtils.indexOfAnyBut(str, valid) == StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the String contains only certain characters.

          \n *\n *

          A null String will return false.\n * A null valid character String will return false.\n * An empty String (length()=0) always returns true.

          \n *\n *
          \n     * StringUtils.containsOnly(null, *)       = false\n     * StringUtils.containsOnly(*, null)       = false\n     * StringUtils.containsOnly(\"\", *)         = true\n     * StringUtils.containsOnly(\"ab\", \"\")      = false\n     * StringUtils.containsOnly(\"abab\", \"abc\") = true\n     * StringUtils.containsOnly(\"ab1\", \"abc\")  = false\n     * StringUtils.containsOnly(\"abz\", \"abc\")  = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @param validChars a String of valid chars, may be null\n * @return true if it only contains valid chars and is non-null\n * @since 2.0\n */\n public static boolean containsOnly(final String str, final String validChars) {\n if (str == null || validChars == null) {\n return false;\n }\n return StringUtils.containsOnly(str, validChars.toCharArray());\n }\n // ContainsNone\n //-----------------------------------------------------------------------\n\n /**\n *

          Checks that the String does not contain certain characters.

          \n *\n *

          A null String will return true.\n * A null invalid character array will return true.\n * An empty String (length()=0) always returns true.

          \n *\n *
          \n     * StringUtils.containsNone(null, *)       = true\n     * StringUtils.containsNone(*, null)       = true\n     * StringUtils.containsNone(\"\", *)         = true\n     * StringUtils.containsNone(\"ab\", '')      = true\n     * StringUtils.containsNone(\"abab\", 'xyz') = true\n     * StringUtils.containsNone(\"ab1\", 'xyz')  = true\n     * StringUtils.containsNone(\"abz\", 'xyz')  = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchChars an array of invalid chars, may be null\n * @return true if it contains none of the invalid chars, or is null\n * @since 2.0\n */\n public static boolean containsNone(final String str, final char[] searchChars) {\n if (str == null || searchChars == null) {\n return true;\n }\n int csLen = str.length();\n int csLast = csLen - 1;\n int searchLen = searchChars.length;\n int searchLast = searchLen - 1;\n for (int i = 0; i < csLen; i++) {\n char ch = str.charAt(i);\n for (int j = 0; j < searchLen; j++) {\n if (searchChars[j] == ch) {\n if (CharUtils.isHighSurrogate(ch)) {\n if (j == searchLast) {\n // missing low surrogate, fine, like String.indexOf(String)\n return false;\n }\n if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) {\n return false;\n }\n } else {\n // ch is in the Basic Multilingual Plane\n return false;\n }\n }\n }\n }\n return true;\n }\n\n /**\n *

          Checks that the String does not contain certain characters.

          \n *\n *

          A null String will return true.\n * A null invalid character array will return true.\n * An empty String (\"\") always returns true.

          \n *\n *
          \n     * StringUtils.containsNone(null, *)       = true\n     * StringUtils.containsNone(*, null)       = true\n     * StringUtils.containsNone(\"\", *)         = true\n     * StringUtils.containsNone(\"ab\", \"\")      = true\n     * StringUtils.containsNone(\"abab\", \"xyz\") = true\n     * StringUtils.containsNone(\"ab1\", \"xyz\")  = true\n     * StringUtils.containsNone(\"abz\", \"xyz\")  = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @param invalidChars a String of invalid chars, may be null\n * @return true if it contains none of the invalid chars, or is null\n * @since 2.0\n */\n public static boolean containsNone(final String str, final String invalidChars) {\n if (str == null || invalidChars == null) {\n return true;\n }\n return StringUtils.containsNone(str, invalidChars.toCharArray());\n }\n // IndexOfAny strings\n //-----------------------------------------------------------------------\n\n /**\n *

          Find the first index of any of a set of potential substrings.

          \n *\n *

          A null String will return -1.\n * A null or zero length search array will return -1.\n * A null search array entry will be ignored, but a search\n * array containing \"\" will return 0 if str is not\n * null. This method uses {@link String#indexOf(String)}.

          \n *\n *
          \n     * StringUtils.indexOfAny(null, *)                     = -1\n     * StringUtils.indexOfAny(*, null)                     = -1\n     * StringUtils.indexOfAny(*, [])                       = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"ab\",\"cd\"])   = 2\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"cd\",\"ab\"])   = 2\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"])   = -1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"zab\",\"aby\"]) = 1\n     * StringUtils.indexOfAny(\"zzabyycdxx\", [\"\"])          = 0\n     * StringUtils.indexOfAny(\"\", [\"\"])                    = 0\n     * StringUtils.indexOfAny(\"\", [\"a\"])                   = -1\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStrs the Strings to search for, may be null\n * @return the first index of any of the searchStrs in str, -1 if no match\n */\n public static int indexOfAny(final String str, final String[] searchStrs) {\n if (str == null || searchStrs == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int sz = searchStrs.length;\n // String's can't have a MAX_VALUEth index.\n int ret = Integer.MAX_VALUE;\n int tmp = 0;\n for (int i = 0; i < sz; i++) {\n String search = searchStrs[i];\n if (search == null) {\n continue;\n }\n tmp = str.indexOf(search);\n if (tmp == StringUtils.INDEX_NOT_FOUND) {\n continue;\n }\n if (tmp < ret) {\n ret = tmp;\n }\n }\n return ret == Integer.MAX_VALUE ? StringUtils.INDEX_NOT_FOUND : ret;\n }\n\n /**\n *

          Find the latest index of any of a set of potential substrings.

          \n *\n *

          A null String will return -1.\n * A null search array will return -1.\n * A null or zero length search array entry will be ignored,\n * but a search array containing \"\" will return the length of str\n * if str is not null. This method uses {@link String#indexOf(String)}

          \n *\n *
          \n     * StringUtils.lastIndexOfAny(null, *)                   = -1\n     * StringUtils.lastIndexOfAny(*, null)                   = -1\n     * StringUtils.lastIndexOfAny(*, [])                     = -1\n     * StringUtils.lastIndexOfAny(*, [null])                 = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"ab\",\"cd\"]) = 6\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"cd\",\"ab\"]) = 6\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"]) = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"op\"]) = -1\n     * StringUtils.lastIndexOfAny(\"zzabyycdxx\", [\"mn\",\"\"])   = 10\n     * 
          \n *\n * @param str the String to check, may be null\n * @param searchStrs the Strings to search for, may be null\n * @return the last index of any of the Strings, -1 if no match\n */\n public static int lastIndexOfAny(final String str, final String[] searchStrs) {\n if (str == null || searchStrs == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n int sz = searchStrs.length;\n int ret = StringUtils.INDEX_NOT_FOUND;\n int tmp = 0;\n for (int i = 0; i < sz; i++) {\n String search = searchStrs[i];\n if (search == null) {\n continue;\n }\n tmp = str.lastIndexOf(search);\n if (tmp > ret) {\n ret = tmp;\n }\n }\n return ret;\n }\n // Substring\n //-----------------------------------------------------------------------\n\n /**\n *

          Gets a substring from the specified String avoiding exceptions.

          \n *\n *

          A negative start position can be used to start n\n * characters from the end of the String.

          \n *\n *

          A null String will return null.\n * An empty (\"\") String will return \"\".

          \n *\n *
          \n     * StringUtils.substring(null, *)   = null\n     * StringUtils.substring(\"\", *)     = \"\"\n     * StringUtils.substring(\"abc\", 0)  = \"abc\"\n     * StringUtils.substring(\"abc\", 2)  = \"c\"\n     * StringUtils.substring(\"abc\", 4)  = \"\"\n     * StringUtils.substring(\"abc\", -2) = \"bc\"\n     * StringUtils.substring(\"abc\", -4) = \"abc\"\n     * 
          \n *\n * @param str the String to get the substring from, may be null\n * @param start the position to start from, negative means\n * count back from the end of the String by this many characters\n * @return substring from start position, null if null String input\n */\n public static String substring(final String str, int start) {\n if (str == null) {\n return null;\n }\n // handle negatives, which means last n characters\n if (start < 0) {\n start = str.length() + start; // remember start is negative\n }\n if (start < 0) {\n start = 0;\n }\n if (start > str.length()) {\n return StringUtils.EMPTY;\n }\n return str.substring(start);\n }\n\n /**\n *

          Gets a substring from the specified String avoiding exceptions.

          \n *\n *

          A negative start position can be used to start/end n\n * characters from the end of the String.

          \n *\n *

          The returned substring starts with the character in the start\n * position and ends before the end position. All position counting is\n * zero-based -- i.e., to start at the beginning of the string use\n * start = 0. Negative start and end positions can be used to\n * specify offsets relative to the end of the String.

          \n *\n *

          If start is not strictly to the left of end, \"\"\n * is returned.

          \n *\n *
          \n     * StringUtils.substring(null, *, *)    = null\n     * StringUtils.substring(\"\", * ,  *)    = \"\";\n     * StringUtils.substring(\"abc\", 0, 2)   = \"ab\"\n     * StringUtils.substring(\"abc\", 2, 0)   = \"\"\n     * StringUtils.substring(\"abc\", 2, 4)   = \"c\"\n     * StringUtils.substring(\"abc\", 4, 6)   = \"\"\n     * StringUtils.substring(\"abc\", 2, 2)   = \"\"\n     * StringUtils.substring(\"abc\", -2, -1) = \"b\"\n     * StringUtils.substring(\"abc\", -4, 2)  = \"ab\"\n     * 
          \n *\n * @param str the String to get the substring from, may be null\n * @param start the position to start from, negative means\n * count back from the end of the String by this many characters\n * @param end the position to end at (exclusive), negative means\n * count back from the end of the String by this many characters\n * @return substring from start position to end positon,\n * null if null String input\n */\n public static String substring(final String str, int start, int end) {\n if (str == null) {\n return null;\n }\n // handle negatives\n if (end < 0) {\n end = str.length() + end; // remember end is negative\n }\n if (start < 0) {\n start = str.length() + start; // remember start is negative\n }\n // check length next\n if (end > str.length()) {\n end = str.length();\n }\n // if start is greater than end, return \"\"\n if (start > end) {\n return StringUtils.EMPTY;\n }\n if (start < 0) {\n start = 0;\n }\n if (end < 0) {\n end = 0;\n }\n return str.substring(start, end);\n }\n // Left/Right/Mid\n //-----------------------------------------------------------------------\n\n /**\n *

          Gets the leftmost len characters of a String.

          \n *\n *

          If len characters are not available, or the\n * String is null, the String will be returned without\n * an exception. An empty String is returned if len is negative.

          \n *\n *
          \n     * StringUtils.left(null, *)    = null\n     * StringUtils.left(*, -ve)     = \"\"\n     * StringUtils.left(\"\", *)      = \"\"\n     * StringUtils.left(\"abc\", 0)   = \"\"\n     * StringUtils.left(\"abc\", 2)   = \"ab\"\n     * StringUtils.left(\"abc\", 4)   = \"abc\"\n     * 
          \n *\n * @param str the String to get the leftmost characters from, may be null\n * @param len the length of the required String\n * @return the leftmost characters, null if null String input\n */\n public static String left(final String str, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0) {\n return StringUtils.EMPTY;\n }\n if (str.length() <= len) {\n return str;\n }\n return str.substring(0, len);\n }\n\n /**\n *

          Gets the rightmost len characters of a String.

          \n *\n *

          If len characters are not available, or the String\n * is null, the String will be returned without an\n * an exception. An empty String is returned if len is negative.

          \n *\n *
          \n     * StringUtils.right(null, *)    = null\n     * StringUtils.right(*, -ve)     = \"\"\n     * StringUtils.right(\"\", *)      = \"\"\n     * StringUtils.right(\"abc\", 0)   = \"\"\n     * StringUtils.right(\"abc\", 2)   = \"bc\"\n     * StringUtils.right(\"abc\", 4)   = \"abc\"\n     * 
          \n *\n * @param str the String to get the rightmost characters from, may be null\n * @param len the length of the required String\n * @return the rightmost characters, null if null String input\n */\n public static String right(final String str, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0) {\n return StringUtils.EMPTY;\n }\n if (str.length() <= len) {\n return str;\n }\n return str.substring(str.length() - len);\n }\n\n /**\n *

          Gets len characters from the middle of a String.

          \n *\n *

          If len characters are not available, the remainder\n * of the String will be returned without an exception. If the\n * String is null, null will be returned.\n * An empty String is returned if len is negative or exceeds the\n * length of str.

          \n *\n *
          \n     * StringUtils.mid(null, *, *)    = null\n     * StringUtils.mid(*, *, -ve)     = \"\"\n     * StringUtils.mid(\"\", 0, *)      = \"\"\n     * StringUtils.mid(\"abc\", 0, 2)   = \"ab\"\n     * StringUtils.mid(\"abc\", 0, 4)   = \"abc\"\n     * StringUtils.mid(\"abc\", 2, 4)   = \"c\"\n     * StringUtils.mid(\"abc\", 4, 2)   = \"\"\n     * StringUtils.mid(\"abc\", -2, 2)  = \"ab\"\n     * 
          \n *\n * @param str the String to get the characters from, may be null\n * @param pos the position to start from, negative treated as zero\n * @param len the length of the required String\n * @return the middle characters, null if null String input\n */\n public static String mid(final String str, int pos, final int len) {\n if (str == null) {\n return null;\n }\n if (len < 0 || pos > str.length()) {\n return StringUtils.EMPTY;\n }\n if (pos < 0) {\n pos = 0;\n }\n if (str.length() <= pos + len) {\n return str.substring(pos);\n }\n return str.substring(pos, pos + len);\n }\n // SubStringAfter/SubStringBefore\n //-----------------------------------------------------------------------\n\n /**\n *

          Gets the substring before the first occurrence of a separator.\n * The separator is not returned.

          \n *\n *

          A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * A null separator will return the input string.

          \n *\n *

          If nothing is found, the string input is returned.

          \n *\n *
          \n     * StringUtils.substringBefore(null, *)      = null\n     * StringUtils.substringBefore(\"\", *)        = \"\"\n     * StringUtils.substringBefore(\"abc\", \"a\")   = \"\"\n     * StringUtils.substringBefore(\"abcba\", \"b\") = \"a\"\n     * StringUtils.substringBefore(\"abc\", \"c\")   = \"ab\"\n     * StringUtils.substringBefore(\"abc\", \"d\")   = \"abc\"\n     * StringUtils.substringBefore(\"abc\", \"\")    = \"\"\n     * StringUtils.substringBefore(\"abc\", null)  = \"abc\"\n     * 
          \n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring before the first occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringBefore(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || separator == null) {\n return str;\n }\n if (separator.length() == 0) {\n return StringUtils.EMPTY;\n }\n int pos = str.indexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n return str.substring(0, pos);\n }\n\n /**\n *

          Gets the substring after the first occurrence of a separator.\n * The separator is not returned.

          \n *\n *

          A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * A null separator will return the empty string if the\n * input string is not null.

          \n *\n *

          If nothing is found, the empty string is returned.

          \n *\n *
          \n     * StringUtils.substringAfter(null, *)      = null\n     * StringUtils.substringAfter(\"\", *)        = \"\"\n     * StringUtils.substringAfter(*, null)      = \"\"\n     * StringUtils.substringAfter(\"abc\", \"a\")   = \"bc\"\n     * StringUtils.substringAfter(\"abcba\", \"b\") = \"cba\"\n     * StringUtils.substringAfter(\"abc\", \"c\")   = \"\"\n     * StringUtils.substringAfter(\"abc\", \"d\")   = \"\"\n     * StringUtils.substringAfter(\"abc\", \"\")    = \"abc\"\n     * 
          \n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring after the first occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringAfter(final String str, final String separator) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (separator == null) {\n return StringUtils.EMPTY;\n }\n int pos = str.indexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return StringUtils.EMPTY;\n }\n return str.substring(pos + separator.length());\n }\n\n /**\n *

          Gets the substring before the last occurrence of a separator.\n * The separator is not returned.

          \n *\n *

          A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * An empty or null separator will return the input string.

          \n *\n *

          If nothing is found, the string input is returned.

          \n *\n *
          \n     * StringUtils.substringBeforeLast(null, *)      = null\n     * StringUtils.substringBeforeLast(\"\", *)        = \"\"\n     * StringUtils.substringBeforeLast(\"abcba\", \"b\") = \"abc\"\n     * StringUtils.substringBeforeLast(\"abc\", \"c\")   = \"ab\"\n     * StringUtils.substringBeforeLast(\"a\", \"a\")     = \"\"\n     * StringUtils.substringBeforeLast(\"a\", \"z\")     = \"a\"\n     * StringUtils.substringBeforeLast(\"a\", null)    = \"a\"\n     * StringUtils.substringBeforeLast(\"a\", \"\")      = \"a\"\n     * 
          \n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring before the last occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringBeforeLast(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(separator)) {\n return str;\n }\n int pos = str.lastIndexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n return str.substring(0, pos);\n }\n\n /**\n *

          Gets the substring after the last occurrence of a separator.\n * The separator is not returned.

          \n *\n *

          A null string input will return null.\n * An empty (\"\") string input will return the empty string.\n * An empty or null separator will return the empty string if\n * the input string is not null.

          \n *\n *

          If nothing is found, the empty string is returned.

          \n *\n *
          \n     * StringUtils.substringAfterLast(null, *)      = null\n     * StringUtils.substringAfterLast(\"\", *)        = \"\"\n     * StringUtils.substringAfterLast(*, \"\")        = \"\"\n     * StringUtils.substringAfterLast(*, null)      = \"\"\n     * StringUtils.substringAfterLast(\"abc\", \"a\")   = \"bc\"\n     * StringUtils.substringAfterLast(\"abcba\", \"b\") = \"a\"\n     * StringUtils.substringAfterLast(\"abc\", \"c\")   = \"\"\n     * StringUtils.substringAfterLast(\"a\", \"a\")     = \"\"\n     * StringUtils.substringAfterLast(\"a\", \"z\")     = \"\"\n     * 
          \n *\n * @param str the String to get a substring from, may be null\n * @param separator the String to search for, may be null\n * @return the substring after the last occurrence of the separator,\n * null if null String input\n * @since 2.0\n */\n public static String substringAfterLast(final String str, final String separator) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (StringUtils.isEmpty(separator)) {\n return StringUtils.EMPTY;\n }\n int pos = str.lastIndexOf(separator);\n if (pos == StringUtils.INDEX_NOT_FOUND || pos == str.length() - separator.length()) {\n return StringUtils.EMPTY;\n }\n return str.substring(pos + separator.length());\n }\n // Substring between\n //-----------------------------------------------------------------------\n\n /**\n *

          Gets the String that is nested in between two instances of the\n * same String.

          \n *\n *

          A null input String returns null.\n * A null tag returns null.

          \n *\n *
          \n     * StringUtils.substringBetween(null, *)            = null\n     * StringUtils.substringBetween(\"\", \"\")             = \"\"\n     * StringUtils.substringBetween(\"\", \"tag\")          = null\n     * StringUtils.substringBetween(\"tagabctag\", null)  = null\n     * StringUtils.substringBetween(\"tagabctag\", \"\")    = \"\"\n     * StringUtils.substringBetween(\"tagabctag\", \"tag\") = \"abc\"\n     * 
          \n *\n * @param str the String containing the substring, may be null\n * @param tag the String before and after the substring, may be null\n * @return the substring, null if no match\n * @since 2.0\n */\n public static String substringBetween(final String str, final String tag) {\n return StringUtils.substringBetween(str, tag, tag);\n }\n\n /**\n *

          Gets the String that is nested in between two Strings.\n * Only the first match is returned.

          \n *\n *

          A null input String returns null.\n * A null open/close returns null (no match).\n * An empty (\"\") open and close returns an empty string.

          \n *\n *
          \n     * StringUtils.substringBetween(\"wx[b]yz\", \"[\", \"]\") = \"b\"\n     * StringUtils.substringBetween(null, *, *)          = null\n     * StringUtils.substringBetween(*, null, *)          = null\n     * StringUtils.substringBetween(*, *, null)          = null\n     * StringUtils.substringBetween(\"\", \"\", \"\")          = \"\"\n     * StringUtils.substringBetween(\"\", \"\", \"]\")         = null\n     * StringUtils.substringBetween(\"\", \"[\", \"]\")        = null\n     * StringUtils.substringBetween(\"yabcz\", \"\", \"\")     = \"\"\n     * StringUtils.substringBetween(\"yabcz\", \"y\", \"z\")   = \"abc\"\n     * StringUtils.substringBetween(\"yabczyabcz\", \"y\", \"z\")   = \"abc\"\n     * 
          \n *\n * @param str the String containing the substring, may be null\n * @param open the String before the substring, may be null\n * @param close the String after the substring, may be null\n * @return the substring, null if no match\n * @since 2.0\n */\n public static String substringBetween(final String str, final String open, final String close) {\n if (str == null || open == null || close == null) {\n return null;\n }\n int start = str.indexOf(open);\n if (start != StringUtils.INDEX_NOT_FOUND) {\n int end = str.indexOf(close, start + open.length());\n if (end != StringUtils.INDEX_NOT_FOUND) {\n return str.substring(start + open.length(), end);\n }\n }\n return null;\n }\n\n /**\n *

          Searches a String for substrings delimited by a start and end tag,\n * returning all matching substrings in an array.

          \n *\n *

          A null input String returns null.\n * A null open/close returns null (no match).\n * An empty (\"\") open/close returns null (no match).

          \n *\n *
          \n     * StringUtils.substringsBetween(\"[a][b][c]\", \"[\", \"]\") = [\"a\",\"b\",\"c\"]\n     * StringUtils.substringsBetween(null, *, *)            = null\n     * StringUtils.substringsBetween(*, null, *)            = null\n     * StringUtils.substringsBetween(*, *, null)            = null\n     * StringUtils.substringsBetween(\"\", \"[\", \"]\")          = []\n     * 
          \n *\n * @param str the String containing the substrings, null returns null, empty returns empty\n * @param open the String identifying the start of the substring, empty returns null\n * @param close the String identifying the end of the substring, empty returns null\n * @return a String Array of substrings, or null if no match\n * @since 2.3\n */\n public static String[] substringsBetween(final String str, final String open, final String close) {\n if (str == null || StringUtils.isEmpty(open) || StringUtils.isEmpty(close)) {\n return null;\n }\n int strLen = str.length();\n if (strLen == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n int closeLen = close.length();\n int openLen = open.length();\n List list = new ArrayList();\n int pos = 0;\n while (pos < strLen - closeLen) {\n int start = str.indexOf(open, pos);\n if (start < 0) {\n break;\n }\n start += openLen;\n int end = str.indexOf(close, start);\n if (end < 0) {\n break;\n }\n list.add(str.substring(start, end));\n pos = end + closeLen;\n }\n if (list.isEmpty()) {\n return null;\n }\n return list.toArray(new String[list.size()]);\n }\n // Splitting\n //-----------------------------------------------------------------------\n\n /**\n *

          Splits the provided text into an array, using whitespace as the separator. but keep separator.

          \n *\n *
          \n     * StringUtils.splitKeep(null)          = null\n     * StringUtils.splitKeep(\"\")            = []\n     * StringUtils.splitKeep(\"a b c\", \" \")  = [\"a\", \" \", \"b\", \" \", \"c\"]\n     * StringUtils.splitKeep(\"abc def\", \" \")= [\"abc\", \" \", \"def\"]\n     * StringUtils.splitKeep(\" abc \", \" \")  = [\" \", \"abc\", \" \"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] splitKeep(String str, char separatorChar) {\n return splitKeep(str, String.valueOf(separatorChar));\n }\n\n /**\n *

          Splits the provided text into an array, using whitespace as the separator. but keep separator.

          \n *\n *
          \n     * StringUtils.splitKeep(null)          = null\n     * StringUtils.splitKeep(\"\")            = []\n     * StringUtils.splitKeep(\"a b c\", \" \")  = [\"a\", \" \", \"b\", \" \", \"c\"]\n     * StringUtils.splitKeep(\"abc def\", \" \")= [\"abc\", \" \", \"def\"]\n     * StringUtils.splitKeep(\" abc \", \" \")  = [\" \", \"abc\", \" \"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] splitKeep(String str, String separatorStr) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n int CHARS = separatorStr.length();\n if (CHARS == 0) {\n throw new IllegalArgumentException(\"chars must be > 0\");\n }\n int lastIndex = 0;\n ArrayList dat = new ArrayList<>();\n while (true) {\n int lookIndex = str.indexOf(separatorStr, lastIndex);\n if (lookIndex == -1) {\n String substring = str.substring(lastIndex);\n if (substring.length() > 0) {\n dat.add(substring);\n }\n break;\n } else {\n if (lastIndex != lookIndex) {\n String term = str.substring(lastIndex, lookIndex);\n dat.add(term);\n }\n dat.add(separatorStr);\n lastIndex = lookIndex + CHARS;\n }\n }\n return dat.toArray(new String[0]);\n }\n\n /**\n *

          Splits the provided text into an array, using whitespace as the\n * separator.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

          \n *\n *

          The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

          \n *\n *

          A null input String returns null.

          \n *\n *
          \n     * StringUtils.split(null)       = null\n     * StringUtils.split(\"\")         = []\n     * StringUtils.split(\"abc def\")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\") = [\"abc\", \"def\"]\n     * StringUtils.split(\" abc \")    = [\"abc\"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str) {\n return StringUtils.split(str, null, -1);\n }\n\n /**\n *

          Splits the provided text into an array, separator specified.\n * This is an alternative to using StringTokenizer.

          \n *\n *

          The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

          \n *\n *

          A null input String returns null.

          \n *\n *
          \n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"a.b.c\", '.')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.split(\"a..b.c\", '.')   = [\"a\", \"b\", \"c\"]\n     * StringUtils.split(\"a:b:c\", '.')    = [\"a:b:c\"]\n     * StringUtils.split(\"a b c\", ' ')    = [\"a\", \"b\", \"c\"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @param separatorChar the character used as the delimiter\n * @return an array of parsed Strings, null if null String input\n * @since 2.0\n */\n public static String[] split(final String str, final char separatorChar) {\n return StringUtils.splitWorker(str, separatorChar, false);\n }\n\n /**\n *

          Splits the provided text into an array, separators specified.\n * This is an alternative to using StringTokenizer.

          \n *\n *

          The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

          \n *\n *

          A null input String returns null.\n * A null separatorChars splits on whitespace.

          \n *\n *
          \n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"abc def\", null) = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc def\", \" \")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\", \" \") = [\"abc\", \"def\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\") = [\"ab\", \"cd\", \"ef\"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str, final String separatorChars) {\n return StringUtils.splitWorker(str, separatorChars, -1, false);\n }\n\n /**\n *

          Splits the provided text into an array with a maximum length,\n * separators specified.

          \n *\n *

          The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.

          \n *\n *

          A null input String returns null.\n * A null separatorChars splits on whitespace.

          \n *\n *

          If more than max delimited substrings are found, the last\n * returned string includes all characters after the first max - 1\n * returned strings (including separator characters).

          \n *\n *
          \n     * StringUtils.split(null, *, *)            = null\n     * StringUtils.split(\"\", *, *)              = []\n     * StringUtils.split(\"ab de fg\", null, 0)   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab   de fg\", null, 0) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\", 0)    = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\", 2)    = [\"ab\", \"cd:ef\"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit\n * @return an array of parsed Strings, null if null String input\n */\n public static String[] split(final String str, final String separatorChars, final int max) {\n return StringUtils.splitWorker(str, separatorChars, max, false);\n }\n\n /**\n *

          Splits the provided text into an array, separator string specified.

          \n *\n *

          The separator(s) will not be included in the returned String array.\n * Adjacent separators are treated as one separator.

          \n *\n *

          A null input String returns null.\n * A null separator splits on whitespace.

          \n *\n *
          \n     * StringUtils.splitByWholeSeparator(null, *)               = null\n     * StringUtils.splitByWholeSeparator(\"\", *)                 = []\n     * StringUtils.splitByWholeSeparator(\"ab de fg\", null)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab   de fg\", null)    = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab:cd:ef\", \":\")       = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\") = [\"ab\", \"cd\", \"ef\"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String was input\n */\n public static String[] splitByWholeSeparator(final String str, final String separator) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, -1, false);\n }\n\n /**\n *

          Splits the provided text into an array, separator string specified.\n * Returns a maximum of max substrings.

          \n *\n *

          The separator(s) will not be included in the returned String array.\n * Adjacent separators are treated as one separator.

          \n *\n *

          A null input String returns null.\n * A null separator splits on whitespace.

          \n *\n *
          \n     * StringUtils.splitByWholeSeparator(null, *, *)               = null\n     * StringUtils.splitByWholeSeparator(\"\", *, *)                 = []\n     * StringUtils.splitByWholeSeparator(\"ab de fg\", null, 0)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab   de fg\", null, 0)    = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparator(\"ab:cd:ef\", \":\", 2)       = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\", 5) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparator(\"ab-!-cd-!-ef\", \"-!-\", 2) = [\"ab\", \"cd-!-ef\"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @return an array of parsed Strings, null if null String was input\n */\n public static String[] splitByWholeSeparator(final String str, final String separator, final int max) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, max, false);\n }\n\n /**\n *

          Splits the provided text into an array, separator string specified.

          \n *\n *

          The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

          \n *\n *

          A null input String returns null.\n * A null separator splits on whitespace.

          \n *\n *
          \n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *)               = null\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"\", *)                 = []\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab de fg\", null)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab   de fg\", null)    = [\"ab\", \"\", \"\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab:cd:ef\", \":\")       = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\") = [\"ab\", \"cd\", \"ef\"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String was input\n * @since 2.4\n */\n public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, -1, true);\n }\n\n /**\n *

          Splits the provided text into an array, separator string specified.\n * Returns a maximum of max substrings.

          \n *\n *

          The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

          \n *\n *

          A null input String returns null.\n * A null separator splits on whitespace.

          \n *\n *
          \n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *)               = null\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"\", *, *)                 = []\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab de fg\", null, 0)      = [\"ab\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab   de fg\", null, 0)    = [\"ab\", \"\", \"\", \"de\", \"fg\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab:cd:ef\", \":\", 2)       = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\", 5) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitByWholeSeparatorPreserveAllTokens(\"ab-!-cd-!-ef\", \"-!-\", 2) = [\"ab\", \"cd-!-ef\"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @return an array of parsed Strings, null if null String was input\n * @since 2.4\n */\n public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator, final int max) {\n return StringUtils.splitByWholeSeparatorWorker(str, separator, max, true);\n }\n\n /**\n * Performs the logic for the splitByWholeSeparatorPreserveAllTokens methods.\n *\n * @param str the String to parse, may be null\n * @param separator String containing the String to be used as a delimiter,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the returned\n * array. A zero or negative value implies no limit.\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n private static String[] splitByWholeSeparatorWorker(final String str, final String separator, final int max, final boolean preserveAllTokens) {\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n if (separator == null || StringUtils.EMPTY.equals(separator)) {\n // Split on whitespace.\n return StringUtils.splitWorker(str, null, max, preserveAllTokens);\n }\n int separatorLength = separator.length();\n ArrayList substrings = new ArrayList<>();\n int numberOfSubstrings = 0;\n int beg = 0;\n int end = 0;\n while (end < len) {\n end = str.indexOf(separator, beg);\n if (end > -1) {\n if (end > beg) {\n numberOfSubstrings += 1;\n if (numberOfSubstrings == max) {\n end = len;\n substrings.add(str.substring(beg));\n } else {\n // The following is OK, because String.substring( beg, end ) excludes\n // the character at the position 'end'.\n substrings.add(str.substring(beg, end));\n // Set the starting point for the next search.\n // The following is equivalent to beg = end + (separatorLength - 1) + 1,\n // which is the right calculation:\n beg = end + separatorLength;\n }\n } else {\n // We found a consecutive occurrence of the separator, so skip it.\n if (preserveAllTokens) {\n numberOfSubstrings += 1;\n if (numberOfSubstrings == max) {\n end = len;\n substrings.add(str.substring(beg));\n } else {\n substrings.add(StringUtils.EMPTY);\n }\n }\n beg = end + separatorLength;\n }\n } else {\n // String.substring( beg ) goes from 'beg' to the end of the String.\n substrings.add(str.substring(beg));\n end = len;\n }\n }\n return substrings.toArray(new String[0]);\n }\n // -----------------------------------------------------------------------\n\n /**\n *

          Splits the provided text into an array, using whitespace as the\n * separator, preserving all tokens, including empty tokens created by\n * adjacent separators. This is an alternative to using StringTokenizer.\n * Whitespace is defined by {@link Character#isWhitespace(char)}.

          \n *\n *

          The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

          \n *\n *

          A null input String returns null.

          \n *\n *
          \n     * StringUtils.splitPreserveAllTokens(null)       = null\n     * StringUtils.splitPreserveAllTokens(\"\")         = []\n     * StringUtils.splitPreserveAllTokens(\"abc def\")  = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc  def\") = [\"abc\", \"\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\" abc \")    = [\"\", \"abc\", \"\"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str) {\n return StringUtils.splitWorker(str, null, -1, true);\n }\n\n /**\n *

          Splits the provided text into an array, separator specified,\n * preserving all tokens, including empty tokens created by adjacent\n * separators. This is an alternative to using StringTokenizer.

          \n *\n *

          The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

          \n *\n *

          A null input String returns null.

          \n *\n *
          \n     * StringUtils.splitPreserveAllTokens(null, *)         = null\n     * StringUtils.splitPreserveAllTokens(\"\", *)           = []\n     * StringUtils.splitPreserveAllTokens(\"a.b.c\", '.')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a..b.c\", '.')   = [\"a\", \"\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a:b:c\", '.')    = [\"a:b:c\"]\n     * StringUtils.splitPreserveAllTokens(\"a\\tb\\nc\", null) = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c\", ' ')    = [\"a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c \", ' ')   = [\"a\", \"b\", \"c\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"a b c  \", ' ')   = [\"a\", \"b\", \"c\", \"\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\" a b c\", ' ')   = [\"\", a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\"  a b c\", ' ')  = [\"\", \"\", a\", \"b\", \"c\"]\n     * StringUtils.splitPreserveAllTokens(\" a b c \", ' ')  = [\"\", a\", \"b\", \"c\", \"\"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @param separatorChar the character used as the delimiter,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final char separatorChar) {\n return StringUtils.splitWorker(str, separatorChar, true);\n }\n\n /**\n * Performs the logic for the split and\n * splitPreserveAllTokens methods that do not return a\n * maximum array length.\n *\n * @param str the String to parse, may be null\n * @param separatorChar the separate character\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n */\n private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n List list = new ArrayList<>();\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n while (i < len) {\n if (str.charAt(i) == separatorChar) {\n if (match || preserveAllTokens) {\n list.add(str.substring(start, i));\n match = false;\n lastMatch = true;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[0]);\n }\n\n /**\n *

          Splits the provided text into an array, separators specified,\n * preserving all tokens, including empty tokens created by adjacent\n * separators. This is an alternative to using StringTokenizer.

          \n *\n *

          The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * For more control over the split use the StrTokenizer class.

          \n *\n *

          A null input String returns null.\n * A null separatorChars splits on whitespace.

          \n *\n *
          \n     * StringUtils.splitPreserveAllTokens(null, *)           = null\n     * StringUtils.splitPreserveAllTokens(\"\", *)             = []\n     * StringUtils.splitPreserveAllTokens(\"abc def\", null)   = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc def\", \" \")    = [\"abc\", \"def\"]\n     * StringUtils.splitPreserveAllTokens(\"abc  def\", \" \")   = [\"abc\", \"\", def\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\")   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef:\", \":\")  = [\"ab\", \"cd\", \"ef\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef::\", \":\") = [\"ab\", \"cd\", \"ef\", \"\", \"\"]\n     * StringUtils.splitPreserveAllTokens(\"ab::cd:ef\", \":\")  = [\"ab\", \"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\":cd:ef\", \":\")     = [\"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"::cd:ef\", \":\")    = [\"\", \"\", cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\":cd:ef:\", \":\")    = [\"\", cd\", \"ef\", \"\"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final String separatorChars) {\n return StringUtils.splitWorker(str, separatorChars, -1, true);\n }\n\n /**\n *

          Splits the provided text into an array with a maximum length,\n * separators specified, preserving all tokens, including empty tokens\n * created by adjacent separators.

          \n *\n *

          The separator is not included in the returned String array.\n * Adjacent separators are treated as separators for empty tokens.\n * Adjacent separators are treated as one separator.

          \n *\n *

          A null input String returns null.\n * A null separatorChars splits on whitespace.

          \n *\n *

          If more than max delimited substrings are found, the last\n * returned string includes all characters after the first max - 1\n * returned strings (including separator characters).

          \n *\n *
          \n     * StringUtils.splitPreserveAllTokens(null, *, *)            = null\n     * StringUtils.splitPreserveAllTokens(\"\", *, *)              = []\n     * StringUtils.splitPreserveAllTokens(\"ab de fg\", null, 0)   = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 0) = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\", 0)    = [\"ab\", \"cd\", \"ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab:cd:ef\", \":\", 2)    = [\"ab\", \"cd:ef\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 2) = [\"ab\", \"  de fg\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 3) = [\"ab\", \"\", \" de fg\"]\n     * StringUtils.splitPreserveAllTokens(\"ab   de fg\", null, 4) = [\"ab\", \"\", \"\", \"de fg\"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters,\n * null splits on whitespace\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit\n * @return an array of parsed Strings, null if null String input\n * @since 2.1\n */\n public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) {\n return StringUtils.splitWorker(str, separatorChars, max, true);\n }\n\n /**\n * Performs the logic for the split and\n * splitPreserveAllTokens methods that return a maximum array\n * length.\n *\n * @param str the String to parse, may be null\n * @param separatorChars the separate character\n * @param max the maximum number of elements to include in the\n * array. A zero or negative value implies no limit.\n * @param preserveAllTokens if true, adjacent separators are\n * treated as empty token separators; if false, adjacent\n * separators are treated as one separator.\n * @return an array of parsed Strings, null if null String input\n */\n private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) {\n // Performance tuned for 2.0 (JDK1.4)\n // Direct code is quicker than StringTokenizer.\n // Also, StringTokenizer uses isSpace() not isWhitespace()\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n List list = new ArrayList<>();\n int sizePlus1 = 1;\n int i = 0, start = 0;\n boolean match = false;\n boolean lastMatch = false;\n if (separatorChars == null) {\n // Null separator means use whitespace\n while (i < len) {\n if (Character.isWhitespace(str.charAt(i))) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else if (separatorChars.length() == 1) {\n // Optimise 1 character case\n char sep = separatorChars.charAt(0);\n while (i < len) {\n if (str.charAt(i) == sep) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n } else {\n // standard case\n while (i < len) {\n if (separatorChars.indexOf(str.charAt(i)) >= 0) {\n if (match || preserveAllTokens) {\n lastMatch = true;\n if (sizePlus1++ == max) {\n i = len;\n lastMatch = false;\n }\n list.add(str.substring(start, i));\n match = false;\n }\n start = ++i;\n continue;\n }\n lastMatch = false;\n match = true;\n i++;\n }\n }\n if (match || preserveAllTokens && lastMatch) {\n list.add(str.substring(start, i));\n }\n return list.toArray(new String[0]);\n }\n\n /**\n *

          Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens.\n *

          \n     * StringUtils.splitByCharacterType(null)         = null\n     * StringUtils.splitByCharacterType(\"\")           = []\n     * StringUtils.splitByCharacterType(\"ab de fg\")   = [\"ab\", \" \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterType(\"ab   de fg\") = [\"ab\", \"   \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterType(\"ab:cd:ef\")   = [\"ab\", \":\", \"cd\", \":\", \"ef\"]\n     * StringUtils.splitByCharacterType(\"number5\")    = [\"number\", \"5\"]\n     * StringUtils.splitByCharacterType(\"fooBar\")     = [\"foo\", \"B\", \"ar\"]\n     * StringUtils.splitByCharacterType(\"foo200Bar\")  = [\"foo\", \"200\", \"B\", \"ar\"]\n     * StringUtils.splitByCharacterType(\"ASFRules\")   = [\"ASFR\", \"ules\"]\n     * 
          \n * @param str the String to split, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n public static String[] splitByCharacterType(final String str) {\n return StringUtils.splitByCharacterType(str, false);\n }\n\n /**\n *

          Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens, with the\n * following exception: the character of type\n * Character.UPPERCASE_LETTER, if any, immediately\n * preceding a token of type Character.LOWERCASE_LETTER\n * will belong to the following token rather than to the preceding, if any,\n * Character.UPPERCASE_LETTER token.\n *

          \n     * StringUtils.splitByCharacterTypeCamelCase(null)         = null\n     * StringUtils.splitByCharacterTypeCamelCase(\"\")           = []\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab de fg\")   = [\"ab\", \" \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab   de fg\") = [\"ab\", \"   \", \"de\", \" \", \"fg\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ab:cd:ef\")   = [\"ab\", \":\", \"cd\", \":\", \"ef\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"number5\")    = [\"number\", \"5\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"fooBar\")     = [\"foo\", \"Bar\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"foo200Bar\")  = [\"foo\", \"200\", \"Bar\"]\n     * StringUtils.splitByCharacterTypeCamelCase(\"ASFRules\")   = [\"ASF\", \"Rules\"]\n     * 
          \n * @param str the String to split, may be null\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n public static String[] splitByCharacterTypeCamelCase(final String str) {\n return StringUtils.splitByCharacterType(str, true);\n }\n\n /**\n *

          Splits a String by Character type as returned by\n * java.lang.Character.getType(char). Groups of contiguous\n * characters of the same type are returned as complete tokens, with the\n * following exception: if camelCase is true,\n * the character of type Character.UPPERCASE_LETTER, if any,\n * immediately preceding a token of type Character.LOWERCASE_LETTER\n * will belong to the following token rather than to the preceding, if any,\n * Character.UPPERCASE_LETTER token.\n * @param str the String to split, may be null\n * @param camelCase whether to use so-called \"camel-case\" for letter types\n * @return an array of parsed Strings, null if null String input\n * @since 2.4\n */\n private static String[] splitByCharacterType(final String str, final boolean camelCase) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n char[] c = str.toCharArray();\n List list = new ArrayList();\n int tokenStart = 0;\n int currentType = Character.getType(c[tokenStart]);\n for (int pos = tokenStart + 1; pos < c.length; pos++) {\n int type = Character.getType(c[pos]);\n if (type == currentType) {\n continue;\n }\n if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) {\n int newTokenStart = pos - 1;\n if (newTokenStart != tokenStart) {\n list.add(new String(c, tokenStart, newTokenStart - tokenStart));\n tokenStart = newTokenStart;\n }\n } else {\n list.add(new String(c, tokenStart, pos - tokenStart));\n tokenStart = pos;\n }\n currentType = type;\n }\n list.add(new String(c, tokenStart, c.length - tokenStart));\n return list.toArray(new String[0]);\n }\n // Joining\n //-----------------------------------------------------------------------\n\n /**\n *

          Joins the elements of the provided array into a single String\n * containing the provided list of elements.

          \n *\n *

          No separator is added to the joined String.\n * Null objects or empty strings within the array are represented by\n * empty strings.

          \n *\n *
          \n     * StringUtils.join(null)            = null\n     * StringUtils.join([])              = \"\"\n     * StringUtils.join([null])          = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"]) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"]) = \"a\"\n     * 
          \n *\n * @param array the array of values to join together, may be null\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array) {\n return StringUtils.join(array, null);\n }\n\n /**\n *

          Joins the elements of the provided array into a single String\n * containing the provided list of elements.

          \n *\n *

          No delimiter is added before or after the list.\n * Null objects or empty strings within the array are represented by\n * empty strings.

          \n *\n *
          \n     * StringUtils.join(null, *)               = null\n     * StringUtils.join([], *)                 = \"\"\n     * StringUtils.join([null], *)             = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], ';')  = \"a;b;c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ';')  = \";;a\"\n     * 
          \n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array, final char separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array, separator, 0, array.length);\n }\n\n /**\n *

          Joins the elements of the provided array into a single String\n * containing the provided list of elements.

          \n *\n *

          No delimiter is added before or after the list.\n * Null objects or empty strings within the array are represented by\n * empty strings.

          \n *\n *
          \n     * StringUtils.join(null, *)               = null\n     * StringUtils.join([], *)                 = \"\"\n     * StringUtils.join([null], *)             = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], ';')  = \"a;b;c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null) = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ';')  = \";;a\"\n     * 
          \n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use\n * @param startIndex the first index to start joining from. It is\n * an error to pass in an end index past the end of the array\n * @param endIndex the index to stop joining from (exclusive). It is\n * an error to pass in an end index past the end of the array\n * @return the joined String, null if null array input\n * @since 2.0\n */\n public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) {\n if (array == null) {\n return null;\n }\n int bufSize = endIndex - startIndex;\n if (bufSize <= 0) {\n return StringUtils.EMPTY;\n }\n bufSize *= (array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1;\n StringBuilder buf = new StringBuilder(bufSize);\n for (int i = startIndex; i < endIndex; i++) {\n if (i > startIndex) {\n buf.append(separator);\n }\n if (array[i] != null) {\n buf.append(array[i]);\n }\n }\n return buf.toString();\n }\n\n /**\n *

          Joins the elements of the provided array into a single String\n * containing the provided list of elements.

          \n *\n *

          No delimiter is added before or after the list.\n * A null separator is the same as an empty String (\"\").\n * Null objects or empty strings within the array are represented by\n * empty strings.

          \n *\n *
          \n     * StringUtils.join(null, *)                = null\n     * StringUtils.join([], *)                  = \"\"\n     * StringUtils.join([null], *)              = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"--\")  = \"a--b--c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null)  = \"abc\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"\")    = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ',')   = \",,a\"\n     * 
          \n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use, null treated as \"\"\n * @return the joined String, null if null array input\n */\n public static String join(final Object[] array, final String separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array, separator, 0, array.length);\n }\n\n /**\n *

          Joins the elements of the provided array into a single String\n * containing the provided list of elements.

          \n *\n *

          No delimiter is added before or after the list.\n * A null separator is the same as an empty String (\"\").\n * Null objects or empty strings within the array are represented by\n * empty strings.

          \n *\n *
          \n     * StringUtils.join(null, *)                = null\n     * StringUtils.join([], *)                  = \"\"\n     * StringUtils.join([null], *)              = \"\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"--\")  = \"a--b--c\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], null)  = \"abc\"\n     * StringUtils.join([\"a\", \"b\", \"c\"], \"\")    = \"abc\"\n     * StringUtils.join([null, \"\", \"a\"], ',')   = \",,a\"\n     * 
          \n *\n * @param array the array of values to join together, may be null\n * @param separator the separator character to use, null treated as \"\"\n * @param startIndex the first index to start joining from. It is\n * an error to pass in an end index past the end of the array\n * @param endIndex the index to stop joining from (exclusive). It is\n * an error to pass in an end index past the end of the array\n * @return the joined String, null if null array input\n */\n public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {\n if (array == null) {\n return null;\n }\n if (separator == null) {\n separator = StringUtils.EMPTY;\n }\n // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))\n // (Assuming that all Strings are roughly equally long)\n int bufSize = endIndex - startIndex;\n if (bufSize <= 0) {\n return StringUtils.EMPTY;\n }\n bufSize *= (array[startIndex] == null ? 16 : array[startIndex].toString().length()) + separator.length();\n StringBuilder buf = new StringBuilder(bufSize);\n for (int i = startIndex; i < endIndex; i++) {\n if (i > startIndex) {\n buf.append(separator);\n }\n if (array[i] != null) {\n buf.append(array[i]);\n }\n }\n return buf.toString();\n }\n // Delete\n //-----------------------------------------------------------------------\n\n /**\n *

          Deletes all whitespaces from a String as defined by\n * {@link Character#isWhitespace(char)}.

          \n *\n *
          \n     * StringUtils.deleteWhitespace(null)         = null\n     * StringUtils.deleteWhitespace(\"\")           = \"\"\n     * StringUtils.deleteWhitespace(\"abc\")        = \"abc\"\n     * StringUtils.deleteWhitespace(\"   ab  c  \") = \"abc\"\n     * 
          \n *\n * @param str the String to delete whitespace from, may be null\n * @return the String without whitespaces, null if null String input\n */\n public static String deleteWhitespace(final String str) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n int sz = str.length();\n char[] chs = new char[sz];\n int count = 0;\n for (int i = 0; i < sz; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n chs[count++] = str.charAt(i);\n }\n }\n if (count == sz) {\n return str;\n }\n return new String(chs, 0, count);\n }\n // Remove\n //-----------------------------------------------------------------------\n\n /**\n *

          Removes a substring only if it is at the begining of a source string,\n * otherwise returns the source string.

          \n *\n *

          A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

          \n *\n *
          \n     * StringUtils.removeStart(null, *)      = null\n     * StringUtils.removeStart(\"\", *)        = \"\"\n     * StringUtils.removeStart(*, null)      = *\n     * StringUtils.removeStart(\"www.domain.com\", \"www.\")   = \"domain.com\"\n     * StringUtils.removeStart(\"domain.com\", \"www.\")       = \"domain.com\"\n     * StringUtils.removeStart(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeStart(\"abc\", \"\")    = \"abc\"\n     * 
          \n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String removeStart(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (str.startsWith(remove)) {\n return str.substring(remove.length());\n }\n return str;\n }\n\n /**\n *

          Case insensitive removal of a substring if it is at the begining of a source string,\n * otherwise returns the source string.

          \n *\n *

          A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

          \n *\n *
          \n     * StringUtils.removeStartIgnoreCase(null, *)      = null\n     * StringUtils.removeStartIgnoreCase(\"\", *)        = \"\"\n     * StringUtils.removeStartIgnoreCase(*, null)      = *\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"www.\")   = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"WWW.\")   = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"domain.com\", \"www.\")       = \"domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeStartIgnoreCase(\"abc\", \"\")    = \"abc\"\n     * 
          \n *\n * @param str the source String to search, may be null\n * @param remove the String to search for (case insensitive) and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.4\n */\n public static String removeStartIgnoreCase(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (StringUtils.startsWithIgnoreCase(str, remove)) {\n return str.substring(remove.length());\n }\n return str;\n }\n\n /**\n *

          Removes a substring only if it is at the end of a source string,\n * otherwise returns the source string.

          \n *\n *

          A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

          \n *\n *
          \n     * StringUtils.removeEnd(null, *)      = null\n     * StringUtils.removeEnd(\"\", *)        = \"\"\n     * StringUtils.removeEnd(*, null)      = *\n     * StringUtils.removeEnd(\"www.domain.com\", \".com.\")  = \"www.domain.com\"\n     * StringUtils.removeEnd(\"www.domain.com\", \".com\")   = \"www.domain\"\n     * StringUtils.removeEnd(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeEnd(\"abc\", \"\")    = \"abc\"\n     * 
          \n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String removeEnd(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (str.endsWith(remove)) {\n return str.substring(0, str.length() - remove.length());\n }\n return str;\n }\n\n /**\n *

          Case insensitive removal of a substring if it is at the end of a source string,\n * otherwise returns the source string.

          \n *\n *

          A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null search string will return the source string.

          \n *\n *
          \n     * StringUtils.removeEndIgnoreCase(null, *)      = null\n     * StringUtils.removeEndIgnoreCase(\"\", *)        = \"\"\n     * StringUtils.removeEndIgnoreCase(*, null)      = *\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".com.\")  = \"www.domain.com\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".com\")   = \"www.domain\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \"domain\") = \"www.domain.com\"\n     * StringUtils.removeEndIgnoreCase(\"abc\", \"\")    = \"abc\"\n     * StringUtils.removeEndIgnoreCase(\"www.domain.com\", \".COM\") = \"www.domain\")\n     * StringUtils.removeEndIgnoreCase(\"www.domain.COM\", \".com\") = \"www.domain\")\n     * 
          \n *\n * @param str the source String to search, may be null\n * @param remove the String to search for (case insensitive) and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.4\n */\n public static String removeEndIgnoreCase(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n if (StringUtils.endsWithIgnoreCase(str, remove)) {\n return str.substring(0, str.length() - remove.length());\n }\n return str;\n }\n\n /**\n *

          Removes all occurrences of a substring from within the source string.

          \n *\n *

          A null source string will return null.\n * An empty (\"\") source string will return the empty string.\n * A null remove string will return the source string.\n * An empty (\"\") remove string will return the source string.

          \n *\n *
          \n     * StringUtils.remove(null, *)        = null\n     * StringUtils.remove(\"\", *)          = \"\"\n     * StringUtils.remove(*, null)        = *\n     * StringUtils.remove(*, \"\")          = *\n     * StringUtils.remove(\"queued\", \"ue\") = \"qd\"\n     * StringUtils.remove(\"queued\", \"zz\") = \"queued\"\n     * 
          \n *\n * @param str the source String to search, may be null\n * @param remove the String to search for and remove, may be null\n * @return the substring with the string removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String remove(final String str, final String remove) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) {\n return str;\n }\n return StringUtils.replace(str, remove, StringUtils.EMPTY, -1);\n }\n\n /**\n *

          Removes all occurrences of a character from within the source string.

          \n *\n *

          A null source string will return null.\n * An empty (\"\") source string will return the empty string.

          \n *\n *
          \n     * StringUtils.remove(null, *)       = null\n     * StringUtils.remove(\"\", *)         = \"\"\n     * StringUtils.remove(\"queued\", 'u') = \"qeed\"\n     * StringUtils.remove(\"queued\", 'z') = \"queued\"\n     * 
          \n *\n * @param str the source String to search, may be null\n * @param remove the char to search for and remove, may be null\n * @return the substring with the char removed if found,\n * null if null String input\n * @since 2.1\n */\n public static String remove(final String str, final char remove) {\n if (StringUtils.isEmpty(str) || str.indexOf(remove) == StringUtils.INDEX_NOT_FOUND) {\n return str;\n }\n char[] chars = str.toCharArray();\n int pos = 0;\n for (int i = 0; i < chars.length; i++) {\n if (chars[i] != remove) {\n chars[pos++] = chars[i];\n }\n }\n return new String(chars, 0, pos);\n }\n // Replacing\n //-----------------------------------------------------------------------\n\n /**\n *

          Replaces a String with another String inside a larger String, once.

          \n *\n *

          A null reference passed to this method is a no-op.

          \n *\n *
          \n     * StringUtils.replaceOnce(null, *, *)        = null\n     * StringUtils.replaceOnce(\"\", *, *)          = \"\"\n     * StringUtils.replaceOnce(\"any\", null, *)    = \"any\"\n     * StringUtils.replaceOnce(\"any\", *, null)    = \"any\"\n     * StringUtils.replaceOnce(\"any\", \"\", *)      = \"any\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", null)  = \"aba\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", \"\")    = \"ba\"\n     * StringUtils.replaceOnce(\"aba\", \"a\", \"z\")   = \"zba\"\n     * 
          \n *\n * @see #replace(String text, String searchString, String replacement, int max)\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace with, may be null\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replaceOnce(final String text, final String searchString, final String replacement) {\n return StringUtils.replace(text, searchString, replacement, 1);\n }\n\n /**\n *

          Replaces all occurrences of a String within another String.

          \n *\n *

          A null reference passed to this method is a no-op.

          \n *\n *
          \n     * StringUtils.replace(null, *, *)        = null\n     * StringUtils.replace(\"\", *, *)          = \"\"\n     * StringUtils.replace(\"any\", null, *)    = \"any\"\n     * StringUtils.replace(\"any\", *, null)    = \"any\"\n     * StringUtils.replace(\"any\", \"\", *)      = \"any\"\n     * StringUtils.replace(\"aba\", \"a\", null)  = \"aba\"\n     * StringUtils.replace(\"aba\", \"a\", \"\")    = \"b\"\n     * StringUtils.replace(\"aba\", \"a\", \"z\")   = \"zbz\"\n     * 
          \n *\n * @see #replace(String text, String searchString, String replacement, int max)\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace it with, may be null\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replace(final String text, final String searchString, final String replacement) {\n return StringUtils.replace(text, searchString, replacement, -1);\n }\n\n /**\n *

          Replaces a String with another String inside a larger String,\n * for the first max values of the search String.

          \n *\n *

          A null reference passed to this method is a no-op.

          \n *\n *
          \n     * StringUtils.replace(null, *, *, *)         = null\n     * StringUtils.replace(\"\", *, *, *)           = \"\"\n     * StringUtils.replace(\"any\", null, *, *)     = \"any\"\n     * StringUtils.replace(\"any\", *, null, *)     = \"any\"\n     * StringUtils.replace(\"any\", \"\", *, *)       = \"any\"\n     * StringUtils.replace(\"any\", *, *, 0)        = \"any\"\n     * StringUtils.replace(\"abaa\", \"a\", null, -1) = \"abaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"\", -1)   = \"b\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 0)   = \"abaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 1)   = \"zbaa\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", 2)   = \"zbza\"\n     * StringUtils.replace(\"abaa\", \"a\", \"z\", -1)  = \"zbzz\"\n     * 
          \n *\n * @param text text to search and replace in, may be null\n * @param searchString the String to search for, may be null\n * @param replacement the String to replace it with, may be null\n * @param max maximum number of values to replace, or -1 if no maximum\n * @return the text with any replacements processed,\n * null if null String input\n */\n public static String replace(final String text, final String searchString, final String replacement, int max) {\n if (StringUtils.isEmpty(text) || StringUtils.isEmpty(searchString) || replacement == null || max == 0) {\n return text;\n }\n int start = 0;\n int end = text.indexOf(searchString, start);\n if (end == StringUtils.INDEX_NOT_FOUND) {\n return text;\n }\n int replLength = searchString.length();\n int increase = replacement.length() - replLength;\n increase = Math.max(increase, 0);\n increase *= max < 0 ? 16 : Math.min(max, 64);\n StringBuilder buf = new StringBuilder(text.length() + increase);\n while (end != StringUtils.INDEX_NOT_FOUND) {\n buf.append(text.substring(start, end)).append(replacement);\n start = end + replLength;\n if (--max == 0) {\n break;\n }\n end = text.indexOf(searchString, start);\n }\n buf.append(text.substring(start));\n return buf.toString();\n }\n\n /**\n *

          \n * Replaces all occurrences of Strings within another String.\n *

          \n *\n *

          \n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored. This will not repeat. For repeating replaces, call the\n * overloaded method.\n *

          \n *\n *
          \n     *  StringUtils.replaceEach(null, *, *)        = null\n     *  StringUtils.replaceEach(\"\", *, *)          = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0]) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null)  = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"})  = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"})  = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"})  = \"wcte\"\n     *  (example of how it does not repeat)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"})  = \"dcte\"\n     * 
          \n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) {\n return StringUtils.replaceEach(text, searchList, replacementList, false, 0);\n }\n\n /**\n *

          \n * Replaces all occurrences of Strings within another String.\n *

          \n *\n *

          \n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored. This will not repeat. For repeating replaces, call the\n * overloaded method.\n *

          \n *\n *
          \n     *  StringUtils.replaceEach(null, *, *, *) = null\n     *  StringUtils.replaceEach(\"\", *, *, *) = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0], *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"}, *) = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"}, *) = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"}, *) = \"wcte\"\n     *  (example of how it repeats)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, false) = \"dcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, true) = \"tcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, true) = IllegalArgumentException\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, false) = \"dcabe\"\n     * 
          \n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IllegalArgumentException\n * if the search is repeating and there is an endless loop due\n * to outputs of one being inputs to another\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) {\n // timeToLive should be 0 if not used or nothing to replace, else it's\n // the length of the replace array\n int timeToLive = searchList == null ? 0 : searchList.length;\n return StringUtils.replaceEach(text, searchList, replacementList, true, timeToLive);\n }\n\n /**\n *

          \n * Replaces all occurrences of Strings within another String.\n *

          \n *\n *

          \n * A null reference passed to this method is a no-op, or if\n * any \"search string\" or \"string to replace\" is null, that replace will be\n * ignored.\n *

          \n *\n *
          \n     *  StringUtils.replaceEach(null, *, *, *) = null\n     *  StringUtils.replaceEach(\"\", *, *, *) = \"\"\n     *  StringUtils.replaceEach(\"aba\", null, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[0], null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", null, new String[0], *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, null, *) = \"aba\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{\"a\"}, new String[]{\"\"}, *) = \"b\"\n     *  StringUtils.replaceEach(\"aba\", new String[]{null}, new String[]{\"a\"}, *) = \"aba\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"w\", \"t\"}, *) = \"wcte\"\n     *  (example of how it repeats)\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, false) = \"dcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"t\"}, true) = \"tcte\"\n     *  StringUtils.replaceEach(\"abcde\", new String[]{\"ab\", \"d\"}, new String[]{\"d\", \"ab\"}, *) = IllegalArgumentException\n     * 
          \n *\n * @param text\n * text to search and replace in, no-op if null\n * @param searchList\n * the Strings to search for, no-op if null\n * @param replacementList\n * the Strings to replace them with, no-op if null\n * @param repeat if true, then replace repeatedly\n * until there are no more possible replacements or timeToLive < 0\n * @param timeToLive\n * if less than 0 then there is a circular reference and endless\n * loop\n * @return the text with any replacements processed, null if\n * null String input\n * @throws IllegalArgumentException\n * if the search is repeating and there is an endless loop due\n * to outputs of one being inputs to another\n * @throws IndexOutOfBoundsException\n * if the lengths of the arrays are not the same (null is ok,\n * and/or size 0)\n * @since 2.4\n */\n private static String replaceEach(final String text, final String[] searchList, final String[] replacementList, final boolean repeat, final int timeToLive) {\n // mchyzer Performance note: This creates very few new objects (one major goal)\n // let me know if there are performance requests, we can create a harness to measure\n if (text == null || text.length() == 0 || searchList == null || searchList.length == 0 || replacementList == null || replacementList.length == 0) {\n return text;\n }\n // if recursing, this shouldnt be less than 0\n if (timeToLive < 0) {\n throw new IllegalStateException(\"TimeToLive of \" + timeToLive + \" is less than 0: \" + text);\n }\n int searchLength = searchList.length;\n int replacementLength = replacementList.length;\n // make sure lengths are ok, these need to be equal\n if (searchLength != replacementLength) {\n throw new IllegalArgumentException(\"Search and Replace array lengths don't match: \" + searchLength + \" vs \" + replacementLength);\n }\n // keep track of which still have matches\n boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];\n // index on index that the match was found\n int textIndex = -1;\n int replaceIndex = -1;\n int tempIndex = -1;\n // index of replace array that will replace the search string found\n // NOTE: logic duplicated below START\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) {\n continue;\n }\n tempIndex = text.indexOf(searchList[i]);\n // see if we need to keep searching for this\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n // NOTE: logic mostly below END\n // no search strings found, we are done\n if (textIndex == -1) {\n return text;\n }\n int start = 0;\n // get a good guess on the size of the result buffer so it doesnt have to double if it goes over a bit\n int increase = 0;\n // count the replacement text elements that are larger than their corresponding text being replaced\n for (int i = 0; i < searchList.length; i++) {\n if (searchList[i] == null || replacementList[i] == null) {\n continue;\n }\n int greater = replacementList[i].length() - searchList[i].length();\n if (greater > 0) {\n increase += 3 * greater; // assume 3 matches\n }\n }\n // have upper-bound at 20% increase, then let Java take over\n increase = Math.min(increase, text.length() / 5);\n StringBuilder buf = new StringBuilder(text.length() + increase);\n while (textIndex != -1) {\n for (int i = start; i < textIndex; i++) {\n buf.append(text.charAt(i));\n }\n buf.append(replacementList[replaceIndex]);\n start = textIndex + searchList[replaceIndex].length();\n textIndex = -1;\n replaceIndex = -1;\n tempIndex = -1;\n // find the next earliest match\n // NOTE: logic mostly duplicated above START\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) {\n continue;\n }\n tempIndex = text.indexOf(searchList[i], start);\n // see if we need to keep searching for this\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n // NOTE: logic duplicated above END\n }\n int textLength = text.length();\n for (int i = start; i < textLength; i++) {\n buf.append(text.charAt(i));\n }\n String result = buf.toString();\n if (!repeat) {\n return result;\n }\n return StringUtils.replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);\n }\n // Replace, character based\n //-----------------------------------------------------------------------\n\n /**\n *

          Replaces all occurrences of a character in a String with another.\n * This is a null-safe version of {@link String#replace(char, char)}.

          \n *\n *

          A null string input returns null.\n * An empty (\"\") string input returns an empty string.

          \n *\n *
          \n     * StringUtils.replaceChars(null, *, *)        = null\n     * StringUtils.replaceChars(\"\", *, *)          = \"\"\n     * StringUtils.replaceChars(\"abcba\", 'b', 'y') = \"aycya\"\n     * StringUtils.replaceChars(\"abcba\", 'z', 'y') = \"abcba\"\n     * 
          \n *\n * @param str String to replace characters in, may be null\n * @param searchChar the character to search for, may be null\n * @param replaceChar the character to replace, may be null\n * @return modified String, null if null string input\n * @since 2.0\n */\n public static String replaceChars(final String str, final char searchChar, final char replaceChar) {\n if (str == null) {\n return null;\n }\n return str.replace(searchChar, replaceChar);\n }\n\n /**\n *

          Replaces multiple characters in a String in one go.\n * This method can also be used to delete characters.

          \n *\n *

          For example:
          \n * replaceChars("hello", "ho", "jy") = jelly.

          \n *\n *

          A null string input returns null.\n * An empty (\"\") string input returns an empty string.\n * A null or empty set of search characters returns the input string.

          \n *\n *

          The length of the search characters should normally equal the length\n * of the replace characters.\n * If the search characters is longer, then the extra search characters\n * are deleted.\n * If the search characters is shorter, then the extra replace characters\n * are ignored.

          \n *\n *
          \n     * StringUtils.replaceChars(null, *, *)           = null\n     * StringUtils.replaceChars(\"\", *, *)             = \"\"\n     * StringUtils.replaceChars(\"abc\", null, *)       = \"abc\"\n     * StringUtils.replaceChars(\"abc\", \"\", *)         = \"abc\"\n     * StringUtils.replaceChars(\"abc\", \"b\", null)     = \"ac\"\n     * StringUtils.replaceChars(\"abc\", \"b\", \"\")       = \"ac\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"yz\")  = \"ayzya\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"y\")   = \"ayya\"\n     * StringUtils.replaceChars(\"abcba\", \"bc\", \"yzx\") = \"ayzya\"\n     * 
          \n *\n * @param str String to replace characters in, may be null\n * @param searchChars a set of characters to search for, may be null\n * @param replaceChars a set of characters to replace, may be null\n * @return modified String, null if null string input\n * @since 2.0\n */\n public static String replaceChars(final String str, final String searchChars, String replaceChars) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) {\n return str;\n }\n if (replaceChars == null) {\n replaceChars = StringUtils.EMPTY;\n }\n boolean modified = false;\n int replaceCharsLength = replaceChars.length();\n int strLength = str.length();\n StringBuilder buf = new StringBuilder(strLength);\n for (int i = 0; i < strLength; i++) {\n char ch = str.charAt(i);\n int index = searchChars.indexOf(ch);\n if (index >= 0) {\n modified = true;\n if (index < replaceCharsLength) {\n buf.append(replaceChars.charAt(index));\n }\n } else {\n buf.append(ch);\n }\n }\n if (modified) {\n return buf.toString();\n }\n return str;\n }\n // Overlay\n //-----------------------------------------------------------------------\n\n /**\n *

          Overlays part of a String with another String.

          \n *\n *

          A null string input returns null.\n * A negative index is treated as zero.\n * An index greater than the string length is treated as the string length.\n * The start index is always the smaller of the two indices.

          \n *\n *
          \n     * StringUtils.overlay(null, *, *, *)            = null\n     * StringUtils.overlay(\"\", \"abc\", 0, 0)          = \"abc\"\n     * StringUtils.overlay(\"abcdef\", null, 2, 4)     = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"\", 2, 4)       = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"\", 4, 2)       = \"abef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 2, 4)   = \"abzzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 4, 2)   = \"abzzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", -1, 4)  = \"zzzzef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 2, 8)   = \"abzzzz\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", -2, -3) = \"zzzzabcdef\"\n     * StringUtils.overlay(\"abcdef\", \"zzzz\", 8, 10)  = \"abcdefzzzz\"\n     * 
          \n *\n * @param str the String to do overlaying in, may be null\n * @param overlay the String to overlay, may be null\n * @param start the position to start overlaying at\n * @param end the position to stop overlaying before\n * @return overlayed String, null if null String input\n * @since 2.0\n */\n public static String overlay(final String str, String overlay, int start, int end) {\n if (str == null) {\n return null;\n }\n if (overlay == null) {\n overlay = StringUtils.EMPTY;\n }\n int len = str.length();\n if (start < 0) {\n start = 0;\n }\n if (start > len) {\n start = len;\n }\n if (end < 0) {\n end = 0;\n }\n if (end > len) {\n end = len;\n }\n if (start > end) {\n int temp = start;\n start = end;\n end = temp;\n }\n return str.substring(0, start) + overlay + str.substring(end);\n }\n // Chomping\n //-----------------------------------------------------------------------\n\n /**\n *

          Removes one newline from end of a String if it's there,\n * otherwise leave it alone. A newline is "\\n",\n * "\\r", or "\\r\\n".

          \n *\n *

          NOTE: This method changed in 2.0.\n * It now more closely matches Perl chomp.

          \n *\n *
          \n     * StringUtils.chomp(null)          = null\n     * StringUtils.chomp(\"\")            = \"\"\n     * StringUtils.chomp(\"abc \\r\")      = \"abc \"\n     * StringUtils.chomp(\"abc\\n\")       = \"abc\"\n     * StringUtils.chomp(\"abc\\r\\n\")     = \"abc\"\n     * StringUtils.chomp(\"abc\\r\\n\\r\\n\") = \"abc\\r\\n\"\n     * StringUtils.chomp(\"abc\\n\\r\")     = \"abc\\n\"\n     * StringUtils.chomp(\"abc\\n\\rabc\")  = \"abc\\n\\rabc\"\n     * StringUtils.chomp(\"\\r\")          = \"\"\n     * StringUtils.chomp(\"\\n\")          = \"\"\n     * StringUtils.chomp(\"\\r\\n\")        = \"\"\n     * 
          \n *\n * @param str the String to chomp a newline from, may be null\n * @return String without newline, null if null String input\n */\n public static String chomp(final String str) {\n if (StringUtils.isEmpty(str)) {\n return str;\n }\n if (str.length() == 1) {\n char ch = str.charAt(0);\n if (ch == CharUtils.CR || ch == CharUtils.LF) {\n return StringUtils.EMPTY;\n }\n return str;\n }\n int lastIdx = str.length() - 1;\n char last = str.charAt(lastIdx);\n if (last == CharUtils.LF) {\n if (str.charAt(lastIdx - 1) == CharUtils.CR) {\n lastIdx--;\n }\n } else if (last != CharUtils.CR) {\n lastIdx++;\n }\n return str.substring(0, lastIdx);\n }\n\n /**\n *

          Removes separator from the end of\n * str if it's there, otherwise leave it alone.

          \n *\n *

          NOTE: This method changed in version 2.0.\n * It now more closely matches Perl chomp.\n * For the previous behavior, use {@link #substringBeforeLast(String, String)}.\n * This method uses {@link String#endsWith(String)}.

          \n *\n *
          \n     * StringUtils.chomp(null, *)         = null\n     * StringUtils.chomp(\"\", *)           = \"\"\n     * StringUtils.chomp(\"foobar\", \"bar\") = \"foo\"\n     * StringUtils.chomp(\"foobar\", \"baz\") = \"foobar\"\n     * StringUtils.chomp(\"foo\", \"foo\")    = \"\"\n     * StringUtils.chomp(\"foo \", \"foo\")   = \"foo \"\n     * StringUtils.chomp(\" foo\", \"foo\")   = \" \"\n     * StringUtils.chomp(\"foo\", \"foooo\")  = \"foo\"\n     * StringUtils.chomp(\"foo\", \"\")       = \"foo\"\n     * StringUtils.chomp(\"foo\", null)     = \"foo\"\n     * 
          \n *\n * @param str the String to chomp from, may be null\n * @param separator separator String, may be null\n * @return String without trailing separator, null if null String input\n */\n public static String chomp(final String str, final String separator) {\n if (StringUtils.isEmpty(str) || separator == null) {\n return str;\n }\n if (str.endsWith(separator)) {\n return str.substring(0, str.length() - separator.length());\n }\n return str;\n }\n // Chopping\n //-----------------------------------------------------------------------\n\n /**\n *

          Remove the last character from a String.

          \n *\n *

          If the String ends in \\r\\n, then remove both\n * of them.

          \n *\n *
          \n     * StringUtils.chop(null)          = null\n     * StringUtils.chop(\"\")            = \"\"\n     * StringUtils.chop(\"abc \\r\")      = \"abc \"\n     * StringUtils.chop(\"abc\\n\")       = \"abc\"\n     * StringUtils.chop(\"abc\\r\\n\")     = \"abc\"\n     * StringUtils.chop(\"abc\")         = \"ab\"\n     * StringUtils.chop(\"abc\\nabc\")    = \"abc\\nab\"\n     * StringUtils.chop(\"a\")           = \"\"\n     * StringUtils.chop(\"\\r\")          = \"\"\n     * StringUtils.chop(\"\\n\")          = \"\"\n     * StringUtils.chop(\"\\r\\n\")        = \"\"\n     * 
          \n *\n * @param str the String to chop last character from, may be null\n * @return String without last character, null if null String input\n */\n public static String chop(final String str) {\n if (str == null) {\n return null;\n }\n int strLen = str.length();\n if (strLen < 2) {\n return StringUtils.EMPTY;\n }\n int lastIdx = strLen - 1;\n String ret = str.substring(0, lastIdx);\n char last = str.charAt(lastIdx);\n if (last == CharUtils.LF) {\n if (ret.charAt(lastIdx - 1) == CharUtils.CR) {\n return ret.substring(0, lastIdx - 1);\n }\n }\n return ret;\n }\n // Padding\n //-----------------------------------------------------------------------\n\n /**\n *

          Repeat a String repeat times to form a\n * new String.

          \n *\n *
          \n     * StringUtils.repeat(null, 2) = null\n     * StringUtils.repeat(\"\", 0)   = \"\"\n     * StringUtils.repeat(\"\", 2)   = \"\"\n     * StringUtils.repeat(\"a\", 3)  = \"aaa\"\n     * StringUtils.repeat(\"ab\", 2) = \"abab\"\n     * StringUtils.repeat(\"a\", -2) = \"\"\n     * 
          \n *\n * @param character the Character to to repeat, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n */\n public static String repeat(final char character, final int repeat) {\n return repeat(character + \"\", repeat);\n }\n\n /**\n *

          Repeat a String repeat times to form a\n * new String.

          \n *\n *
          \n     * StringUtils.repeat(null, 2) = null\n     * StringUtils.repeat(\"\", 0)   = \"\"\n     * StringUtils.repeat(\"\", 2)   = \"\"\n     * StringUtils.repeat(\"a\", 3)  = \"aaa\"\n     * StringUtils.repeat(\"ab\", 2) = \"abab\"\n     * StringUtils.repeat(\"a\", -2) = \"\"\n     * 
          \n *\n * @param str the String to repeat, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n */\n public static String repeat(final String str, final int repeat) {\n // Performance tuned for 2.0 (JDK1.4)\n if (str == null) {\n return null;\n }\n if (repeat <= 0) {\n return StringUtils.EMPTY;\n }\n int inputLength = str.length();\n if (repeat == 1 || inputLength == 0) {\n return str;\n }\n if (inputLength == 1 && repeat <= StringUtils.PAD_LIMIT) {\n return StringUtils.padding(repeat, str.charAt(0));\n }\n int outputLength = inputLength * repeat;\n switch (inputLength) {\n case 1:\n char ch = str.charAt(0);\n char[] output1 = new char[outputLength];\n for (int i = repeat - 1; i >= 0; i--) {\n output1[i] = ch;\n }\n return new String(output1);\n case 2:\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n char[] output2 = new char[outputLength];\n for (int i = repeat * 2 - 2; i >= 0; i--, i--) {\n output2[i] = ch0;\n output2[i + 1] = ch1;\n }\n return new String(output2);\n default:\n StringBuilder buf = new StringBuilder(outputLength);\n for (int i = 0; i < repeat; i++) {\n buf.append(str);\n }\n return buf.toString();\n }\n }\n\n /**\n *

          Repeat a String repeat times to form a\n * new String, with a String separator injected each time.

          \n *\n *
          \n     * StringUtils.repeat(null, null, 2) = null\n     * StringUtils.repeat(null, \"x\", 2)  = null\n     * StringUtils.repeat(\"\", null, 0)   = \"\"\n     * StringUtils.repeat(\"\", \"\", 2)     = \"\"\n     * StringUtils.repeat(\"\", \"x\", 3)    = \"xxx\"\n     * StringUtils.repeat(\"?\", \", \", 3)  = \"?, ?, ?\"\n     * 
          \n *\n * @param str the String to repeat, may be null\n * @param separator the String to inject, may be null\n * @param repeat number of times to repeat str, negative treated as zero\n * @return a new String consisting of the original String repeated,\n * null if null String input\n * @since 2.5\n */\n public static String repeat(final String str, final String separator, final int repeat) {\n if (str == null || separator == null) {\n return StringUtils.repeat(str, repeat);\n } else {\n // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it\n String result = StringUtils.repeat(str + separator, repeat);\n return StringUtils.removeEnd(result, separator);\n }\n }\n\n /**\n *

          Returns padding using the specified delimiter repeated\n * to a given length.

          \n *\n *
          \n     * StringUtils.padding(0, 'e')  = \"\"\n     * StringUtils.padding(3, 'e')  = \"eee\"\n     * StringUtils.padding(-2, 'e') = IndexOutOfBoundsException\n     * 
          \n *\n *

          Note: this method doesn't not support padding with\n * Unicode Supplementary Characters\n * as they require a pair of chars to be represented.\n * If you are needing to support full I18N of your applications\n * consider using {@link #repeat(String, int)} instead.\n *

          \n *\n * @param repeat number of times to repeat delim\n * @param padChar character to repeat\n * @return String with repeated character\n * @throws IndexOutOfBoundsException if repeat < 0\n * @see #repeat(String, int)\n */\n private static String padding(final int repeat, final char padChar) throws IndexOutOfBoundsException {\n if (repeat < 0) {\n throw new IndexOutOfBoundsException(\"Cannot pad a negative amount: \" + repeat);\n }\n final char[] buf = new char[repeat];\n Arrays.fill(buf, padChar);\n return new String(buf);\n }\n\n /**\n *

          Right pad a String with spaces (' ').

          \n *\n *

          The String is padded to the size of size.

          \n *\n *
          \n     * StringUtils.rightPad(null, *)   = null\n     * StringUtils.rightPad(\"\", 3)     = \"   \"\n     * StringUtils.rightPad(\"bat\", 3)  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5)  = \"bat  \"\n     * StringUtils.rightPad(\"bat\", 1)  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1) = \"bat\"\n     * 
          \n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String rightPad(final String str, final int size) {\n return StringUtils.rightPad(str, size, ' ');\n }\n\n /**\n *

          Right pad a String with a specified character.

          \n *\n *

          The String is padded to the size of size.

          \n *\n *
          \n     * StringUtils.rightPad(null, *, *)     = null\n     * StringUtils.rightPad(\"\", 3, 'z')     = \"zzz\"\n     * StringUtils.rightPad(\"bat\", 3, 'z')  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, 'z')  = \"batzz\"\n     * StringUtils.rightPad(\"bat\", 1, 'z')  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1, 'z') = \"bat\"\n     * 
          \n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padChar the character to pad with\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n * @since 2.0\n */\n public static String rightPad(final String str, final int size, final char padChar) {\n if (str == null) {\n return null;\n }\n int pads = size - str.length();\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (pads > StringUtils.PAD_LIMIT) {\n return StringUtils.rightPad(str, size, String.valueOf(padChar));\n }\n return str.concat(StringUtils.padding(pads, padChar));\n }\n\n /**\n *

          Right pad a String with a specified String.

          \n *\n *

          The String is padded to the size of size.

          \n *\n *
          \n     * StringUtils.rightPad(null, *, *)      = null\n     * StringUtils.rightPad(\"\", 3, \"z\")      = \"zzz\"\n     * StringUtils.rightPad(\"bat\", 3, \"yz\")  = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, \"yz\")  = \"batyz\"\n     * StringUtils.rightPad(\"bat\", 8, \"yz\")  = \"batyzyzy\"\n     * StringUtils.rightPad(\"bat\", 1, \"yz\")  = \"bat\"\n     * StringUtils.rightPad(\"bat\", -1, \"yz\") = \"bat\"\n     * StringUtils.rightPad(\"bat\", 5, null)  = \"bat  \"\n     * StringUtils.rightPad(\"bat\", 5, \"\")    = \"bat  \"\n     * 
          \n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padStr the String to pad with, null or empty treated as single space\n * @return right padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String rightPad(final String str, final int size, String padStr) {\n if (str == null) {\n return null;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int padLen = padStr.length();\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (padLen == 1 && pads <= StringUtils.PAD_LIMIT) {\n return StringUtils.rightPad(str, size, padStr.charAt(0));\n }\n if (pads == padLen) {\n return str.concat(padStr);\n } else if (pads < padLen) {\n return str.concat(padStr.substring(0, pads));\n } else {\n char[] padding = new char[pads];\n char[] padChars = padStr.toCharArray();\n for (int i = 0; i < pads; i++) {\n padding[i] = padChars[i % padLen];\n }\n return str.concat(new String(padding));\n }\n }\n\n /**\n *

          Left pad a String with spaces (' ').

          \n *\n *

          The String is padded to the size of size.

          \n *\n *
          \n     * StringUtils.leftPad(null, *)   = null\n     * StringUtils.leftPad(\"\", 3)     = \"   \"\n     * StringUtils.leftPad(\"bat\", 3)  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5)  = \"  bat\"\n     * StringUtils.leftPad(\"bat\", 1)  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1) = \"bat\"\n     * 
          \n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String leftPad(final String str, final int size) {\n return StringUtils.leftPad(str, size, ' ');\n }\n\n /**\n *

          Left pad a String with a specified character.

          \n *\n *

          Pad to a size of size.

          \n *\n *
          \n     * StringUtils.leftPad(null, *, *)     = null\n     * StringUtils.leftPad(\"\", 3, 'z')     = \"zzz\"\n     * StringUtils.leftPad(\"bat\", 3, 'z')  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, 'z')  = \"zzbat\"\n     * StringUtils.leftPad(\"bat\", 1, 'z')  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1, 'z') = \"bat\"\n     * 
          \n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padChar the character to pad with\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n * @since 2.0\n */\n public static String leftPad(final String str, final int size, final char padChar) {\n if (str == null) {\n return null;\n }\n int pads = size - str.length();\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (pads > StringUtils.PAD_LIMIT) {\n return StringUtils.leftPad(str, size, String.valueOf(padChar));\n }\n return StringUtils.padding(pads, padChar).concat(str);\n }\n\n /**\n *

          Left pad a String with a specified String.

          \n *\n *

          Pad to a size of size.

          \n *\n *
          \n     * StringUtils.leftPad(null, *, *)      = null\n     * StringUtils.leftPad(\"\", 3, \"z\")      = \"zzz\"\n     * StringUtils.leftPad(\"bat\", 3, \"yz\")  = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, \"yz\")  = \"yzbat\"\n     * StringUtils.leftPad(\"bat\", 8, \"yz\")  = \"yzyzybat\"\n     * StringUtils.leftPad(\"bat\", 1, \"yz\")  = \"bat\"\n     * StringUtils.leftPad(\"bat\", -1, \"yz\") = \"bat\"\n     * StringUtils.leftPad(\"bat\", 5, null)  = \"  bat\"\n     * StringUtils.leftPad(\"bat\", 5, \"\")    = \"  bat\"\n     * 
          \n *\n * @param str the String to pad out, may be null\n * @param size the size to pad to\n * @param padStr the String to pad with, null or empty treated as single space\n * @return left padded String or original String if no padding is necessary,\n * null if null String input\n */\n public static String leftPad(final String str, final int size, String padStr) {\n if (str == null) {\n return null;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int padLen = padStr.length();\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str; // returns original String when possible\n }\n if (padLen == 1 && pads <= StringUtils.PAD_LIMIT) {\n return StringUtils.leftPad(str, size, padStr.charAt(0));\n }\n if (pads == padLen) {\n return padStr.concat(str);\n } else if (pads < padLen) {\n return padStr.substring(0, pads).concat(str);\n } else {\n char[] padding = new char[pads];\n char[] padChars = padStr.toCharArray();\n for (int i = 0; i < pads; i++) {\n padding[i] = padChars[i % padLen];\n }\n return new String(padding).concat(str);\n }\n }\n\n /**\n * Gets a String's length or 0 if the String is null.\n *\n * @param str\n * a String or null\n * @return String length or 0 if the String is null.\n * @since 2.4\n */\n public static int length(final String str) {\n return str == null ? 0 : str.length();\n }\n // Centering\n //-----------------------------------------------------------------------\n\n /**\n *

          Centers a String in a larger String of size size\n * using the space character (' ').

          \n *\n *

          If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

          \n *\n *

          Equivalent to center(str, size, \" \").

          \n *\n *
          \n     * StringUtils.center(null, *)   = null\n     * StringUtils.center(\"\", 4)     = \"    \"\n     * StringUtils.center(\"ab\", -1)  = \"ab\"\n     * StringUtils.center(\"ab\", 4)   = \" ab \"\n     * StringUtils.center(\"abcd\", 2) = \"abcd\"\n     * StringUtils.center(\"a\", 4)    = \" a  \"\n     * 
          \n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @return centered String, null if null String input\n */\n public static String center(final String str, final int size) {\n return StringUtils.center(str, size, ' ');\n }\n\n /**\n *

          Centers a String in a larger String of size size.\n * Uses a supplied character as the value to pad the String with.

          \n *\n *

          If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

          \n *\n *
          \n     * StringUtils.center(null, *, *)     = null\n     * StringUtils.center(\"\", 4, ' ')     = \"    \"\n     * StringUtils.center(\"ab\", -1, ' ')  = \"ab\"\n     * StringUtils.center(\"ab\", 4, ' ')   = \" ab\"\n     * StringUtils.center(\"abcd\", 2, ' ') = \"abcd\"\n     * StringUtils.center(\"a\", 4, ' ')    = \" a  \"\n     * StringUtils.center(\"a\", 4, 'y')    = \"yayy\"\n     * 
          \n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @param padChar the character to pad the new String with\n * @return centered String, null if null String input\n * @since 2.0\n */\n public static String center(String str, final int size, final char padChar) {\n if (str == null || size <= 0) {\n return str;\n }\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str;\n }\n str = StringUtils.leftPad(str, strLen + pads / 2, padChar);\n str = StringUtils.rightPad(str, size, padChar);\n return str;\n }\n\n /**\n *

          Centers a String in a larger String of size size.\n * Uses a supplied String as the value to pad the String with.

          \n *\n *

          If the size is less than the String length, the String is returned.\n * A null String returns null.\n * A negative size is treated as zero.

          \n *\n *
          \n     * StringUtils.center(null, *, *)     = null\n     * StringUtils.center(\"\", 4, \" \")     = \"    \"\n     * StringUtils.center(\"ab\", -1, \" \")  = \"ab\"\n     * StringUtils.center(\"ab\", 4, \" \")   = \" ab\"\n     * StringUtils.center(\"abcd\", 2, \" \") = \"abcd\"\n     * StringUtils.center(\"a\", 4, \" \")    = \" a  \"\n     * StringUtils.center(\"a\", 4, \"yz\")   = \"yayz\"\n     * StringUtils.center(\"abc\", 7, null) = \"  abc  \"\n     * StringUtils.center(\"abc\", 7, \"\")   = \"  abc  \"\n     * 
          \n *\n * @param str the String to center, may be null\n * @param size the int size of new String, negative treated as zero\n * @param padStr the String to pad the new String with, must not be null or empty\n * @return centered String, null if null String input\n * @throws IllegalArgumentException if padStr is null or empty\n */\n public static String center(String str, final int size, String padStr) {\n if (str == null || size <= 0) {\n return str;\n }\n if (StringUtils.isEmpty(padStr)) {\n padStr = \" \";\n }\n int strLen = str.length();\n int pads = size - strLen;\n if (pads <= 0) {\n return str;\n }\n str = StringUtils.leftPad(str, strLen + pads / 2, padStr);\n str = StringUtils.rightPad(str, size, padStr);\n return str;\n }\n // Case conversion\n //-----------------------------------------------------------------------\n\n /**\n *

          Converts a String to upper case as per {@link String#toUpperCase()}.

          \n *\n *

          A null input String returns null.

          \n *\n *
          \n     * StringUtils.upperCase(null)  = null\n     * StringUtils.upperCase(\"\")    = \"\"\n     * StringUtils.upperCase(\"aBc\") = \"ABC\"\n     * 
          \n *\n *

          Note: As described in the documentation for {@link String#toUpperCase()},\n * the result of this method is affected by the current locale.\n * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}\n * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

          \n *\n * @param str the String to upper case, may be null\n * @return the upper cased String, null if null String input\n */\n public static String upperCase(final String str) {\n if (str == null) {\n return null;\n }\n return str.toUpperCase();\n }\n\n /**\n *

          Converts a String to upper case as per {@link String#toUpperCase(Locale)}.

          \n *\n *

          A null input String returns null.

          \n *\n *
          \n     * StringUtils.upperCase(null, Locale.ENGLISH)  = null\n     * StringUtils.upperCase(\"\", Locale.ENGLISH)    = \"\"\n     * StringUtils.upperCase(\"aBc\", Locale.ENGLISH) = \"ABC\"\n     * 
          \n *\n * @param str the String to upper case, may be null\n * @param locale the locale that defines the case transformation rules, must not be null\n * @return the upper cased String, null if null String input\n * @since 2.5\n */\n public static String upperCase(final String str, final Locale locale) {\n if (str == null) {\n return null;\n }\n return str.toUpperCase(locale);\n }\n\n /**\n *

          Converts a String to lower case as per {@link String#toLowerCase()}.

          \n *\n *

          A null input String returns null.

          \n *\n *
          \n     * StringUtils.lowerCase(null)  = null\n     * StringUtils.lowerCase(\"\")    = \"\"\n     * StringUtils.lowerCase(\"aBc\") = \"abc\"\n     * 
          \n *\n *

          Note: As described in the documentation for {@link String#toLowerCase()},\n * the result of this method is affected by the current locale.\n * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}\n * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

          \n *\n * @param str the String to lower case, may be null\n * @return the lower cased String, null if null String input\n */\n public static String lowerCase(final String str) {\n if (str == null) {\n return null;\n }\n return str.toLowerCase();\n }\n\n /**\n *

          Converts a String to lower case as per {@link String#toLowerCase(Locale)}.

          \n *\n *

          A null input String returns null.

          \n *\n *
          \n     * StringUtils.lowerCase(null, Locale.ENGLISH)  = null\n     * StringUtils.lowerCase(\"\", Locale.ENGLISH)    = \"\"\n     * StringUtils.lowerCase(\"aBc\", Locale.ENGLISH) = \"abc\"\n     * 
          \n *\n * @param str the String to lower case, may be null\n * @param locale the locale that defines the case transformation rules, must not be null\n * @return the lower cased String, null if null String input\n * @since 2.5\n */\n public static String lowerCase(final String str, final Locale locale) {\n if (str == null) {\n return null;\n }\n return str.toLowerCase(locale);\n }\n\n /**\n *

          Capitalizes a String changing the first letter to title case as\n * per {@link Character#toTitleCase(char)}. No other letters are changed.

          \n *\n * A null input String returns null.

          \n *\n *
          \n     * StringUtils.capitalize(null)  = null\n     * StringUtils.capitalize(\"\")    = \"\"\n     * StringUtils.capitalize(\"cat\") = \"Cat\"\n     * StringUtils.capitalize(\"cAt\") = \"CAt\"\n     * 
          \n *\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null String input\n * @see #uncapitalize(String)\n * @since 2.0\n */\n public static String capitalize(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n return Character.toTitleCase(str.charAt(0)) + str.substring(1);\n }\n\n /**\n *

          Uncapitalizes a String changing the first letter to title case as\n * per {@link Character#toLowerCase(char)}. No other letters are changed.

          \n *\n * A null input String returns null.

          \n *\n *
          \n     * StringUtils.uncapitalize(null)  = null\n     * StringUtils.uncapitalize(\"\")    = \"\"\n     * StringUtils.uncapitalize(\"Cat\") = \"cat\"\n     * StringUtils.uncapitalize(\"CAT\") = \"cAT\"\n     * 
          \n *\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null String input\n * @see #capitalize(String)\n * @since 2.0\n */\n public static String uncapitalize(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n return Character.toLowerCase(str.charAt(0)) + str.substring(1);\n }\n\n /**\n *

          Swaps the case of a String changing upper and title case to\n * lower case, and lower case to upper case.

          \n *\n *
            \n *
          • Upper case character converts to Lower case
          • \n *
          • Title case character converts to Lower case
          • \n *
          • Lower case character converts to Upper case
          • \n *
          \n *\n * A null input String returns null.

          \n *\n *
          \n     * StringUtils.swapCase(null)                 = null\n     * StringUtils.swapCase(\"\")                   = \"\"\n     * StringUtils.swapCase(\"The dog has a BONE\") = \"tHE DOG HAS A bone\"\n     * 
          \n *\n *

          NOTE: This method changed in Lang version 2.0.\n * It no longer performs a word based algorithm.\n * If you only use ASCII, you will notice no change.\n * That functionality is available in WordUtils.

          \n *\n * @param str the String to swap case, may be null\n * @return the changed String, null if null String input\n */\n public static String swapCase(final String str) {\n int strLen;\n if (str == null || (strLen = str.length()) == 0) {\n return str;\n }\n StringBuilder buffer = new StringBuilder(strLen);\n char ch = 0;\n for (int i = 0; i < strLen; i++) {\n ch = str.charAt(i);\n if (Character.isUpperCase(ch)) {\n ch = Character.toLowerCase(ch);\n } else if (Character.isTitleCase(ch)) {\n ch = Character.toLowerCase(ch);\n } else if (Character.isLowerCase(ch)) {\n ch = Character.toUpperCase(ch);\n }\n buffer.append(ch);\n }\n return buffer.toString();\n }\n // Count matches\n //-----------------------------------------------------------------------\n\n /**\n *

          Counts how many times the substring appears in the larger String.

          \n *\n *

          A null or empty (\"\") String input returns 0.

          \n *\n *
          \n     * StringUtils.countMatches(null, *)       = 0\n     * StringUtils.countMatches(\"\", *)         = 0\n     * StringUtils.countMatches(\"abba\", null)  = 0\n     * StringUtils.countMatches(\"abba\", \"\")    = 0\n     * StringUtils.countMatches(\"abba\", \"a\")   = 2\n     * StringUtils.countMatches(\"abba\", \"ab\")  = 1\n     * StringUtils.countMatches(\"abba\", \"xxx\") = 0\n     * 
          \n *\n * @param str the String to check, may be null\n * @param sub the substring to count, may be null\n * @return the number of occurrences, 0 if either String is null\n */\n public static int countMatches(final String str, final String sub) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(sub)) {\n return 0;\n }\n int count = 0;\n int idx = 0;\n while ((idx = str.indexOf(sub, idx)) != StringUtils.INDEX_NOT_FOUND) {\n count++;\n idx += sub.length();\n }\n return count;\n }\n // Character Tests\n //-----------------------------------------------------------------------\n\n /**\n *

          Checks if the String contains only unicode letters.

          \n *\n *

          null will return false.\n * An empty String (length()=0) will return true.

          \n *\n *
          \n     * StringUtils.isAlpha(null)   = false\n     * StringUtils.isAlpha(\"\")     = true\n     * StringUtils.isAlpha(\"  \")   = false\n     * StringUtils.isAlpha(\"abc\")  = true\n     * StringUtils.isAlpha(\"ab2c\") = false\n     * StringUtils.isAlpha(\"ab-c\") = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @return true if only contains letters, and is non-null\n */\n public static boolean isAlpha(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetter(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

          Checks if the String contains only unicode letters and\n * space (' ').

          \n *\n *

          null will return false\n * An empty String (length()=0) will return true.

          \n *\n *
          \n     * StringUtils.isAlphaSpace(null)   = false\n     * StringUtils.isAlphaSpace(\"\")     = true\n     * StringUtils.isAlphaSpace(\"  \")   = true\n     * StringUtils.isAlphaSpace(\"abc\")  = true\n     * StringUtils.isAlphaSpace(\"ab c\") = true\n     * StringUtils.isAlphaSpace(\"ab2c\") = false\n     * StringUtils.isAlphaSpace(\"ab-c\") = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @return true if only contains letters and space,\n * and is non-null\n */\n public static boolean isAlphaSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetter(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

          Checks if the String contains only unicode letters or digits.

          \n *\n *

          null will return false.\n * An empty String (length()=0) will return true.

          \n *\n *
          \n     * StringUtils.isAlphanumeric(null)   = false\n     * StringUtils.isAlphanumeric(\"\")     = true\n     * StringUtils.isAlphanumeric(\"  \")   = false\n     * StringUtils.isAlphanumeric(\"abc\")  = true\n     * StringUtils.isAlphanumeric(\"ab c\") = false\n     * StringUtils.isAlphanumeric(\"ab2c\") = true\n     * StringUtils.isAlphanumeric(\"ab-c\") = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @return true if only contains letters or digits,\n * and is non-null\n */\n public static boolean isAlphanumeric(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetterOrDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

          Checks if the String contains only unicode letters, digits\n * or space (' ').

          \n *\n *

          null will return false.\n * An empty String (length()=0) will return true.

          \n *\n *
          \n     * StringUtils.isAlphanumeric(null)   = false\n     * StringUtils.isAlphanumeric(\"\")     = true\n     * StringUtils.isAlphanumeric(\"  \")   = true\n     * StringUtils.isAlphanumeric(\"abc\")  = true\n     * StringUtils.isAlphanumeric(\"ab c\") = true\n     * StringUtils.isAlphanumeric(\"ab2c\") = true\n     * StringUtils.isAlphanumeric(\"ab-c\") = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @return true if only contains letters, digits or space,\n * and is non-null\n */\n public static boolean isAlphanumericSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLetterOrDigit(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

          Checks if the string contains only ASCII printable characters.

          \n *\n *

          null will return false.\n * An empty String (length()=0) will return true.

          \n *\n *
          \n     * StringUtils.isAsciiPrintable(null)     = false\n     * StringUtils.isAsciiPrintable(\"\")       = true\n     * StringUtils.isAsciiPrintable(\" \")      = true\n     * StringUtils.isAsciiPrintable(\"Ceki\")   = true\n     * StringUtils.isAsciiPrintable(\"ab2c\")   = true\n     * StringUtils.isAsciiPrintable(\"!ab-c~\") = true\n     * StringUtils.isAsciiPrintable(\"\\u0020\") = true\n     * StringUtils.isAsciiPrintable(\"\\u0021\") = true\n     * StringUtils.isAsciiPrintable(\"\\u007e\") = true\n     * StringUtils.isAsciiPrintable(\"\\u007f\") = false\n     * StringUtils.isAsciiPrintable(\"Ceki G\\u00fclc\\u00fc\") = false\n     * 
          \n *\n * @param str the string to check, may be null\n * @return true if every character is in the range\n * 32 thru 126\n * @since 2.1\n */\n public static boolean isAsciiPrintable(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!CharUtils.isAsciiPrintable(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

          Checks if the String contains only unicode digits.\n * A decimal point is not a unicode digit and returns false.

          \n *\n *

          null will return false.\n * An empty String (length()=0) will return true.

          \n *\n *
          \n     * StringUtils.isNumeric(null)   = false\n     * StringUtils.isNumeric(\"\")     = true\n     * StringUtils.isNumeric(\"  \")   = false\n     * StringUtils.isNumeric(\"123\")  = true\n     * StringUtils.isNumeric(\"12 3\") = false\n     * StringUtils.isNumeric(\"ab2c\") = false\n     * StringUtils.isNumeric(\"12-3\") = false\n     * StringUtils.isNumeric(\"12.3\") = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @return true if only contains digits, and is non-null\n */\n public static boolean isNumeric(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isDigit(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

          Checks if the String contains only unicode digits or space\n * (' ').\n * A decimal point is not a unicode digit and returns false.

          \n *\n *

          null will return false.\n * An empty String (length()=0) will return true.

          \n *\n *
          \n     * StringUtils.isNumeric(null)   = false\n     * StringUtils.isNumeric(\"\")     = true\n     * StringUtils.isNumeric(\"  \")   = true\n     * StringUtils.isNumeric(\"123\")  = true\n     * StringUtils.isNumeric(\"12 3\") = true\n     * StringUtils.isNumeric(\"ab2c\") = false\n     * StringUtils.isNumeric(\"12-3\") = false\n     * StringUtils.isNumeric(\"12.3\") = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @return true if only contains digits or space,\n * and is non-null\n */\n public static boolean isNumericSpace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != ' ') {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

          Checks if the String contains only whitespace.

          \n *\n *

          null will return false.\n * An empty String (length()=0) will return true.

          \n *\n *
          \n     * StringUtils.isWhitespace(null)   = false\n     * StringUtils.isWhitespace(\"\")     = true\n     * StringUtils.isWhitespace(\"  \")   = true\n     * StringUtils.isWhitespace(\"abc\")  = false\n     * StringUtils.isWhitespace(\"ab2c\") = false\n     * StringUtils.isWhitespace(\"ab-c\") = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @return true if only contains whitespace, and is non-null\n * @since 2.0\n */\n public static boolean isWhitespace(final String str) {\n if (str == null) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

          Checks if the String contains only lowercase characters.

          \n *\n *

          null will return false.\n * An empty String (length()=0) will return false.

          \n *\n *
          \n     * StringUtils.isAllLowerCase(null)   = false\n     * StringUtils.isAllLowerCase(\"\")     = false\n     * StringUtils.isAllLowerCase(\"  \")   = false\n     * StringUtils.isAllLowerCase(\"abc\")  = true\n     * StringUtils.isAllLowerCase(\"abC\") = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @return true if only contains lowercase characters, and is non-null\n * @since 2.5\n */\n public static boolean isAllLowerCase(final String str) {\n if (str == null || StringUtils.isEmpty(str)) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isLowerCase(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n *

          Checks if the String contains only uppercase characters.

          \n *\n *

          null will return false.\n * An empty String (length()=0) will return false.

          \n *\n *
          \n     * StringUtils.isAllUpperCase(null)   = false\n     * StringUtils.isAllUpperCase(\"\")     = false\n     * StringUtils.isAllUpperCase(\"  \")   = false\n     * StringUtils.isAllUpperCase(\"ABC\")  = true\n     * StringUtils.isAllUpperCase(\"aBC\") = false\n     * 
          \n *\n * @param str the String to check, may be null\n * @return true if only contains uppercase characters, and is non-null\n * @since 2.5\n */\n public static boolean isAllUpperCase(final String str) {\n if (str == null || StringUtils.isEmpty(str)) {\n return false;\n }\n int sz = str.length();\n for (int i = 0; i < sz; i++) {\n if (!Character.isUpperCase(str.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n // Defaults\n //-----------------------------------------------------------------------\n\n /**\n *

          Returns either the passed in String,\n * or if the String is null, an empty String (\"\").

          \n *\n *
          \n     * StringUtils.defaultString(null)  = \"\"\n     * StringUtils.defaultString(\"\")    = \"\"\n     * StringUtils.defaultString(\"bat\") = \"bat\"\n     * 
          \n *\n * @see ObjectUtils#toString(Object)\n * @see String#valueOf(Object)\n * @param str the String to check, may be null\n * @return the passed in String, or the empty String if it\n * was null\n */\n public static String defaultString(final String str) {\n return str == null ? StringUtils.EMPTY : str;\n }\n\n /**\n *

          Returns either the passed in String, or if the String is\n * null, the value of defaultStr.

          \n *\n *
          \n     * StringUtils.defaultString(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultString(\"\", \"NULL\")    = \"\"\n     * StringUtils.defaultString(\"bat\", \"NULL\") = \"bat\"\n     * 
          \n *\n * @see ObjectUtils#toString(Object, String)\n * @see String#valueOf(Object)\n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is null, may be null\n * @return the passed in String, or the default if it was null\n */\n public static String defaultString(final String str, final String defaultStr) {\n return str == null ? defaultStr : str;\n }\n\n /**\n *

          Returns either the passed in String, or if the String is\n * whitespace, empty (\"\") or null, the value of defaultStr.

          \n *\n *
          \n     * StringUtils.defaultIfBlank(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultIfBlank(\"\", \"NULL\")    = \"NULL\"\n     * StringUtils.defaultIfBlank(\" \", \"NULL\")   = \"NULL\"\n     * StringUtils.defaultIfBlank(\"bat\", \"NULL\") = \"bat\"\n     * StringUtils.defaultIfBlank(\"\", null)      = null\n     * 
          \n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is whitespace, empty (\"\") or null, may be null\n * @return the passed in String, or the default\n * @see StringUtils#defaultString(String, String)\n * @since 2.6\n */\n public static String defaultIfBlank(final String str, final String defaultStr) {\n return StringUtils.isBlank(str) ? defaultStr : str;\n }\n\n /**\n *

          Returns either the passed in String, or if the String is\n * empty or null, the value of defaultStr.

          \n *\n *
          \n     * StringUtils.defaultIfEmpty(null, \"NULL\")  = \"NULL\"\n     * StringUtils.defaultIfEmpty(\"\", \"NULL\")    = \"NULL\"\n     * StringUtils.defaultIfEmpty(\"bat\", \"NULL\") = \"bat\"\n     * StringUtils.defaultIfEmpty(\"\", null)      = null\n     * 
          \n *\n * @param str the String to check, may be null\n * @param defaultStr the default String to return\n * if the input is empty (\"\") or null, may be null\n * @return the passed in String, or the default\n * @see StringUtils#defaultString(String, String)\n */\n public static String defaultIfEmpty(final String str, final String defaultStr) {\n return StringUtils.isEmpty(str) ? defaultStr : str;\n }\n // Reversing\n //-----------------------------------------------------------------------\n\n /**\n *

          Reverses a String as per {@link StringBuilder#reverse()}.

          \n *\n *

          A null String returns null.

          \n *\n *
          \n     * StringUtils.reverse(null)  = null\n     * StringUtils.reverse(\"\")    = \"\"\n     * StringUtils.reverse(\"bat\") = \"tab\"\n     * 
          \n *\n * @param str the String to reverse, may be null\n * @return the reversed String, null if null String input\n */\n public static String reverse(final String str) {\n if (str == null) {\n return null;\n }\n return new StringBuilder(str).reverse().toString();\n }\n\n /**\n *

          Reverses a String that is delimited by a specific character.

          \n *\n *

          The Strings between the delimiters are not reversed.\n * Thus java.lang.String becomes String.lang.java (if the delimiter\n * is '.').

          \n *\n *
          \n     * StringUtils.reverseDelimited(null, *)      = null\n     * StringUtils.reverseDelimited(\"\", *)        = \"\"\n     * StringUtils.reverseDelimited(\"a.b.c\", 'x') = \"a.b.c\"\n     * StringUtils.reverseDelimited(\"a.b.c\", \".\") = \"c.b.a\"\n     * 
          \n *\n * @param str the String to reverse, may be null\n * @param separatorChar the separator character to use\n * @return the reversed String, null if null String input\n * @since 2.0\n */\n public static String reverseDelimited(final String str, final char separatorChar) {\n if (str == null) {\n return null;\n }\n // could implement manually, but simple way is to reuse other,\n // probably slower, methods.\n String[] strs = StringUtils.split(str, separatorChar);\n ArrayUtils.reverse(strs);\n return StringUtils.join(strs, separatorChar);\n }\n // Abbreviating\n //-----------------------------------------------------------------------\n\n /**\n *

          Abbreviates a String using ellipses. This will turn\n * \"Now is the time for all good men\" into \"Now is the time for...\"

          \n *\n *

          Specifically:\n *

            \n *
          • If str is less than maxWidth characters\n * long, return it.
          • \n *
          • Else abbreviate it to (substring(str, 0, max-3) + \"...\").
          • \n *
          • If maxWidth is less than 4, throw an\n * IllegalArgumentException.
          • \n *
          • In no case will it return a String of length greater than\n * maxWidth.
          • \n *
          \n *

          \n *\n *
          \n     * StringUtils.abbreviate(null, *)      = null\n     * StringUtils.abbreviate(\"\", 4)        = \"\"\n     * StringUtils.abbreviate(\"abcdefg\", 6) = \"abc...\"\n     * StringUtils.abbreviate(\"abcdefg\", 7) = \"abcdefg\"\n     * StringUtils.abbreviate(\"abcdefg\", 8) = \"abcdefg\"\n     * StringUtils.abbreviate(\"abcdefg\", 4) = \"a...\"\n     * StringUtils.abbreviate(\"abcdefg\", 3) = IllegalArgumentException\n     * 
          \n *\n * @param str the String to check, may be null\n * @param maxWidth maximum length of result String, must be at least 4\n * @return abbreviated String, null if null String input\n * @throws IllegalArgumentException if the width is too small\n * @since 2.0\n */\n public static String abbreviate(final String str, final int maxWidth) {\n return StringUtils.abbreviate(str, 0, maxWidth);\n }\n\n /**\n *

          Abbreviates a String using ellipses. This will turn\n * \"Now is the time for all good men\" into \"...is the time for...\"

          \n *\n *

          Works like abbreviate(String, int), but allows you to specify\n * a \"left edge\" offset. Note that this left edge is not necessarily going to\n * be the leftmost character in the result, or the first character following the\n * ellipses, but it will appear somewhere in the result.\n *\n *

          In no case will it return a String of length greater than\n * maxWidth.

          \n *\n *
          \n     * StringUtils.abbreviate(null, *, *)                = null\n     * StringUtils.abbreviate(\"\", 0, 4)                  = \"\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", -1, 10) = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 0, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 1, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 4, 10)  = \"abcdefg...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 5, 10)  = \"...fghi...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 6, 10)  = \"...ghij...\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 8, 10)  = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 10, 10) = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghijklmno\", 12, 10) = \"...ijklmno\"\n     * StringUtils.abbreviate(\"abcdefghij\", 0, 3)        = IllegalArgumentException\n     * StringUtils.abbreviate(\"abcdefghij\", 5, 6)        = IllegalArgumentException\n     * 
          \n *\n * @param str the String to check, may be null\n * @param offset left edge of source String\n * @param maxWidth maximum length of result String, must be at least 4\n * @return abbreviated String, null if null String input\n * @throws IllegalArgumentException if the width is too small\n * @since 2.0\n */\n public static String abbreviate(final String str, int offset, final int maxWidth) {\n if (str == null) {\n return null;\n }\n if (maxWidth < 4) {\n throw new IllegalArgumentException(\"Minimum abbreviation width is 4\");\n }\n if (str.length() <= maxWidth) {\n return str;\n }\n if (offset > str.length()) {\n offset = str.length();\n }\n if (str.length() - offset < maxWidth - 3) {\n offset = str.length() - (maxWidth - 3);\n }\n if (offset <= 4) {\n return str.substring(0, maxWidth - 3) + \"...\";\n }\n if (maxWidth < 7) {\n throw new IllegalArgumentException(\"Minimum abbreviation width with offset is 7\");\n }\n if (offset + maxWidth - 3 < str.length()) {\n return \"...\" + StringUtils.abbreviate(str.substring(offset), maxWidth - 3);\n }\n return \"...\" + str.substring(str.length() - (maxWidth - 3));\n }\n\n /**\n *

          Abbreviates a String to the length passed, replacing the middle characters with the supplied\n * replacement String.

          \n *\n *

          This abbreviation only occurs if the following criteria is met:\n *

            \n *
          • Neither the String for abbreviation nor the replacement String are null or empty
          • \n *
          • The length to truncate to is less than the length of the supplied String
          • \n *
          • The length to truncate to is greater than 0
          • \n *
          • The abbreviated String will have enough room for the length supplied replacement String\n * and the first and last characters of the supplied String for abbreviation
          • \n *
          \n * Otherwise, the returned String will be the same as the supplied String for abbreviation.\n *

          \n *\n *
          \n     * StringUtils.abbreviateMiddle(null, null, 0)      = null\n     * StringUtils.abbreviateMiddle(\"abc\", null, 0)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abc\", \".\", 0)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abc\", \".\", 3)      = \"abc\"\n     * StringUtils.abbreviateMiddle(\"abcdef\", \".\", 4)     = \"ab.f\"\n     * 
          \n *\n * @param str the String to abbreviate, may be null\n * @param middle the String to replace the middle characters with, may be null\n * @param length the length to abbreviate str to.\n * @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation.\n * @since 2.5\n */\n public static String abbreviateMiddle(final String str, final String middle, final int length) {\n if (StringUtils.isEmpty(str) || StringUtils.isEmpty(middle)) {\n return str;\n }\n if (length >= str.length() || length < middle.length() + 2) {\n return str;\n }\n int targetSting = length - middle.length();\n int startOffset = targetSting / 2 + targetSting % 2;\n int endOffset = str.length() - targetSting / 2;\n return str.substring(0, startOffset) + middle + str.substring(endOffset);\n }\n // Difference\n //-----------------------------------------------------------------------\n\n /**\n *

          Compares two Strings, and returns the portion where they differ.\n * (More precisely, return the remainder of the second String,\n * starting from where it's different from the first.)

          \n *\n *

          For example,\n * difference(\"i am a machine\", \"i am a robot\") -> \"robot\".

          \n *\n *
          \n     * StringUtils.difference(null, null) = null\n     * StringUtils.difference(\"\", \"\") = \"\"\n     * StringUtils.difference(\"\", \"abc\") = \"abc\"\n     * StringUtils.difference(\"abc\", \"\") = \"\"\n     * StringUtils.difference(\"abc\", \"abc\") = \"\"\n     * StringUtils.difference(\"ab\", \"abxyz\") = \"xyz\"\n     * StringUtils.difference(\"abcde\", \"abxyz\") = \"xyz\"\n     * StringUtils.difference(\"abcde\", \"xyz\") = \"xyz\"\n     * 
          \n *\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return the portion of str2 where it differs from str1; returns the\n * empty String if they are equal\n * @since 2.0\n */\n public static String difference(final String str1, final String str2) {\n if (str1 == null) {\n return str2;\n }\n if (str2 == null) {\n return str1;\n }\n int at = StringUtils.indexOfDifference(str1, str2);\n if (at == StringUtils.INDEX_NOT_FOUND) {\n return StringUtils.EMPTY;\n }\n return str2.substring(at);\n }\n\n /**\n *

          Compares two Strings, and returns the index at which the\n * Strings begin to differ.

          \n *\n *

          For example,\n * indexOfDifference(\"i am a machine\", \"i am a robot\") -> 7

          \n *\n *
          \n     * StringUtils.indexOfDifference(null, null) = -1\n     * StringUtils.indexOfDifference(\"\", \"\") = -1\n     * StringUtils.indexOfDifference(\"\", \"abc\") = 0\n     * StringUtils.indexOfDifference(\"abc\", \"\") = 0\n     * StringUtils.indexOfDifference(\"abc\", \"abc\") = -1\n     * StringUtils.indexOfDifference(\"ab\", \"abxyz\") = 2\n     * StringUtils.indexOfDifference(\"abcde\", \"abxyz\") = 2\n     * StringUtils.indexOfDifference(\"abcde\", \"xyz\") = 0\n     * 
          \n *\n * @param str1 the first String, may be null\n * @param str2 the second String, may be null\n * @return the index where str2 and str1 begin to differ; -1 if they are equal\n * @since 2.0\n */\n public static int indexOfDifference(final String str1, final String str2) {\n if (str1 != null && str1.equals(str2)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n if (str1 == null || str2 == null) {\n return 0;\n }\n int i;\n for (i = 0; i < str1.length() && i < str2.length(); ++i) {\n if (str1.charAt(i) != str2.charAt(i)) {\n break;\n }\n }\n if (i < str2.length() || i < str1.length()) {\n return i;\n }\n return StringUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Compares all Strings in an array and returns the index at which the\n * Strings begin to differ.

          \n *\n *

          For example,\n * indexOfDifference(new String[] {\"i am a machine\", \"i am a robot\"}) -> 7

          \n *\n *
          \n     * StringUtils.indexOfDifference(null) = -1\n     * StringUtils.indexOfDifference(new String[] {}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"abc\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {null, null}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"\", \"\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"\", null}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", null, null}) = 0\n     * StringUtils.indexOfDifference(new String[] {null, null, \"abc\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"\", \"abc\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"abc\"}) = -1\n     * StringUtils.indexOfDifference(new String[] {\"abc\", \"a\"}) = 1\n     * StringUtils.indexOfDifference(new String[] {\"ab\", \"abxyz\"}) = 2\n     * StringUtils.indexOfDifference(new String[] {\"abcde\", \"abxyz\"}) = 2\n     * StringUtils.indexOfDifference(new String[] {\"abcde\", \"xyz\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"xyz\", \"abcde\"}) = 0\n     * StringUtils.indexOfDifference(new String[] {\"i am a machine\", \"i am a robot\"}) = 7\n     * 
          \n *\n * @param strs array of strings, entries may be null\n * @return the index where the strings begin to differ; -1 if they are all equal\n * @since 2.4\n */\n public static int indexOfDifference(final String[] strs) {\n if (strs == null || strs.length <= 1) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n boolean anyStringNull = false;\n boolean allStringsNull = true;\n int arrayLen = strs.length;\n int shortestStrLen = Integer.MAX_VALUE;\n int longestStrLen = 0;\n // find the min and max string lengths; this avoids checking to make\n // sure we are not exceeding the length of the string each time through\n // the bottom loop.\n for (int i = 0; i < arrayLen; i++) {\n if (strs[i] == null) {\n anyStringNull = true;\n shortestStrLen = 0;\n } else {\n allStringsNull = false;\n shortestStrLen = Math.min(strs[i].length(), shortestStrLen);\n longestStrLen = Math.max(strs[i].length(), longestStrLen);\n }\n }\n // handle lists containing all nulls or all empty strings\n if (allStringsNull || longestStrLen == 0 && !anyStringNull) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n // handle lists containing some nulls or some empty strings\n if (shortestStrLen == 0) {\n return 0;\n }\n // find the position with the first difference across all strings\n int firstDiff = -1;\n for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {\n char comparisonChar = strs[0].charAt(stringPos);\n for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {\n if (strs[arrayPos].charAt(stringPos) != comparisonChar) {\n firstDiff = stringPos;\n break;\n }\n }\n if (firstDiff != -1) {\n break;\n }\n }\n if (firstDiff == -1 && shortestStrLen != longestStrLen) {\n // we compared all of the characters up to the length of the\n // shortest string and didn't find a match, but the string lengths\n // vary, so return the length of the shortest string.\n return shortestStrLen;\n }\n return firstDiff;\n }\n\n /**\n *

          Compares all Strings in an array and returns the initial sequence of\n * characters that is common to all of them.

          \n *\n *

          For example,\n * getCommonPrefix(new String[] {\"i am a machine\", \"i am a robot\"}) -> \"i am a \"

          \n *\n *
          \n     * StringUtils.getCommonPrefix(null) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\"}) = \"abc\"\n     * StringUtils.getCommonPrefix(new String[] {null, null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", \"\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", null, null}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {null, null, \"abc\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"\", \"abc\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"abc\"}) = \"abc\"\n     * StringUtils.getCommonPrefix(new String[] {\"abc\", \"a\"}) = \"a\"\n     * StringUtils.getCommonPrefix(new String[] {\"ab\", \"abxyz\"}) = \"ab\"\n     * StringUtils.getCommonPrefix(new String[] {\"abcde\", \"abxyz\"}) = \"ab\"\n     * StringUtils.getCommonPrefix(new String[] {\"abcde\", \"xyz\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"xyz\", \"abcde\"}) = \"\"\n     * StringUtils.getCommonPrefix(new String[] {\"i am a machine\", \"i am a robot\"}) = \"i am a \"\n     * 
          \n *\n * @param strs array of String objects, entries may be null\n * @return the initial sequence of characters that are common to all Strings\n * in the array; empty String if the array is null, the elements are all null\n * or if there is no common prefix.\n * @since 2.4\n */\n public static String getCommonPrefix(final String[] strs) {\n if (strs == null || strs.length == 0) {\n return StringUtils.EMPTY;\n }\n int smallestIndexOfDiff = StringUtils.indexOfDifference(strs);\n if (smallestIndexOfDiff == StringUtils.INDEX_NOT_FOUND) {\n // all strings were identical\n if (strs[0] == null) {\n return StringUtils.EMPTY;\n }\n return strs[0];\n } else if (smallestIndexOfDiff == 0) {\n // there were no common initial characters\n return StringUtils.EMPTY;\n } else {\n // we found a common initial character sequence\n return strs[0].substring(0, smallestIndexOfDiff);\n }\n }\n // Misc\n //-----------------------------------------------------------------------\n\n /**\n *

          Find the Levenshtein distance between two Strings.

          \n *\n *

          This is the number of changes needed to change one String into\n * another, where each change is a single character modification (deletion,\n * insertion or substitution).

          \n *\n *

          The previous implementation of the Levenshtein distance algorithm\n * was from http://www.merriampark.com/ld.htm

          \n *\n *

          Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError\n * which can occur when my Java implementation is used with very large strings.
          \n * This implementation of the Levenshtein distance algorithm\n * is from http://www.merriampark.com/ldjava.htm

          \n *\n *
          \n     * StringUtils.getLevenshteinDistance(null, *)             = IllegalArgumentException\n     * StringUtils.getLevenshteinDistance(*, null)             = IllegalArgumentException\n     * StringUtils.getLevenshteinDistance(\"\",\"\")               = 0\n     * StringUtils.getLevenshteinDistance(\"\",\"a\")              = 1\n     * StringUtils.getLevenshteinDistance(\"aaapppp\", \"\")       = 7\n     * StringUtils.getLevenshteinDistance(\"frog\", \"fog\")       = 1\n     * StringUtils.getLevenshteinDistance(\"fly\", \"ant\")        = 3\n     * StringUtils.getLevenshteinDistance(\"elephant\", \"hippo\") = 7\n     * StringUtils.getLevenshteinDistance(\"hippo\", \"elephant\") = 7\n     * StringUtils.getLevenshteinDistance(\"hippo\", \"zzzzzzzz\") = 8\n     * StringUtils.getLevenshteinDistance(\"hello\", \"hallo\")    = 1\n     * 
          \n *\n * @param s the first String, must not be null\n * @param t the second String, must not be null\n * @return result distance\n * @throws IllegalArgumentException if either String input null\n */\n public static int getLevenshteinDistance(String s, String t) {\n if (s == null || t == null) {\n throw new IllegalArgumentException(\"Strings must not be null\");\n }\n /*\n The difference between this impl. and the previous is that, rather\n than creating and retaining a matrix of size s.length()+1 by t.length()+1,\n we maintain two single-dimensional arrays of length s.length()+1. The first, d,\n is the 'current working' distance array that maintains the newest distance cost\n counts as we iterate through the characters of String s. Each time we increment\n the index of String t we are comparing, d is copied to p, the second int[]. Doing so\n allows us to retain the previous cost counts as required by the algorithm (taking\n the minimum of the cost count to the left, up one, and diagonally up and to the left\n of the current cost count being calculated). (Note that the arrays aren't really\n copied anymore, just switched...this is clearly much better than cloning an array\n or doing a System.arraycopy() each time through the outer loop.)\n\n Effectively, the difference between the two implementations is this one does not\n cause an out of memory condition when calculating the LD over two very large strings.\n */\n int n = s.length(); // length of s\n int m = t.length(); // length of t\n if (n == 0) {\n return m;\n } else if (m == 0) {\n return n;\n }\n if (n > m) {\n // swap the input strings to consume less memory\n String tmp = s;\n s = t;\n t = tmp;\n n = m;\n m = t.length();\n }\n int[] p = new int[n + 1]; //'previous' cost array, horizontally\n int[] d = new int[n + 1]; // cost array, horizontally\n int[] _d; //placeholder to assist in swapping p and d\n // indexes into strings s and t\n int i; // iterates through s\n int j; // iterates through t\n char t_j; // jth character of t\n int cost; // cost\n for (i = 0; i <= n; i++) {\n p[i] = i;\n }\n for (j = 1; j <= m; j++) {\n t_j = t.charAt(j - 1);\n d[0] = j;\n for (i = 1; i <= n; i++) {\n cost = s.charAt(i - 1) == t_j ? 0 : 1;\n // minimum of cell to the left+1, to the top+1, diagonally left and up +cost\n d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);\n }\n // copy current distance counts to 'previous row' distance counts\n _d = p;\n p = d;\n d = _d;\n }\n // our last action in the above loop was to switch d and p, so p now\n // actually has the most recent cost counts\n return p[n];\n }\n // startsWith\n //-----------------------------------------------------------------------\n\n /**\n *

          Check if a String starts with a specified prefix.

          \n *\n *

          nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

          \n *\n *
          \n     * StringUtils.startsWith(null, null)      = true\n     * StringUtils.startsWith(null, \"abc\")     = false\n     * StringUtils.startsWith(\"abcdef\", null)  = false\n     * StringUtils.startsWith(\"abcdef\", \"abc\") = true\n     * StringUtils.startsWith(\"ABCDEF\", \"abc\") = false\n     * 
          \n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @return true if the String starts with the prefix, case sensitive, or\n * both null\n * @since 2.4\n */\n public static boolean startsWith(final String str, final String prefix) {\n return StringUtils.startsWith(str, prefix, false);\n }\n\n /**\n *

          Case insensitive check if a String starts with a specified prefix.

          \n *\n *

          nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case insensitive.

          \n *\n *
          \n     * StringUtils.startsWithIgnoreCase(null, null)      = true\n     * StringUtils.startsWithIgnoreCase(null, \"abc\")     = false\n     * StringUtils.startsWithIgnoreCase(\"abcdef\", null)  = false\n     * StringUtils.startsWithIgnoreCase(\"abcdef\", \"abc\") = true\n     * StringUtils.startsWithIgnoreCase(\"ABCDEF\", \"abc\") = true\n     * 
          \n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @return true if the String starts with the prefix, case insensitive, or\n * both null\n * @since 2.4\n */\n public static boolean startsWithIgnoreCase(final String str, final String prefix) {\n return StringUtils.startsWith(str, prefix, true);\n }\n\n /**\n *

          Check if a String starts with a specified prefix (optionally case insensitive).

          \n *\n * @see String#startsWith(String)\n * @param str the String to check, may be null\n * @param prefix the prefix to find, may be null\n * @param ignoreCase inidicates whether the compare should ignore case\n * (case insensitive) or not.\n * @return true if the String starts with the prefix or\n * both null\n */\n private static boolean startsWith(final String str, final String prefix, final boolean ignoreCase) {\n if (str == null || prefix == null) {\n return str == null && prefix == null;\n }\n if (prefix.length() > str.length()) {\n return false;\n }\n return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());\n }\n\n /**\n *

          Check if a String starts with any of an array of specified strings.

          \n *\n *
          \n     * StringUtils.startsWithAny(null, null)      = false\n     * StringUtils.startsWithAny(null, new String[] {\"abc\"})  = false\n     * StringUtils.startsWithAny(\"abcxyz\", null)     = false\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {\"\"}) = false\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {\"abc\"}) = true\n     * StringUtils.startsWithAny(\"abcxyz\", new String[] {null, \"xyz\", \"abc\"}) = true\n     * 
          \n *\n * @see #startsWith(String, String)\n * @param string the String to check, may be null\n * @param searchStrings the Strings to find, may be null or empty\n * @return true if the String starts with any of the the prefixes, case insensitive, or\n * both null\n * @since 2.5\n */\n public static boolean startsWithAny(final String string, final String[] searchStrings) {\n if (StringUtils.isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {\n return false;\n }\n for (String searchString : searchStrings) {\n if (StringUtils.startsWith(string, searchString)) {\n return true;\n }\n }\n return false;\n }\n // endsWith\n //-----------------------------------------------------------------------\n\n /**\n *

          Check if a String ends with a specified suffix.

          \n *\n *

          nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case sensitive.

          \n *\n *
          \n     * StringUtils.endsWith(null, null)      = true\n     * StringUtils.endsWith(null, \"def\")     = false\n     * StringUtils.endsWith(\"abcdef\", null)  = false\n     * StringUtils.endsWith(\"abcdef\", \"def\") = true\n     * StringUtils.endsWith(\"ABCDEF\", \"def\") = false\n     * StringUtils.endsWith(\"ABCDEF\", \"cde\") = false\n     * 
          \n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @return true if the String ends with the suffix, case sensitive, or\n * both null\n * @since 2.4\n */\n public static boolean endsWith(final String str, final String suffix) {\n return StringUtils.endsWith(str, suffix, false);\n }\n\n /**\n *

          Case insensitive check if a String ends with a specified suffix.

          \n *\n *

          nulls are handled without exceptions. Two null\n * references are considered to be equal. The comparison is case insensitive.

          \n *\n *
          \n     * StringUtils.endsWithIgnoreCase(null, null)      = true\n     * StringUtils.endsWithIgnoreCase(null, \"def\")     = false\n     * StringUtils.endsWithIgnoreCase(\"abcdef\", null)  = false\n     * StringUtils.endsWithIgnoreCase(\"abcdef\", \"def\") = true\n     * StringUtils.endsWithIgnoreCase(\"ABCDEF\", \"def\") = true\n     * StringUtils.endsWithIgnoreCase(\"ABCDEF\", \"cde\") = false\n     * 
          \n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @return true if the String ends with the suffix, case insensitive, or\n * both null\n * @since 2.4\n */\n public static boolean endsWithIgnoreCase(final String str, final String suffix) {\n return StringUtils.endsWith(str, suffix, true);\n }\n\n /**\n *

          Check if a String ends with a specified suffix (optionally case insensitive).

          \n *\n * @see String#endsWith(String)\n * @param str the String to check, may be null\n * @param suffix the suffix to find, may be null\n * @param ignoreCase inidicates whether the compare should ignore case\n * (case insensitive) or not.\n * @return true if the String starts with the prefix or\n * both null\n */\n private static boolean endsWith(final String str, final String suffix, final boolean ignoreCase) {\n if (str == null || suffix == null) {\n return str == null && suffix == null;\n }\n if (suffix.length() > str.length()) {\n return false;\n }\n int strOffset = str.length() - suffix.length();\n return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());\n }\n\n /**\n *

          \n * Similar to http://www.w3.org/TR/xpath/#function-normalize\n * -space\n *

          \n *

          \n * The function returns the argument string with whitespace normalized by using\n * {@link #trim(String)} to remove leading and trailing whitespace\n * and then replacing sequences of whitespace characters by a single space.\n *

          \n * In XML Whitespace characters are the same as those allowed by the S production, which is S ::= (#x20 | #x9 | #xD | #xA)+\n *

          \n * See Java's {@link Character#isWhitespace(char)} for which characters are considered whitespace.\n *

          \n * The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also\n * normalize. Additonally {@link #trim(String)} removes control characters (char <= 32) from both\n * ends of this String.\n *

          \n *\n * @see Character#isWhitespace(char)\n * @see #trim(String)\n * @see \n * http://www.w3.org/TR/xpath/#function-normalize-space\n * @param str the source String to normalize whitespaces from, may be null\n * @return the modified string with whitespace normalized, null if null String input\n *\n * @since 2.6\n */\n public static String normalizeSpace(String str) {\n str = StringUtils.strip(str);\n if (str == null || str.length() <= 2) {\n return str;\n }\n StringBuilder b = new StringBuilder(str.length());\n for (int i = 0; i < str.length(); i++) {\n char c = str.charAt(i);\n if (Character.isWhitespace(c)) {\n if (i > 0 && !Character.isWhitespace(str.charAt(i - 1))) {\n b.append(' ');\n }\n } else {\n b.append(c);\n }\n }\n return b.toString();\n }\n\n /**\n *

          Check if a String ends with any of an array of specified strings.

          \n *\n *
          \n     * StringUtils.endsWithAny(null, null)      = false\n     * StringUtils.endsWithAny(null, new String[] {\"abc\"})  = false\n     * StringUtils.endsWithAny(\"abcxyz\", null)     = false\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {\"\"}) = true\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {\"xyz\"}) = true\n     * StringUtils.endsWithAny(\"abcxyz\", new String[] {null, \"xyz\", \"abc\"}) = true\n     * 
          \n *\n * @param string the String to check, may be null\n * @param searchStrings the Strings to find, may be null or empty\n * @return true if the String ends with any of the the prefixes, case insensitive, or\n * both null\n * @since 2.6\n */\n public static boolean endsWithAny(final String string, final String[] searchStrings) {\n if (StringUtils.isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {\n return false;\n }\n for (String searchString : searchStrings) {\n if (StringUtils.endsWith(string, searchString)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 转换首字母大写。\n *
          \n     * StringUtils.firstCharToUpperCase(null)      = null\n     * StringUtils.firstCharToUpperCase(\"\")        = \"\"\n     * StringUtils.firstCharToUpperCase(\"abc\")     = \"Abc\"\n     * StringUtils.firstCharToUpperCase(\"Abc\")     = \"Abc\"\n     * StringUtils.firstCharToUpperCase(\"ABC\")     = \"ABC\"\n     * 
          \n */\n public static String firstCharToUpperCase(final String value) {\n if (StringUtils.isBlank(value)) {\n return value;\n }\n StringBuilder sb = new StringBuilder(value);\n char firstChar = sb.charAt(0);\n sb.delete(0, 1);\n sb.insert(0, (char) (firstChar >= 97 ? firstChar - 32 : firstChar));\n return sb.toString();\n }\n\n /**\n * 转换首字母小写。\n *
          \n     * StringUtils.firstCharToLowerCase(null)      = null\n     * StringUtils.firstCharToLowerCase(\"\")        = \"\"\n     * StringUtils.firstCharToLowerCase(\"abc\")     = \"abc\"\n     * StringUtils.firstCharToLowerCase(\"Abc\")     = \"abc\"\n     * StringUtils.firstCharToLowerCase(\"ABC\")     = \"aBC\"\n     * 
          \n */\n public static String firstCharToLowerCase(final String value) {\n if (StringUtils.isBlank(value)) {\n return value;\n }\n StringBuilder sb = new StringBuilder(value);\n char firstChar = sb.charAt(0);\n sb.delete(0, 1);\n sb.insert(0, (char) (firstChar <= 90 ? firstChar + 32 : firstChar));\n return sb.toString();\n }\n\n /**\n * 执行字符串匹配。\n *
          \n     * StringUtils.equalsBlankIgnoreCase(null,\"\")         = true\n     * StringUtils.equalsBlankIgnoreCase(\"\",\"\")           = true\n     * StringUtils.equalsBlankIgnoreCase(\" \",\"\")          = true\n     * StringUtils.equalsBlankIgnoreCase(\" \",null)        = true\n     * StringUtils.equalsBlankIgnoreCase(\"bob\",\"\")        = false\n     * StringUtils.equalsBlankIgnoreCase(\"  bob  \",\"bob\") = true\n     * 
          \n */\n public static boolean equalsBlankIgnoreCase(final String str1, final String str2) {\n return StringUtils.equalsIgnoreCase(StringUtils.trimToEmpty(str1), StringUtils.trimToEmpty(str2));\n }\n\n /* ------------------------------------------------------------ */\n private static final char[] escapes = new char[32];\n\n static {\n Arrays.fill(escapes, (char) 0xFFFF);\n escapes['\\b'] = 'b';\n escapes['\\t'] = 't';\n escapes['\\n'] = 'n';\n escapes['\\f'] = 'f';\n escapes['\\r'] = 'r';\n }\n\n /** Quote a string into an Appendable.\n * The characters \", \\, \\n, \\r, \\t, \\f and \\b are escaped\n * @param input The String to quote.\n */\n public static String quote(String input) {\n StringBuilder buffer = new StringBuilder();\n quote(buffer, input);\n return buffer.toString();\n }\n\n public static void quote(Appendable buffer, String input) {\n try {\n buffer.append('\"');\n for (int i = 0; i < input.length(); ++i) {\n char c = input.charAt(i);\n if (c >= 32) {\n if (c == '\"' || c == '\\\\')\n buffer.append('\\\\');\n buffer.append(c);\n } else {\n char escape = escapes[c];\n if (escape == 0xFFFF) {\n // Unicode escape\n buffer.append('\\\\').append('u').append('0').append('0');\n if (c < 0x10)\n buffer.append('0');\n buffer.append(Integer.toString(c, 16));\n } else {\n buffer.append('\\\\').append(escape);\n }\n }\n }\n buffer.append('\"');\n } catch (IOException x) {\n throw new RuntimeException(x);\n }\n }\n\n /** Object to String ,when null object then null else return toString(); */\n public static String toString(Object object) {\n return (object == null) ? null : object.toString();\n }\n}", "file_name": "StringUtils.java", "human_label": "Return the given string's length.If the string is null,and zero will be returned.", "level": "self_contained", "lineno": "4474", "name": "length", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636767ab1a6d9265ec018676", "all_context": "{ \"class_level\" : \"import java.math.BigInteger;\\nimport java.nio.ByteBuffer;\\nimport java.nio.charset.Charset;\\nCharset UTF8;\\nCharset ISO_8859_1;\\nlong serialVersionUID;\\nTextFormat();\\nunescapeBytes(CharSequence input);\\nInvalidEscapeSequenceException(String description);\\nescapeText(String input);\\nunescapeText(String input);\\nisOctal(char c);\\nisHex(char c);\\ndigitValue(char c);\\nparseInt32(String text);\\nparseUInt32(String text);\\nparseInt64(String text);\\nparseUInt64(String text);\\nparseInteger(String text,boolean isSigned,boolean isLong);\\nescapeBytes(ByteBuffer input);\\n\", \"repo_level\" : \"\" }", "class_name": "TextFormat", "code": "private static boolean isHex(final char c){\n return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F');\n}\n", "docstring": "/** \n * Is this a hex digit?\n */\n", "end_lineno": "298", "file_content": "//========================================================================\n//Copyright 2007-2009 David Yu dyuproject@gmail.com\n//------------------------------------------------------------------------\n//Licensed under the Apache License, Version 2.0 (the \"License\");\n//you may not use this file except in compliance with the License.\n//You may obtain a copy of the License at \n//http://www.apache.org/licenses/LICENSE-2.0\n//Unless required by applicable law or agreed to in writing, software\n//distributed under the License is distributed on an \"AS IS\" BASIS,\n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//See the License for the specific language governing permissions and\n//limitations under the License.\n//========================================================================\n\n// Protocol Buffers - Google's data interchange format\n// Copyright 2008 Google Inc. All rights reserved.\n// http://code.google.com/p/protobuf/\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\npackage io.protostuff.parser;\n\nimport java.math.BigInteger;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.Charset;\n\n/**\n * Provide ascii text parsing and formatting support for proto2 instances. The implementation largely follows\n * google/protobuf/text_format.cc.\n * \n * @author wenboz@google.com Wenbo Zhu\n * @author kenton@google.com Kenton Varda\n * @author David Yu\n */\npublic final class TextFormat\n{\n private TextFormat()\n {\n }\n\n static final Charset UTF8 = Charset.forName(\"UTF-8\"), ISO_8859_1 = Charset.forName(\"ISO-8859-1\");\n\n // =================================================================\n // Utility functions\n //\n // Some of these methods are package-private because Descriptors.java uses\n // them.\n\n /**\n * Escapes bytes in the format used in protocol buffer text format, which is the same as the format used for C\n * string literals. All bytes that are not printable 7-bit ASCII characters are escaped, as well as backslash,\n * single-quote, and double-quote characters. Characters for which no defined short-hand escape sequence is defined\n * will be escaped using 3-digit octal sequences.\n */\n static StringBuilder escapeBytes(ByteBuffer input)\n {\n // input.flip();\n int length = input.limit();\n final StringBuilder builder = new StringBuilder(length);\n for (int i = 0; i < length; i++)\n {\n final byte b = input.get(i);\n switch (b)\n {\n // Java does not recognize \\a or \\v, apparently.\n case 0x07:\n builder.append(\"\\\\007\");\n break;\n case '\\b':\n builder.append(\"\\\\b\");\n break;\n case '\\f':\n builder.append(\"\\\\f\");\n break;\n case '\\n':\n builder.append(\"\\\\n\");\n break;\n case '\\r':\n builder.append(\"\\\\r\");\n break;\n case '\\t':\n builder.append(\"\\\\t\");\n break;\n case 0x0b:\n builder.append(\"\\\\013\");\n break;\n case '\\\\':\n builder.append(\"\\\\\\\\\");\n break;\n case '\\'':\n builder.append(\"\\\\\\'\");\n break;\n case '\"':\n builder.append(\"\\\\\\\"\");\n break;\n default:\n if (b >= 0x20)\n {\n builder.append((char) b);\n }\n else\n {\n builder.append('\\\\');\n builder.append((char) ('0' + ((b >>> 6) & 3)));\n builder.append((char) ('0' + ((b >>> 3) & 7)));\n builder.append((char) ('0' + (b & 7)));\n }\n break;\n }\n }\n return builder;\n }\n\n /**\n * Un-escape a byte sequence as escaped using {@link #escapeBytes(ByteString)}. Two-digit hex escapes (starting with\n * \"\\x\") are also recognized.\n */\n static ByteBuffer unescapeBytes(final CharSequence input)\n {\n int pos = 0, len = input.length();\n final byte[] result = new byte[len];\n ByteBuffer buffer = ByteBuffer.wrap(result);\n for (int i = 0; i < len; i++)\n {\n char c = input.charAt(i);\n if (c == '\\\\')\n {\n if (i + 1 < len)\n {\n ++i;\n c = input.charAt(i);\n if (isOctal(c))\n {\n // Octal escape.\n int code = digitValue(c);\n if (i + 1 < len && isOctal(input.charAt(i + 1)))\n {\n ++i;\n code = code * 8 + digitValue(input.charAt(i));\n }\n if (i + 1 < len && isOctal(input.charAt(i + 1)))\n {\n ++i;\n code = code * 8 + digitValue(input.charAt(i));\n }\n result[pos++] = (byte) code;\n }\n else\n {\n switch (c)\n {\n case 'a':\n result[pos++] = 0x07;\n break;\n case 'b':\n result[pos++] = '\\b';\n break;\n case 'f':\n result[pos++] = '\\f';\n break;\n case 'n':\n result[pos++] = '\\n';\n break;\n case 'r':\n result[pos++] = '\\r';\n break;\n case 't':\n result[pos++] = '\\t';\n break;\n case 'v':\n result[pos++] = 0x0b;\n break;\n case '\\\\':\n result[pos++] = '\\\\';\n break;\n case '\\'':\n result[pos++] = '\\'';\n break;\n case '\"':\n result[pos++] = '\\\"';\n break;\n\n case 'x':\n // hex escape\n int code = 0;\n if (i + 1 < len && isHex(input.charAt(i + 1)))\n {\n ++i;\n code = digitValue(input.charAt(i));\n }\n else\n {\n throw new InvalidEscapeSequenceException(\n \"Invalid escape sequence: '\\\\x' with no digits\");\n }\n if (i + 1 < len && isHex(input.charAt(i + 1)))\n {\n ++i;\n code = code * 16 + digitValue(input.charAt(i));\n }\n result[pos++] = (byte) code;\n break;\n\n default:\n throw new InvalidEscapeSequenceException(\n \"Invalid escape sequence: '\\\\\" + c + '\\'');\n }\n }\n }\n else\n {\n throw new InvalidEscapeSequenceException(\n \"Invalid escape sequence: '\\\\' at end of string.\");\n }\n }\n else\n {\n result[pos++] = (byte) c;\n }\n }\n buffer.limit(pos);\n return buffer;\n }\n\n /**\n * Thrown by {@link TextFormat#unescapeBytes} and {@link TextFormat#unescapeText} when an invalid escape sequence is\n * seen.\n */\n static class InvalidEscapeSequenceException extends RuntimeException\n {\n private static final long serialVersionUID = -8164033650142593305L;\n\n InvalidEscapeSequenceException(final String description)\n {\n super(description);\n }\n }\n\n /**\n * Like {@link #escapeBytes(ByteString)}, but escapes a text string. Non-ASCII characters are first encoded as\n * UTF-8, then each byte is escaped individually as a 3-digit octal escape. Yes, it's weird.\n */\n static String escapeText(final String input)\n {\n return escapeBytes(ByteBuffer.wrap(input.getBytes(ISO_8859_1))).toString();\n }\n\n /**\n * Un-escape a text string as escaped using {@link #escapeText(String)}. Two-digit hex escapes (starting with \"\\x\")\n * are also recognized.\n */\n static String unescapeText(String input)\n {\n ByteBuffer buffer = unescapeBytes(input);\n return new String(buffer.array(), buffer.position(), buffer.limit(), ISO_8859_1);\n }\n\n /**\n * Is this an octal digit?\n */\n private static boolean isOctal(final char c)\n {\n return '0' <= c && c <= '7';\n }\n\n /**\n * Is this a hex digit?\n */\n private static boolean isHex(final char c)\n {\n return ('0' <= c && c <= '9') ||\n ('a' <= c && c <= 'f') ||\n ('A' <= c && c <= 'F');\n }\n\n /**\n * Interpret a character as a digit (in any base up to 36) and return the numeric value. This is like\n * {@code Character.digit()} but we don't accept non-ASCII digits.\n */\n private static int digitValue(final char c)\n {\n if ('0' <= c && c <= '9')\n {\n return c - '0';\n }\n else if ('a' <= c && c <= 'z')\n {\n return c - 'a' + 10;\n }\n else\n {\n return c - 'A' + 10;\n }\n }\n\n /**\n * Parse a 32-bit signed integer from the text. Unlike the Java standard {@code Integer.parseInt()}, this function\n * recognizes the prefixes \"0x\" and \"0\" to signify hexidecimal and octal numbers, respectively.\n */\n static int parseInt32(final String text) throws NumberFormatException\n {\n return (int) parseInteger(text, true, false);\n }\n\n /**\n * Parse a 32-bit unsigned integer from the text. Unlike the Java standard {@code Integer.parseInt()}, this function\n * recognizes the prefixes \"0x\" and \"0\" to signify hexidecimal and octal numbers, respectively. The result is\n * coerced to a (signed) {@code int} when returned since Java has no unsigned integer type.\n */\n static int parseUInt32(final String text) throws NumberFormatException\n {\n return (int) parseInteger(text, false, false);\n }\n\n /**\n * Parse a 64-bit signed integer from the text. Unlike the Java standard {@code Integer.parseInt()}, this function\n * recognizes the prefixes \"0x\" and \"0\" to signify hexidecimal and octal numbers, respectively.\n */\n static long parseInt64(final String text) throws NumberFormatException\n {\n return parseInteger(text, true, true);\n }\n\n /**\n * Parse a 64-bit unsigned integer from the text. Unlike the Java standard {@code Integer.parseInt()}, this function\n * recognizes the prefixes \"0x\" and \"0\" to signify hexidecimal and octal numbers, respectively. The result is\n * coerced to a (signed) {@code long} when returned since Java has no unsigned long type.\n */\n static long parseUInt64(final String text) throws NumberFormatException\n {\n return parseInteger(text, false, true);\n }\n\n private static long parseInteger(final String text,\n final boolean isSigned,\n final boolean isLong)\n throws NumberFormatException\n {\n int pos = 0;\n\n boolean negative = false;\n if (text.startsWith(\"-\", pos))\n {\n if (!isSigned)\n {\n throw new NumberFormatException(\"Number must be positive: \" + text);\n }\n ++pos;\n negative = true;\n }\n\n int radix = 10;\n if (text.startsWith(\"0x\", pos))\n {\n pos += 2;\n radix = 16;\n }\n else if (text.startsWith(\"0\", pos))\n {\n radix = 8;\n }\n\n final String numberText = text.substring(pos);\n\n long result = 0;\n if (numberText.length() < 16)\n {\n // Can safely assume no overflow.\n result = Long.parseLong(numberText, radix);\n if (negative)\n {\n result = -result;\n }\n\n // Check bounds.\n // No need to check for 64-bit numbers since they'd have to be 16 chars\n // or longer to overflow.\n if (!isLong)\n {\n if (isSigned)\n {\n if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)\n {\n throw new NumberFormatException(\n \"Number out of range for 32-bit signed integer: \" + text);\n }\n }\n else\n {\n if (result >= (1L << 32) || result < 0)\n {\n throw new NumberFormatException(\n \"Number out of range for 32-bit unsigned integer: \" + text);\n }\n }\n }\n }\n else\n {\n BigInteger bigValue = new BigInteger(numberText, radix);\n if (negative)\n {\n bigValue = bigValue.negate();\n }\n\n // Check bounds.\n if (!isLong)\n {\n if (isSigned)\n {\n if (bigValue.bitLength() > 31)\n {\n throw new NumberFormatException(\n \"Number out of range for 32-bit signed integer: \" + text);\n }\n }\n else\n {\n if (bigValue.bitLength() > 32)\n {\n throw new NumberFormatException(\n \"Number out of range for 32-bit unsigned integer: \" + text);\n }\n }\n }\n else\n {\n if (isSigned)\n {\n if (bigValue.bitLength() > 63)\n {\n throw new NumberFormatException(\n \"Number out of range for 64-bit signed integer: \" + text);\n }\n }\n else\n {\n if (bigValue.bitLength() > 64)\n {\n throw new NumberFormatException(\n \"Number out of range for 64-bit unsigned integer: \" + text);\n }\n }\n }\n\n result = bigValue.longValue();\n }\n\n return result;\n }\n}\n", "file_name": "TextFormat.java", "human_label": "Return true if the given character is a hex digit,otherwise return false.", "level": "self_contained", "lineno": "290", "name": "isHex", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "io.protostuff.parser", "project": "protostuff-master" }, { "_id": "636766f81a6d9265ec017748", "all_context": "{ \"class_level\" : \"import java.nio.charset.StandardCharsets;\\nimport java.security.NoSuchAlgorithmException;\\nString Base64Chars;\\nbase64EncodeFoArray(byte[] s);\\nbase64Decode(String s);\\nbase64DecodeToArray(String s);\\nencodeMD5(byte[] source);\\ngetMD5(String source);\\ngetMD5(byte[] source);\\nstr2HexStr(String str);\\nhexStr2Str(String hexStr);\\nbyte2HexStr(byte[] b);\\nhexStr2Bytes(String src);\\nstringToUnicode(String strText);\\nunicodeToString(String hex);\\nuniteBytes(String src0,String src1);\\nbase64Encode(String s);\\n\", \"repo_level\" : \"\" }", "class_name": "CommonCodeUtils", "code": "public static String base64Decode(final String s){\n byte[] b=Base64.base64DecodeToArray(s);\n if (b == null) {\n return null;\n }\n if (b.length == 0) {\n return \"\";\n }\n return new String(b,StandardCharsets.UTF_8);\n}\n", "docstring": "/** \n * Decoding a string to a string follow the Base64 regular. \n */\n", "end_lineno": "101", "file_content": "/*\n * Copyright 2008-2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.nio.charset.StandardCharsets;\nimport java.security.NoSuchAlgorithmException;\n\n/**\n *\n * @version : 2012-6-21\n * @author 赵永春 (zyc@hasor.net)\n */\npublic class CommonCodeUtils {\n /**\n * 简单编码类,该类提供了Base64的编码,该编码器与配套的js编码器可以实现互相编码互相转化功能。\n * @version 2009-4-28\n * @author 赵永春 (zyc@hasor.net)\n */\n public static abstract class Base64 {\n protected static final String Base64Chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*-\"; // supplement\n /***/\n // /**返回与Base64对应的JSbase64编码/解码脚本*/\n // public static Reader getJSReader() throws UnsupportedEncodingException {\n // return new InputStreamReader(Base64.class.getResourceAsStream(\"/META-INF/resource/util/base64.js\"), \"utf-8\");\n // };\n\n /**\n * 使用UTF-8编码进行Base64编码\n * @param s 要编码的原始数据\n * @return 返回编码之后的字符串。\n */\n public static String base64Encode(final String s) {\n if (s == null || s.length() == 0) {\n return s;\n }\n byte[] b = null;\n b = s.getBytes(StandardCharsets.UTF_8);\n return Base64.base64EncodeFoArray(b);\n }\n\n /** Encoding a byte array to a string follow the Base64 regular. */\n public static String base64EncodeFoArray(final byte[] s) {\n if (s == null) {\n return null;\n }\n if (s.length == 0) {\n return \"\";\n }\n StringBuffer buf = new StringBuffer();\n int b0, b1, b2, b3;\n int len = s.length;\n int i = 0;\n while (i < len) {\n byte tmp = s[i++];\n b0 = (tmp & 0xfc) >> 2;\n b1 = (tmp & 0x03) << 4;\n if (i < len) {\n tmp = s[i++];\n b1 |= (tmp & 0xf0) >> 4;\n b2 = (tmp & 0x0f) << 2;\n if (i < len) {\n tmp = s[i++];\n b2 |= (tmp & 0xc0) >> 6;\n b3 = tmp & 0x3f;\n } else {\n b3 = 64; // 1 byte \"-\" is supplement\n }\n } else {\n b2 = b3 = 64;// 2 bytes \"-\" are supplement\n }\n buf.append(Base64.Base64Chars.charAt(b0));\n buf.append(Base64.Base64Chars.charAt(b1));\n buf.append(Base64.Base64Chars.charAt(b2));\n buf.append(Base64.Base64Chars.charAt(b3));\n }\n return buf.toString();\n }\n\n /** Decoding a string to a string follow the Base64 regular. */\n public static String base64Decode(final String s) {\n byte[] b = Base64.base64DecodeToArray(s);\n if (b == null) {\n return null;\n }\n if (b.length == 0) {\n return \"\";\n }\n return new String(b, StandardCharsets.UTF_8);\n }\n\n /** Decoding a string to a byte array follow the Base64 regular */\n public static byte[] base64DecodeToArray(final String s) {\n if (s == null) {\n return null;\n }\n int len = s.length();\n if (len == 0) {\n return new byte[0];\n }\n if (len % 4 != 0) {\n throw new IllegalArgumentException(s);\n }\n byte[] b = new byte[len / 4 * 3];\n int i = 0, j = 0, e = 0, c, tmp;\n while (i < len) {\n c = Base64.Base64Chars.indexOf(s.charAt(i++));\n tmp = c << 18;\n c = Base64.Base64Chars.indexOf(s.charAt(i++));\n tmp |= c << 12;\n c = Base64.Base64Chars.indexOf(s.charAt(i++));\n if (c < 64) {\n tmp |= c << 6;\n c = Base64.Base64Chars.indexOf(s.charAt(i++));\n if (c < 64) {\n tmp |= c;\n } else {\n e = 1;\n }\n } else {\n e = 2;\n i++;\n }\n b[j + 2] = (byte) (tmp & 0xff);\n tmp >>= 8;\n b[j + 1] = (byte) (tmp & 0xff);\n tmp >>= 8;\n b[j + 0] = (byte) (tmp & 0xff);\n j += 3;\n }\n if (e != 0) {\n len = b.length - e;\n byte[] copy = new byte[len];\n System.arraycopy(b, 0, copy, 0, len);\n return copy;\n }\n return b;\n }\n }\n\n /**\n * MD5算法提供\n * @version : 2011-11-7\n * @author 赵永春 (zyc@hasor.net)\n */\n public static abstract class MD5 {\n public static String encodeMD5(final byte[] source) throws NoSuchAlgorithmException {\n String s = null;\n // 用来将字节转换成 16 进制表示的字符\n char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n java.security.MessageDigest md = java.security.MessageDigest.getInstance(\"MD5\");\n md.update(source);\n byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数,用字节表示就是 16 个字节\n char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符,所以表示成 16 进制需要 32 个字符\n int k = 0; // 表示转换结果中对应的字符位置\n for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节转换成 16 进制字符的转换\n byte byte0 = tmp[i]; // 取第 i 个字节\n str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, >>> 为逻辑右移,将符号位一起右移\n str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换\n }\n s = new String(str); // 换后的结果转换为字符串\n return s;\n }\n\n public static String getMD5(final String source) throws NoSuchAlgorithmException {\n return MD5.getMD5(source.getBytes());\n }\n\n public static String getMD5(final byte[] source) throws NoSuchAlgorithmException {\n String s = null;\n // 用来将字节转换成 16 进制表示的字符\n char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n java.security.MessageDigest md = java.security.MessageDigest.getInstance(\"MD5\");\n md.update(source);\n byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数,用字节表示就是 16 个字节\n char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符,所以表示成 16 进制需要 32 个字符\n int k = 0; // 表示转换结果中对应的字符位置\n for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节转换成 16 进制字符的转换\n byte byte0 = tmp[i]; // 取第 i 个字节\n str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, >>> 为逻辑右移,将符号位一起右移\n str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换\n }\n s = new String(str); // 换后的结果转换为字符串\n return s;\n }\n }\n\n /**\n * 基于十六进制的字符转换\n * @version : 2013-8-13\n * @author 赵永春 (zyc@hasor.net)\n */\n public static abstract class HexConversion {\n /** 字符串转换成十六进制字符串 */\n public static String str2HexStr(final String str) {\n char[] chars = \"0123456789ABCDEF\".toCharArray();\n StringBuilder sb = new StringBuilder(\"\");\n byte[] bs = str.getBytes();\n int bit;\n for (byte element : bs) {\n bit = (element & 0x0f0) >> 4;\n sb.append(chars[bit]);\n bit = element & 0x0f;\n sb.append(chars[bit]);\n }\n return sb.toString();\n }\n\n /** 十六进制转换字符串 */\n public static String hexStr2Str(final String hexStr) {\n String str = \"0123456789ABCDEF\";\n char[] hexs = hexStr.toCharArray();\n byte[] bytes = new byte[hexStr.length() / 2];\n int n;\n for (int i = 0; i < bytes.length; i++) {\n n = str.indexOf(hexs[2 * i]) * 16;\n n += str.indexOf(hexs[2 * i + 1]);\n bytes[i] = (byte) (n & 0xff);\n }\n return new String(bytes);\n }\n\n /** bytes转换成十六进制字符串 */\n public static String byte2HexStr(final byte[] b) {\n String hs = \"\";\n String stmp = \"\";\n for (byte element : b) {\n stmp = Integer.toHexString(element & 0XFF);\n if (stmp.length() == 1) {\n hs = hs + \"0\" + stmp;\n } else {\n hs = hs + stmp;\n //if (n 128) {\n strRet += \"\\\\u\" + strHex;\n } else {\n // 低位在前面补00\n strRet += \"\\\\u00\" + strHex;\n }\n }\n return strRet;\n }\n\n /** unicode的String转换成String的字符串 */\n public static String unicodeToString(final String hex) {\n int t = hex.length() / 6;\n StringBuilder str = new StringBuilder();\n for (int i = 0; i < t; i++) {\n String s = hex.substring(i * 6, (i + 1) * 6);\n // 高位需要补上00再转\n String s1 = s.substring(2, 4) + \"00\";\n // 低位直接转\n String s2 = s.substring(4);\n // 将16进制的string转为int\n int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);\n // 将int转换为字符\n char[] chars = Character.toChars(n);\n str.append(new String(chars));\n }\n return str.toString();\n }\n\n private static byte uniteBytes(final String src0, final String src1) {\n byte b0 = Byte.decode(\"0x\" + src0).byteValue();\n b0 = (byte) (b0 << 4);\n byte b1 = Byte.decode(\"0x\" + src1).byteValue();\n byte ret = (byte) (b0 | b1);\n return ret;\n }\n }\n}", "file_name": "CommonCodeUtils.java", "human_label": "Decoding a string follow the Base64 regular to an array,and return a string constructed from the array according to UTF_8.", "level": "class_runnable", "lineno": "91", "name": "base64Decode", "oracle_context": "{ \"apis\" : \"[base64DecodeToArray]\", \"classes\" : \"[byte[], StandardCharsets]\", \"vars\" : \"[length, UTF_8]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636766f11a6d9265ec017663", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static boolean isSameLength(final double[] array1,final double[] array2){\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n}\n", "docstring": "/** \n *

          Checks whether two arrays are the same length, treating null arrays as length 0.

          \n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treatingnull as an empty array\n */\n", "end_lineno": "1146", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

          Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

          \n *\n *

          This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

          \n *\n *

          #ThreadSafe#

          \n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

          ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

          \n *\n *

          This constructor is public to permit tools that require a JavaBean instance\n * to operate.

          \n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

          \n *\n *

          This method can be used to initialize:

          \n *
          \n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

          Shallow clones an array returning a typecast result and handling\n * null.

          \n *\n *

          The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

          Produces a new array containing the elements between\n * the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n *

          The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

          \n *\n *
          \n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new long array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new int array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new short array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new char array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new byte array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new double array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new float array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new boolean array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

          Any multi-dimensional aspects of the arrays are ignored.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

          \n *\n *

          If the input array is null, 0 is returned.

          \n *\n *
          \n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
          \n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

          Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

          \n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          There is no special handling for multi-dimensional arrays.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given object in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

          Finds the index of the given object in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given object within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given object in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the object is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

          \n *\n *

          The method returns false if a null array\n * is passed in.

          \n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Characters to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Character to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive chars to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Longs to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Long to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive longs to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Integers to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Integer to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive ints to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Shorts to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Short to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive shorts to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Bytes to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Bytes to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive bytes to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Doubles to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Doubles to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive doubles to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Floats to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Floats to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive floats to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Booleans to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Booleans to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive booleans to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

          Checks if an array of Objects is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive longs is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive ints is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive shorts is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive chars is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive bytes is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive doubles is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive floats is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive booleans is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

          Checks if an array of Objects is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive longs is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive ints is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive shorts is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive chars is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive bytes is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive doubles is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive floats is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive booleans is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

          \n *\n *
          \n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
          \n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Return true if the length of array1 is the same as the length of array2 or both them are null,otherwise return false.", "level": "self_contained", "lineno": "1132", "name": "isSameLength", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[length]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "6367667d1a6d9265ec0173ff", "all_context": "{ \"class_level\" : \"import org.slf4j.Logger;\\nimport org.slf4j.LoggerFactory;\\nimport javax.servlet.http.HttpServletRequest;\\nimport javax.servlet.http.HttpServletResponse;\\nimport java.util.List;\\nimport java.util.concurrent.TimeUnit;\\nimport java.util.concurrent.atomic.AtomicBoolean;\\nimport static org.atmosphere.cpr.AtmosphereResourceImpl.METEOR;\\nimport static org.atmosphere.cpr.FrameworkConfig.ATMOSPHERE_RESOURCE;\\nLogger logger;\\nAtmosphereResource r;\\nObject o;\\nAtomicBoolean isDestroyed;\\nMeteor(AtmosphereResource r,List l,Serializer s);\\nbuild(HttpServletRequest r);\\nbuild(HttpServletRequest r,Serializer s);\\nbuild(HttpServletRequest req,List l,Serializer s);\\nbuild(HttpServletRequest req,SCOPE scope,List l,Serializer s);\\nsuspend(long l);\\nresumeOnBroadcast(boolean resumeOnBroadcast);\\ntransport();\\nsuspend(long timeout,TimeUnit timeunit);\\nresume();\\nbroadcast(Object o);\\nschedule(Object o,long period);\\ndelayBroadadcast(Object o,long period);\\ngetBroadcaster();\\nsetBroadcaster(Broadcaster b);\\nattachement();\\nattach(Object o);\\naddListener(AtmosphereResourceEventListener e);\\nremoveListener(AtmosphereResourceEventListener e);\\ndestroy();\\ndestroyed();\\ngetAtmosphereResource();\\ngetAtmosphereConfig();\\n\", \"repo_level\" : \"\" }", "class_name": "Meteor", "code": "public static Meteor lookup(HttpServletRequest r){\n Object o=r.getAttribute(METEOR);\n return o == null ? null : Meteor.class.isAssignableFrom(o.getClass()) ? (Meteor)o : null;\n}\n", "docstring": "/** \n * Retrieve an instance of {@link Meteor} based on the {@link HttpServletRequest}.\n * @param r {@link HttpServletRequest}\n * @return a {@link Meteor} or null if not found\n */\n", "end_lineno": "74", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n\npackage org.atmosphere.cpr;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport java.util.List;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\nimport static org.atmosphere.cpr.AtmosphereResourceImpl.METEOR;\nimport static org.atmosphere.cpr.FrameworkConfig.ATMOSPHERE_RESOURCE;\n\n/**\n * A {@link Meteor} is a simple class that can be used from a {@link javax.servlet.Servlet}\n * to suspend, broadcast and resume responses. A {@link Meteor} can be created by invoking\n * the build() method.\n *

          \n * Meteor.build(HttpServletRequest).suspend(-1);\n *

          \n * A Meteor is usually created when an application needs to suspend a response.\n * A Meteor instance can then be cached and re-used later for either\n * broadcasting a message, or when an application needs to resume the\n * suspended response.\n *\n * @author Jeanfrancois Arcand\n */\npublic class Meteor {\n\n private static final Logger logger = LoggerFactory.getLogger(Meteor.class);\n\n private final AtmosphereResource r;\n private Object o;\n private final AtomicBoolean isDestroyed = new AtomicBoolean(false);\n\n private Meteor(AtmosphereResource r,\n List l, Serializer s) {\n\n this.r = r;\n this.r.setSerializer(s);\n if (l != null) {\n for (BroadcastFilter f : l) {\n this.r.getBroadcaster().getBroadcasterConfig().addFilter(f);\n }\n }\n }\n\n /**\n * Retrieve an instance of {@link Meteor} based on the {@link HttpServletRequest}.\n *\n * @param r {@link HttpServletRequest}\n * @return a {@link Meteor} or null if not found\n */\n public static Meteor lookup(HttpServletRequest r) {\n Object o = r.getAttribute(METEOR);\n return o == null ? null : Meteor.class.isAssignableFrom(o.getClass()) ? (Meteor) o : null;\n }\n\n /**\n * Create a {@link Meteor} using the {@link HttpServletRequest}.\n *\n * @param r an {@link HttpServletRequest}\n * @return a {@link Meteor} than can be used to resume, suspend and broadcast {@link Object}\n */\n public static Meteor build(HttpServletRequest r) {\n return build(r, null);\n }\n\n /**\n * Create a {@link Meteor} using the {@link HttpServletRequest} and use the\n * {@link Serializer} for writing the result of a broadcast operation using\n * the {@link HttpServletResponse}.\n *\n * @param r an {@link HttpServletRequest}\n * @param s a {@link Serializer} used when writing broadcast events\n * @return a {@link Meteor} than can be used to resume, suspend and broadcast {@link Object}\n */\n public static Meteor build(HttpServletRequest r, Serializer s) {\n return build(r, null, s);\n }\n\n /**\n * Create a {@link Meteor} using the {@link HttpServletRequest} and use a list of\n * {@link BroadcastFilter} and {@link Serializer} for writing the result\n * of a broadcast operation the {@link HttpServletResponse}.\n *\n * @param req an {@link HttpServletRequest}\n * @param l a list of {@link BroadcastFilter}\n * @param s a {@link Serializer} used when writing broadcast events\n * @return a {@link Meteor} than can be used to resume, suspend and broadcast {@link Object}\n */\n public static Meteor build(HttpServletRequest req, List l, Serializer s) {\n return build(req, Broadcaster.SCOPE.APPLICATION, l, s);\n }\n\n /**\n * Create a {@link Meteor} using the {@link HttpServletRequest} and use a list of\n * {@link BroadcastFilter} and {@link Serializer} for writing the result\n * of a broadcast operation the {@link HttpServletResponse}.\n *\n * @param req an {@link HttpServletRequest}\n * @param scope the {@link Broadcaster.SCOPE}}\n * @param l a list of {@link BroadcastFilter}\n * @param s a {@link Serializer} used when writing broadcast events\n * @return a {@link Meteor} than can be used to resume, suspend and broadcast {@link Object}\n */\n public static Meteor build(HttpServletRequest req, Broadcaster.SCOPE scope,\n List l, Serializer s) {\n AtmosphereResource r =\n (AtmosphereResource)\n req.getAttribute(ATMOSPHERE_RESOURCE);\n if (r == null) throw new IllegalStateException(\"MeteorServlet not defined in web.xml\");\n\n Broadcaster b;\n if (scope == Broadcaster.SCOPE.REQUEST) {\n try {\n BroadcasterFactory f = r.getAtmosphereConfig().getBroadcasterFactory();\n b = f.get(DefaultBroadcaster.class, DefaultBroadcaster.class.getSimpleName()\n + r.getAtmosphereConfig().uuidProvider().generateUuid());\n } catch (Throwable t) {\n throw new RuntimeException(t);\n }\n b.setScope(scope);\n r.setBroadcaster(b);\n req.setAttribute(AtmosphereResourceImpl.SKIP_BROADCASTER_CREATION, Boolean.TRUE);\n }\n\n Meteor m = new Meteor(r, l, (s != null ? s : r.getSerializer()));\n req.setAttribute(METEOR, m);\n return m;\n }\n\n /**\n * Suspend the underlying {@link HttpServletResponse}. Passing a value of -1\n * suspends the response forever.\n *\n * @param l the maximum time a response stay suspended\n * @return {@link Meteor}\n */\n public Meteor suspend(long l) {\n if (destroyed()) return null;\n r.suspend(l);\n return this;\n }\n\n /**\n * Resume the Meteor after the first broadcast operation. This is useful when long-polling is used.\n *\n * @param resumeOnBroadcast\n * @return this\n */\n public Meteor resumeOnBroadcast(boolean resumeOnBroadcast) {\n r.resumeOnBroadcast(resumeOnBroadcast);\n return this;\n }\n\n /**\n * Return the current {@link org.atmosphere.cpr.AtmosphereResource.TRANSPORT}. The transport needs to be\n * explicitly set by the client by adding the appropriate {@link HeaderConfig#X_ATMOSPHERE_TRANSPORT} value,\n * which can be long-polling, streaming, websocket or JSONP.\n *\n * @return\n */\n public AtmosphereResource.TRANSPORT transport() {\n return r.transport();\n }\n\n /**\n * Suspend the underlying {@link HttpServletResponse}. Passing a value of -1\n * suspends the response forever.\n *\n * @param timeout the maximum time a response stay suspended\n * @param timeunit The time unit of the timeout value\n * @return {@link Meteor}\n */\n\n public Meteor suspend(long timeout, TimeUnit timeunit) {\n if (destroyed()) return null;\n r.suspend(timeout, timeunit);\n return this;\n }\n\n /**\n * Resume the underlying {@link HttpServletResponse}.\n *\n * @return {@link Meteor}\n */\n public Meteor resume() {\n if (destroyed()) return null;\n r.resume();\n return this;\n }\n\n /**\n * Broadcast an {@link Object} to all suspended responses.\n *\n * @param o an {@link Object}\n * @return {@link Meteor}\n */\n public Meteor broadcast(Object o) {\n if (destroyed()) return null;\n r.getBroadcaster().broadcast(o);\n return this;\n }\n\n /**\n * Schedule a periodic broadcast, in seconds.\n *\n * @param o an {@link Object}\n * @param period period in seconds\n * @return {@link Meteor}\n */\n public Meteor schedule(Object o, long period) {\n if (destroyed()) return null;\n r.getBroadcaster().scheduleFixedBroadcast(o, period, TimeUnit.SECONDS);\n return this;\n }\n\n /**\n * Schedule a delayed broadcast, in seconds.\n *\n * @param o an {@link Object}\n * @param period period in seconds\n * @return {@link Meteor}\n */\n public Meteor delayBroadadcast(Object o, long period) {\n if (destroyed()) return null;\n r.getBroadcaster().delayBroadcast(o, period, TimeUnit.SECONDS);\n return this;\n }\n\n /**\n * Return the underlying {@link Broadcaster}.\n *\n * @return\n */\n public Broadcaster getBroadcaster() {\n if (destroyed()) return null;\n return r.getBroadcaster();\n }\n\n /**\n * Set a {@link Broadcaster} instance.\n *\n * @param b\n */\n public void setBroadcaster(Broadcaster b) {\n if (destroyed()) return;\n r.setBroadcaster(b);\n }\n\n /**\n * Return an {@link Object} with this {@link Meteor}.\n *\n * @return the {@link Object}\n */\n public Object attachement() {\n return o;\n }\n\n /**\n * Attach an {@link Object} with this {@link Meteor}.\n *\n * @return the {@link Object}\n */\n public void attach(Object o) {\n this.o = o;\n }\n\n /**\n * Add a {@link AtmosphereResourceEventListener} which gets invoked when\n * responses are resuming, when the remote client closes the connection or\n * when the a {@link Broadcaster#broadcast} operations occurs.\n *\n * @param e an instance of {@link AtmosphereResourceEventListener}\n */\n public Meteor addListener(AtmosphereResourceEventListener e) {\n if (!destroyed()) {\n r.addEventListener(e);\n }\n return this;\n }\n\n /**\n * Remove a {@link AtmosphereResourceEventListener} which gets invoked when\n * a response is resuming, when the remote client closes the connection or\n * when the a {@link Broadcaster#broadcast} operations occurs.\n *\n * @param e an instance of {@link AtmosphereResourceEventListener}\n */\n public Meteor removeListener(AtmosphereResourceEventListener e) {\n if (!destroyed()) {\n r.removeEventListener(e);\n }\n return this;\n }\n\n /**\n * Mark this instance as destroyed. No more operations will be allowed.\n */\n public void destroy() {\n isDestroyed.set(true);\n }\n\n private boolean destroyed() {\n if (isDestroyed.get()) {\n logger.debug(\"This Meteor is destroyed and cannot be used.\");\n return true;\n }\n return false;\n }\n\n /**\n * Return the underlying {@link AtmosphereResource}.\n *\n * @return the underlying {@link AtmosphereResource}\n */\n public AtmosphereResource getAtmosphereResource() {\n return r;\n }\n\n /**\n * Return the {@link org.atmosphere.cpr.AtmosphereConfig}\n * @return the {@link org.atmosphere.cpr.AtmosphereConfig}\n */\n public AtmosphereConfig getAtmosphereConfig() {\n return r.getAtmosphereConfig();\n }\n}\n", "file_name": "Meteor.java", "human_label": "Return a Meteor object based on the HttpServletRequest r.", "level": "class_runnable", "lineno": "65", "name": "lookup", "oracle_context": "{ \"apis\" : \"[getAttribute, isAssignableFrom, getClass, Meteor]\", \"classes\" : \"[Object]\", \"vars\" : \"[]\" }", "package": "org.atmosphere.cpr", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767691a6d9265ec0181a6", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static String[] split(String toSplit,String delimiter){\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset=toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter=toSplit.substring(0,offset);\n String afterDelimiter=toSplit.substring(offset + delimiter.length());\n return new String[]{beforeDelimiter,afterDelimiter};\n}\n", "docstring": "/** \n * Split a String at the first occurrence of the delimiter. Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, andindex 1 being after the delimiter (neither element includes the delimiter); or null if the delimiter wasn't found in the given input String\n */\n", "end_lineno": "881", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *

          \n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
          \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
          \n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
          \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

          The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

          This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

          The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

          The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

          Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

          Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

          The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

          The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

          A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

          A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Split the given string toSplit at the first occurrence of the given delimiter,and return two substrings that don't include the delimiter.", "level": "class_runnable", "lineno": "861", "name": "split", "oracle_context": "{ \"apis\" : \"[hasLength, indexOf, substring, length]\", \"classes\" : \"[String]\", \"vars\" : \"[]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636767601a6d9265ec0180e2", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.alg.util.*;\\nimport org.jgrapht.generate.*;\\nimport org.jgrapht.graph.*;\\nimport org.jgrapht.util.*;\\nimport java.util.*;\\nint n;\\nint m;\\nGraph graph;\\nMap vertices;\\nList indices;\\nBoolean weaklyChordal;\\nGraphPath certificate;\\nWeakChordalityInspector(Graph graph);\\nisWeaklyChordal();\\ngetCertificate();\\nlazyComputeWeakChordality();\\ncomputeGlobalSeparatorList();\\nreformatSeparatorList(List separators,E edge);\\ngetLabeling(E edge);\\nsortSeparatorsList(List separators);\\nunequalSeparators(List sep1,List sep2);\\ncomputeCoConnectedComponents(Graph graph,List separator);\\nputToNextBucket(Integer vertex,Integer vertexLabel,List bucketsByLabel,List labels);\\nreload(List bucketsByLabel,List labels,int minLabel);\\ncheckLabels(List coConnectedComponents,List separator);\\nfindHole(V sourceInSeparator,V source,V target,V targetInSeparator);\\nfindAntiHole(V source,V targetInSeparator);\\nfindHole(Graph graph,V sourceInSeparator,V source,V target,V targetInSeparator);\\nfindCycle(Set visited,Graph graph,V tarInSep,V tar,V sour,V sourInSep);\\nminimizeCycle(Graph graph,List cycle,V tar,V tarInSep,V sour,V sourInSep);\\nfindSeparators(Graph graph,E edge);\\ngetSeparator(Graph graph,V startVertex,Map dfsMap);\\nneighborhoodSetOf(Graph g,E edge);\\ninitMappings();\\n\", \"repo_level\" : \"\" }", "class_name": "WeakChordalityInspector", "code": "private List>,E>> computeGlobalSeparatorList(){\n List>,E>> globalSeparatorList=new ArrayList<>();\n for ( E edge : graph.edgeSet()) {\n V source=graph.getEdgeSource(edge);\n V target=graph.getEdgeTarget(edge);\n if (source != target) {\n List> edgeSeparators=findSeparators(graph,edge);\n globalSeparatorList.addAll(reformatSeparatorList(edgeSeparators,edge));\n }\n }\n return globalSeparatorList;\n}\n", "docstring": "/** \n * Computes the global separator list of the {@code graph}. More precisely, for every edge $e$ in the $G = (V, E)$ computes list of minimal separators $S_e$ in the neighborhood of $e$ and then concatenates these lists. Note: the result may contain duplicates\n * @return the list of minimal separators of every edge $e$ in the inspected graph\n */\n", "end_lineno": "241", "file_content": "/*\n * (C) Copyright 2018-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.cycle;\n\nimport org.jgrapht.*;\nimport org.jgrapht.alg.util.*;\nimport org.jgrapht.generate.*;\nimport org.jgrapht.graph.*;\nimport org.jgrapht.util.*;\n\nimport java.util.*;\n\n/**\n * Tests whether a graph is weakly\n * chordal. Weakly chordal graphs are also known as weakly triangulated graphs. Triangulated in\n * the context of chordality has a different meaning than triangulated in the context of planarity,\n * where it refers to a maximal planar graph, see:\n * \n * http://mathworld.wolfram.com/TriangulatedGraph.html\n *

          \n * The following definitions of are equivalent:\n *

            \n *
          1. A graph is weakly chordal (weakly triangulated) if neither it nor its complement contains a\n * chordless cycles with five or more\n * vertices.
          2. \n *
          3. A 2-pair in a graph is a pair of non-adjacent vertices $x$, $y$ such that every chordless\n * path has exactly two edges. A graph is weakly chordal if every connected\n * induced subgraph $H$ that is not a\n * complete graph, contains a 2-pair.
          4. \n *
          \n * Chordal and weakly chordal graphs are\n * perfect.
          \n * For more details, refer to: Hayward, R.B. Weakly triangulated graphs, Journal of Combinatorial\n * Theory, Series B, vol 39, Issue 3, pp 200-208, 1985.\n *

          \n * The implementation in this class is based on: Lars Severin Skeide (2002)\n * Recognizing weakly chordal graphs.\n * Candidate Scientist Thesis in Informatics. Department of Informatics, University of Bergen,\n * Norway. The terminology used in this implementation is consistent with the one used in this\n * thesis.\n *

          \n * Both the runtime complexity and space complexity of the algorithm implemented in this class is\n * $\\mathcal{O}(|E|^2)$.
          \n * The inspected {@code graph} is specified at the construction time and cannot be modified. When\n * the graph is modified externally, the behavior of the {@code WeakChordalityInspector} is\n * undefined.\n *

          \n * In the case the inspected graph in not weakly chordal, this inspector provides a certificate in\n * the form of some hole or\n * anti-hole. The running time of\n * finding a hole is $\\mathcal{O}(|V| + |E|)$ and of finding an anti-hole - $\\mathcal{O}(|E|^2)$ in\n * the worst case.\n *\n * @param the graph vertex type\n * @param the graph edge type\n * @author Timofey Chudakov\n */\npublic class WeakChordalityInspector\n{\n /**\n * Vertex number\n */\n private final int n;\n /**\n * Edge number\n */\n private final int m;\n /**\n * The inspected graph\n */\n private Graph graph;\n /**\n * Bijective mapping of vertices onto $\\left[0,n-1\\right]$\n */\n private Map vertices;\n /**\n * Inverse of the bijective mapping of vertices onto $\\left[0,n-1\\right]$\n */\n private List indices;\n /**\n * Contains true if the graph is weakly chordal, otherwise false. Is null before the first call\n * to the {@link WeakChordalityInspector#isWeaklyChordal()}.\n */\n private Boolean weaklyChordal = null;\n /**\n * Contains a hole or an anti-hole of the graph, if it isn't weakly chordal\n */\n private GraphPath certificate;\n\n /**\n * Creates a weak chordality inspector for the {@code graph}\n *\n * @param graph the inspected {@code graph}\n */\n public WeakChordalityInspector(Graph graph)\n {\n this.graph = Objects.requireNonNull(graph);\n if (graph.getType().isDirected()) {\n this.graph = new AsUndirectedGraph<>(graph);\n }\n n = graph.vertexSet().size();\n m = graph.edgeSet().size();\n initMappings();\n }\n\n /**\n * Initializes the mappings of the vertices\n */\n private void initMappings()\n {\n VertexToIntegerMapping mapping = new VertexToIntegerMapping<>(graph.vertexSet());\n vertices = mapping.getVertexMap();\n indices = mapping.getIndexList();\n }\n\n /**\n * Check whether the inspected {@code graph} is weakly chordal. Note: this value is computed\n * lazily.\n *\n * @return true, if the inspected {@code graph} is weakly chordal, otherwise false.\n */\n public boolean isWeaklyChordal()\n {\n return lazyComputeWeakChordality();\n }\n\n /**\n * Computes and returns the certificate in the form of a hole or anti-hole in the inspected\n * {@code graph}. Returns null if the inspected graph is weakly chordal. Note: certificate is\n * computed lazily.\n *\n * @return a hole or\n * anti-hole in the\n * inspected {@code graph}, null if the {@code graph} is weakly chordal\n */\n public GraphPath getCertificate()\n {\n lazyComputeWeakChordality();\n return certificate;\n }\n\n /**\n * Lazily tests the weak chordality of the {@code graph} and returns the computed value.\n *\n * @return true, if the inspected {@code graph} is weakly chordal, otherwise false.\n */\n private boolean lazyComputeWeakChordality()\n {\n if (weaklyChordal == null) {\n List>, E>> globalSeparatorList =\n computeGlobalSeparatorList();\n\n if (globalSeparatorList.size() > 0) {\n Pair pair;\n sortSeparatorsList(globalSeparatorList);\n\n // Iterating over separators. Computing coconnected components only for distinct\n // separators\n int separatorsNum = 1;\n List> original = globalSeparatorList.get(0).getFirst();\n List> coConnectedComponents =\n computeCoConnectedComponents(graph, original);\n\n for (Pair>, E> separator : globalSeparatorList) {\n if (unequalSeparators(original, separator.getFirst())) {\n original = separator.getFirst();\n ++separatorsNum;\n if (n + m < separatorsNum) {\n return weaklyChordal = false;\n } else {\n coConnectedComponents = computeCoConnectedComponents(graph, original);\n }\n }\n if ((pair = checkLabels(coConnectedComponents, separator.getFirst())) != null) {\n // Found a pair of vertices which has labels 1 and 2. This means the graph\n // isn't weakly chordal. Start detecting a hole\n E holeFormer = separator.getSecond();\n V source = graph.getEdgeSource(holeFormer);\n V target = graph.getEdgeTarget(holeFormer);\n\n V sourceInSeparator = indices.get(pair.getFirst());\n V targetInSeparator = indices.get(pair.getSecond());\n\n if (!graph.containsEdge(source, sourceInSeparator)) {\n V t = sourceInSeparator;\n sourceInSeparator = targetInSeparator;\n targetInSeparator = t;\n }\n if (graph.containsEdge(sourceInSeparator, targetInSeparator)) {\n findAntiHole(source, targetInSeparator);\n } else {\n findHole(sourceInSeparator, source, target, targetInSeparator);\n }\n return weaklyChordal = false;\n }\n }\n\n return weaklyChordal = true;\n } else {\n\n return weaklyChordal = true;\n }\n }\n return weaklyChordal;\n }\n\n /**\n * Computes the global separator list of the {@code graph}. More precisely, for every edge $e$\n * in the $G = (V, E)$ computes list of minimal separators $S_e$ in the neighborhood of $e$ and\n * then concatenates these lists. Note: the result may contain duplicates\n *\n * @return the list of minimal separators of every edge $e$ in the inspected graph\n */\n private List>, E>> computeGlobalSeparatorList()\n {\n List>, E>> globalSeparatorList = new ArrayList<>();\n for (E edge : graph.edgeSet()) {\n V source = graph.getEdgeSource(edge);\n V target = graph.getEdgeTarget(edge);\n if (source != target) {\n List> edgeSeparators = findSeparators(graph, edge);\n globalSeparatorList.addAll(reformatSeparatorList(edgeSeparators, edge));\n }\n }\n return globalSeparatorList;\n }\n\n /**\n * Reformats the list o {@code separators} so that is can be conveniently used by this\n * inspector. More precisely, in every separator from the list of minimal separators in the\n * neighborhood of the {@code edge} substitutes all vertices for their indices in the numeration\n * defined by {@code vertices}. Pairs every separator with the {@code edge}.\n *\n * @param separators the list of minimal separators in the neighborhood of the {@code edge}\n * @param edge the edge, which neighborhood contains minimal separators from {@code separators}\n * @return the reformatted list of minimal separators\n */\n private List>, E>> reformatSeparatorList(\n List> separators, E edge)\n {\n List labeling = getLabeling(edge);\n List>, E>> reformattedSeparators = new ArrayList<>();\n List>>> vInSeparator = new ArrayList<>(n);\n for (int i = 0; i < n; i++) {\n vInSeparator.add(new ArrayList<>());\n }\n\n for (Set computedSeparator : separators) {\n List> reformattedSeparator =\n new ArrayList<>(computedSeparator.size());\n reformattedSeparators.add(new Pair<>(reformattedSeparator, edge));\n for (V vertex : computedSeparator) {\n int vertexIndex = vertices.get(vertex);\n vInSeparator.get(vertexIndex).add(reformattedSeparator);\n }\n }\n\n for (int vertex = 0; vertex < n; vertex++) {\n List>> listOfSeparators = vInSeparator.get(vertex);\n for (List> separator : listOfSeparators) {\n separator.add(new Pair<>(vertex, labeling.get(vertex)));\n }\n }\n\n return reformattedSeparators;\n\n }\n\n /**\n * Computes the labeling of the neighborhood of {@code edge} on the vertices {@code source} and\n * {@code target}. Vertex from the neighborhood is labeled with \"1\" if it sees only\n * {@code source}, \"2\" is it sees only {@code target}, and \"3\" if it sees both vertices.\n *\n * @param edge the edge, whose neighborhood is to be labeled\n * @return the computed labeling with the respect to the rule described above\n */\n private List getLabeling(E edge)\n {\n V source = graph.getEdgeSource(edge);\n V target = graph.getEdgeTarget(edge);\n List labeling = new ArrayList<>(Collections.nCopies(n, null));\n for (E sourceEdge : graph.edgesOf(source)) {\n labeling.set(vertices.get(Graphs.getOppositeVertex(graph, sourceEdge, source)), 1);\n }\n for (E targetEdge : graph.edgesOf(target)) {\n Integer oppositeIndex =\n vertices.get(Graphs.getOppositeVertex(graph, targetEdge, target));\n if (labeling.get(oppositeIndex) != null) {\n labeling.set(oppositeIndex, 3);\n } else {\n labeling.set(oppositeIndex, 2);\n }\n }\n return labeling;\n }\n\n /**\n * Sorts the {@code separators} using bucket sort\n *\n * @param separators the list of separators to be sorted\n */\n private void sortSeparatorsList(List>, E>> separators)\n {\n Queue>, E>> mainQueue = new ArrayDeque<>();\n int maxSeparatorLength = 0;\n for (Pair>, E> separator : separators) {\n if (separator.getFirst().size() > maxSeparatorLength) {\n maxSeparatorLength = separator.getFirst().size();\n }\n mainQueue.add(separator);\n }\n separators.clear();\n List>, E>>> queues = new ArrayList<>(n);\n for (int i = 0; i < n; i++) {\n queues.add(new LinkedList<>());\n }\n for (int i = 0; i < maxSeparatorLength; i++) {\n while (!mainQueue.isEmpty()) {\n Pair>, E> separator = mainQueue.remove();\n if (i >= separator.getFirst().size()) {\n separators.add(separator);\n } else {\n queues\n .get(\n separator\n .getFirst().get(separator.getFirst().size() - i - 1).getFirst())\n .add(separator);\n }\n }\n for (Queue>, E>> queue : queues) {\n mainQueue.addAll(queue);\n queue.clear();\n }\n }\n separators.addAll(mainQueue);\n }\n\n /**\n * Compares two separators for inequality. Labeling of the vertices in the separators isn't\n * considered\n *\n * @param sep1 first separator\n * @param sep2 second separator\n * @return true, if the separators are unequal, false otherwise\n */\n private boolean unequalSeparators(\n List> sep1, List> sep2)\n {\n if (sep1.size() == sep2.size()) {\n for (int i = 0; i < sep1.size(); i++) {\n if (!sep2.get(i).getFirst().equals(sep1.get(i).getFirst())) {\n return true;\n }\n }\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Computes the connected components of the complement of the graph induces by the vertices of\n * the {@code separator}. They are also called \"coconnected components\". The running time is\n * $\\mathcal{O}(|V| + |E|)$.\n *\n * @param separator the separators, whose coconnected components are computed\n * @return the coconected of the {@code separator}\n */\n private List> computeCoConnectedComponents(\n Graph graph, List> separator)\n {\n List> coConnectedComponents = new ArrayList<>();\n\n // Initializing buckets, labels and set of unvisited vertices. Every vertex in separator is\n // put\n // to bucket with label 0\n List> bucketsByLabel = new ArrayList<>(separator.size());\n for (int i = 0; i < separator.size(); i++) {\n bucketsByLabel.add(new HashSet<>());\n }\n List labels = new ArrayList<>(Collections.nCopies(n, -1));\n Set unvisited = CollectionUtil.newHashSetWithExpectedSize(separator.size());\n separator.forEach(pair -> {\n unvisited.add(pair.getFirst());\n labels.set(pair.getFirst(), 0);\n });\n bucketsByLabel.set(0, unvisited);\n int minLabel = 0;\n\n while (unvisited.size() > 0) {\n List coConnectedComponent = new ArrayList<>();\n do {\n // When minLabel = coConnectedComponent.size(), we've visited all vertices in some\n // coconnected component in the separator. If there exist unvisited vertices, we\n // start again\n while (!bucketsByLabel.get(minLabel).isEmpty()) {\n Integer vertex = bucketsByLabel.get(minLabel).iterator().next();\n bucketsByLabel.get(minLabel).remove(vertex);\n coConnectedComponent.add(vertex);\n labels.set(vertex, -1);\n\n for (E edge : graph.edgesOf(indices.get(vertex))) {\n Integer opposite = vertices\n .get(Graphs.getOppositeVertex(graph, edge, indices.get(vertex)));\n Integer oppositeLabel = labels.get(opposite);\n if (oppositeLabel != -1) {\n putToNextBucket(opposite, oppositeLabel, bucketsByLabel, labels);\n }\n }\n }\n ++minLabel;\n } while (minLabel != coConnectedComponent.size());\n reload(bucketsByLabel, labels, minLabel);\n\n coConnectedComponents.add(coConnectedComponent);\n minLabel = 0;\n }\n return coConnectedComponents;\n }\n\n /**\n * Moves the {@code vertex} to the next bucket.\n *\n * @param vertex the vertex to be moved\n * @param vertexLabel the label of the {@code vertex}\n * @param bucketsByLabel the buckets, in which vertices are stored\n * @param labels the labels of the vertices\n */\n private void putToNextBucket(\n Integer vertex, Integer vertexLabel, List> bucketsByLabel,\n List labels)\n {\n bucketsByLabel.get(vertexLabel).remove(vertex);\n bucketsByLabel.get(vertexLabel + 1).add(vertex);\n labels.set(vertex, vertexLabel + 1);\n }\n\n /**\n * Moves all vertices from the bucket with label {@code minLabel} to the bucket with label 0.\n * Clears the bucket with label {@code minLabel}. Updates the labeling accordingly.\n *\n * @param bucketsByLabel the buckets vertices are stored in\n * @param labels the labels of the vertices\n * @param minLabel the minimum value of the non-empty bucket\n */\n private void reload(List> bucketsByLabel, List labels, int minLabel)\n {\n if (minLabel != 0 && minLabel < bucketsByLabel.size()) {\n Set bucket = bucketsByLabel.get(minLabel);\n for (Integer vertex : bucket) {\n labels.set(vertex, 0);\n bucketsByLabel.get(0).add(vertex);\n }\n bucket.clear();\n }\n }\n\n /**\n * For a given coconnected component of the {@code separator} checks whether every vertex in it\n * is seen by al least one vertex of the edge that is separated by the {@code separator}\n *\n * @param coConnectedComponents the set of the coconected components of the {@code separator}\n * @param separator minimal separator of some edge in the {@code graph}\n * @return true if the condition described above holds, false otherwise\n */\n private Pair checkLabels(\n List> coConnectedComponents, List> separator)\n {\n List vertexLabels = new ArrayList<>(Collections.nCopies(n, null));\n for (Pair vertexAndLabel : separator) {\n vertexLabels.set(vertexAndLabel.getFirst(), vertexAndLabel.getSecond());\n }\n for (List coConnectedComponent : coConnectedComponents) {\n int label = 0;\n Integer labelVertex = null;\n for (Integer vertex : coConnectedComponent) {\n if (vertexLabels.get(vertex) != 3) {\n if (label != 0) {\n if (label != vertexLabels.get(vertex)) {\n return new Pair<>(labelVertex, vertex);\n }\n } else {\n label = vertexLabels.get(vertex);\n labelVertex = vertex;\n }\n }\n }\n }\n return null;\n }\n\n /**\n * Finds a hole in the inspected {@code graph}. Vertices {@code sourceInSeparator},\n * {@code source}, {@code target} and {@code targetInSeparator} belong to the computes hole.\n * They are used to correctly find a hole in the inspected graph.\n *\n * @param sourceInSeparator vertex on the hole\n * @param source vertex on the hole\n * @param target vertex on the hole\n * @param targetInSeparator vertex on the hole\n */\n private void findHole(V sourceInSeparator, V source, V target, V targetInSeparator)\n {\n this.certificate = findHole(graph, sourceInSeparator, source, target, targetInSeparator);\n }\n\n /**\n * Finds an anti-hole in the inspected {@code graph}. Vertices {@code source} and\n * {@code targetInSeparator} specify an edge, which belongs to the anti-hole in the complement\n * of the {@code graph}. Then the hole in the complement of the graph is computed in the graph's\n * complement in the same way a hole is computed in the {@code graph}.\n *\n * @param source endpoint of the edge that belongs to the anti-hole\n * @param targetInSeparator endpoint of the edge that belongs to the anti-hole\n */\n private void findAntiHole(V source, V targetInSeparator)\n {\n // Generating the complement of the inspected graph\n ComplementGraphGenerator generator = new ComplementGraphGenerator<>(graph, false);\n Graph complement = Pseudograph. createBuilder(graph.getEdgeSupplier()).build();\n generator.generateGraph(complement);\n\n E cycleFormer = complement.getEdge(source, targetInSeparator);\n V cycleSource = graph.getEdgeSource(cycleFormer);\n V cycleTarget = graph.getEdgeTarget(cycleFormer);\n\n // For edge cycleFormer we need to find the separator, which contains vertices with labels 1\n // and 2\n // After that the procedure of detecting a hole in the complement of the graph is identical\n // to finding a hole in the graph itself\n List> separators = findSeparators(complement, cycleFormer);\n List>, E>> reformatted =\n reformatSeparatorList(separators, cycleFormer);\n\n sortSeparatorsList(reformatted);\n\n List> original = reformatted.get(0).getFirst();\n List> coConnectedComponents =\n computeCoConnectedComponents(complement, original);\n\n Pair pair;\n for (Pair>, E> separator : reformatted) {\n if (unequalSeparators(separator.getFirst(), original)) {\n original = separator.getFirst();\n coConnectedComponents =\n computeCoConnectedComponents(complement, separator.getFirst());\n }\n if ((pair = checkLabels(coConnectedComponents, separator.getFirst())) != null) {\n // Found a pair of vertices with labels 1 and 2\n V cycleSourceInSeparator = indices.get(pair.getFirst());\n V cycleTargetInSeparator = indices.get(pair.getSecond());\n if (!complement.containsEdge(cycleSourceInSeparator, cycleSource)) {\n V t = cycleSourceInSeparator;\n cycleSourceInSeparator = cycleTargetInSeparator;\n cycleTargetInSeparator = t;\n }\n this.certificate = findHole(\n complement, cycleSourceInSeparator, cycleSource, cycleTarget,\n cycleTargetInSeparator);\n return;\n }\n }\n }\n\n /**\n * Finds a hole in the specified {@code graph}. Vertices {@code sourceInSeparator},\n * {@code source}, {@code target} and {@code targetInSeparator} belong to the computes hole.\n * They are used to correctly find a hole in the specified {@code graph}.\n *\n * @param sourceInSeparator vertex on the hole\n * @param source vertex on the hole\n * @param target vertex on the hole\n * @param targetInSeparator vertex on the hole\n * @return the computed hole on the {@code graph}\n */\n private GraphPath findHole(\n Graph graph, V sourceInSeparator, V source, V target, V targetInSeparator)\n {\n Set visited = CollectionUtil.newHashSetWithExpectedSize(graph.vertexSet().size());\n visited.add(target);\n visited.add(source);\n\n // Obtaining some cycle, which can be minimized to a hole\n List cycle =\n findCycle(visited, graph, targetInSeparator, target, source, sourceInSeparator);\n cycle = minimizeCycle(graph, cycle, target, targetInSeparator, source, sourceInSeparator);\n\n return new GraphWalk<>(graph, cycle, 0);\n }\n\n /**\n * Starts the iterative depth-first traversal from {@code sourInSep} vertex. Tries to build a\n * cycle with the vertices, which aren't adjacent to the {@code tar} and {@code sour}. This\n * condition is used in order to ensure that the cycle contains a hole, to which it is later\n * minimized.\n *\n * @param visited defines which vertices have been visited already\n * @param graph the graph the search is performed on\n * @param tarInSep the end point of the cycle\n * @param tar the vertex, which can't be adjacent to the vertices in the cycle\n * @param sour the vertex, which can't be adjacent to the vertices in the cycle\n * @param sourInSep the vertex the search is started from\n * @return the computed cycle, which contains a hole\n */\n private List findCycle(\n Set visited, Graph graph, V tarInSep, V tar, V sour, V sourInSep)\n {\n List cycle = new ArrayList<>(Arrays.asList(tarInSep, tar, sour));\n Deque stack = new ArrayDeque<>();\n stack.add(sourInSep);\n\n while (!stack.isEmpty()) {\n V currentVertex = stack.removeLast();\n if (visited.add(currentVertex)) {\n\n // trying to advance cycle from current vertex\n // removing all vertices from the head of the cycle, which aren't adjacent to the\n // current vertex\n while (!graph.containsEdge(cycle.get(cycle.size() - 1), currentVertex)) {\n cycle.remove(cycle.size() - 1);\n }\n cycle.add(currentVertex);\n if (tarInSep.equals(currentVertex)) {\n // the cycle is complete\n break;\n } else {\n for (V neighbor : Graphs.neighborListOf(graph, currentVertex)) {\n // add a vertex to the stack if it hasn't been visited yet and it isn't\n // adjacent to the\n // source vertex and (it isn't adjacent to the target vertex or it is\n // targetInSeparator (the end of the cycle))\n if (!visited.contains(neighbor) && !graph.containsEdge(sour, neighbor)\n && (!graph.containsEdge(tar, neighbor) || neighbor.equals(tarInSep)))\n {\n stack.add(neighbor);\n }\n }\n }\n }\n }\n return cycle;\n }\n\n /**\n * Minimizes the {@code cycle} so that it contains a hole in the {@code graph}. Vertices\n * {@code tar}, {@code tarInSep}, {@code sour} and {@code sourInSep} belong to the final result.\n *\n * @param graph the graph, which contains vertices from {@code cycle}\n * @param cycle the cycle to minimize\n * @param tar vertex, which should belong to the final result\n * @param tarInSep vertex, which should belong to the final result\n * @param sour vertex, which should belong to the final result\n * @param sourInSep vertex, which should belong to the final result\n * @return a list of vertices, which defines a hole in the {@code graph}\n */\n private List minimizeCycle(\n Graph graph, List cycle, V tar, V tarInSep, V sour, V sourInSep)\n {\n List minimizedCycle = new ArrayList<>(Arrays.asList(tarInSep, tar, sour));\n Set forwardVertices = new HashSet<>(cycle);\n forwardVertices.remove(tar);\n forwardVertices.remove(sour);\n forwardVertices.remove(sourInSep);\n\n for (int i = 3; i < cycle.size() - 1;) {\n V current = cycle.get(i);\n minimizedCycle.add(current);\n forwardVertices.remove(current);\n\n // Computing a set of vertices, which are adjacent to current and have greater index\n // in the cycle than current\n Set currentForward = new HashSet<>();\n for (V neighbor : Graphs.neighborListOf(graph, current)) {\n if (forwardVertices.contains(neighbor)) {\n currentForward.add(neighbor);\n }\n }\n\n // Jump to the forward vertex with the greatest index. Therefore we ensure, that\n // the resulting cycle doesn't contain chords\n for (V forwardVertex : currentForward) {\n if (forwardVertices.contains(forwardVertex)) {\n do {\n forwardVertices.remove(cycle.get(i));\n i++;\n } while (i < cycle.size() && !cycle.get(i).equals(forwardVertex));\n }\n }\n }\n minimizedCycle.add(tarInSep);\n return minimizedCycle;\n }\n\n /**\n * Computes and returns all minimal separators in the neighborhood of the {@code edge} in the\n * {@code graph}. The result may contain duplicate separators.\n *\n * @param graph the graph to search minimal separators in\n * @param edge the edge, whose neighborhood is being explored\n * @return the list of all minimal separators in the neighborhood of the {@code edge}. The\n * resulted list may contain duplicates.\n */\n private List> findSeparators(Graph graph, E edge)\n {\n List> separators = new ArrayList<>();\n V source = graph.getEdgeSource(edge);\n V target = graph.getEdgeTarget(edge);\n Set neighborhood = neighborhoodSetOf(graph, edge);\n Map dfsMap = CollectionUtil.newHashMapWithExpectedSize(graph.vertexSet().size());\n\n // 0 - unvisited (white), 1 - neighbor of the edge (red), 2 - visited (black)\n for (V vertex : graph.vertexSet()) {\n if (neighborhood.contains(vertex)) {\n dfsMap.put(vertex, (byte) 1);\n } else {\n dfsMap.put(vertex, (byte) 0);\n }\n }\n dfsMap.put(source, (byte) 2);\n dfsMap.put(target, (byte) 2);\n\n for (V vertex : graph.vertexSet()) {\n if (dfsMap.get(vertex) == 0) {\n // possible to find one more separator\n Set separator = getSeparator(graph, vertex, dfsMap);\n if (!separator.isEmpty()) {\n separators.add(separator);\n }\n }\n }\n\n return separators;\n }\n\n /**\n * Performs iterative depth-first search starting from the {@code startVertex} in the\n * {@code graph}. Adds every encountered red vertex to the resulting separator. Doesn't process\n * red vertices. Marks all white vertices with black color.\n *\n * @param graph the graph dfs is performed on\n * @param startVertex the vertex to start depth-first traversal from\n * @param dfsMap the depth-first vertex labeling\n * @return the computed separator, which consists of all encountered red vertices\n */\n private Set getSeparator(Graph graph, V startVertex, Map dfsMap)\n {\n Deque stack = new ArrayDeque<>();\n Set separator = new HashSet<>();\n stack.add(startVertex);\n\n while (!stack.isEmpty()) {\n V currentVertex = stack.removeLast();\n if (dfsMap.get(currentVertex) == 0) {\n dfsMap.put(currentVertex, (byte) 2);\n for (E edge : graph.edgesOf(currentVertex)) {\n V opposite = Graphs.getOppositeVertex(graph, edge, currentVertex);\n if (dfsMap.get(opposite) == 0) {\n stack.add(opposite);\n } else if (dfsMap.get(opposite) == 1) {\n separator.add(opposite); // found red vertex, which belongs to the separator\n }\n }\n }\n }\n\n return separator;\n }\n\n /**\n * Returns a set of vertices that are neighbors of the source of the specified edge or of the\n * target of specified edge. The endpoints of the specified edge aren't included in the result.\n *\n * @param g the graph to look for neighbors in\n * @param edge the edge to get the neighbors of\n * @return a set of vertices that are neighbors of at least one endpoint of the specified edge.\n * The endpoints of the specified edge aren't included in the result\n */\n private Set neighborhoodSetOf(Graph g, E edge)\n {\n Set neighborhood = new HashSet<>();\n\n V source = g.getEdgeSource(edge);\n V target = g.getEdgeTarget(edge);\n\n for (E e : g.edgesOf(source)) {\n neighborhood.add(Graphs.getOppositeVertex(g, e, source));\n }\n for (E e : g.edgesOf(target)) {\n neighborhood.add(Graphs.getOppositeVertex(g, e, target));\n }\n neighborhood.remove(source);\n neighborhood.remove(target);\n\n return neighborhood;\n }\n}\n", "file_name": "WeakChordalityInspector.java", "human_label": "Select an edge which isn't a circle in the graph,compute the list of the minimal separators in the neighborhood of the edge and put the pair of list and edge into the return list.Repeat for each edge in the graph and then return the final list.", "level": "class_runnable", "lineno": "222", "name": "computeGlobalSeparatorList", "oracle_context": "{ \"apis\" : \"[edgeSet, getEdgeSource, getEdgeTarget, findSeparators, addAll, reformatSeparatorList]\", \"classes\" : \"[List>,E>>, V, List>]\", \"vars\" : \"[graph]\" }", "package": "org.jgrapht.alg.cycle", "project": "jgrapht-master" }, { "_id": "636766f31a6d9265ec01768f", "all_context": "{ \"class_level\" : \"import java.lang.reflect.Array;\\nimport java.util.ArrayList;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.Map.Entry;\\nObject[] EMPTY_OBJECT_ARRAY;\\nClass[] EMPTY_CLASS_ARRAY;\\nString[] EMPTY_STRING_ARRAY;\\nlong[] EMPTY_LONG_ARRAY;\\nLong[] EMPTY_LONG_OBJECT_ARRAY;\\nint[] EMPTY_INT_ARRAY;\\nInteger[] EMPTY_INTEGER_OBJECT_ARRAY;\\nshort[] EMPTY_SHORT_ARRAY;\\nShort[] EMPTY_SHORT_OBJECT_ARRAY;\\nbyte[] EMPTY_BYTE_ARRAY;\\nByte[] EMPTY_BYTE_OBJECT_ARRAY;\\ndouble[] EMPTY_DOUBLE_ARRAY;\\nDouble[] EMPTY_DOUBLE_OBJECT_ARRAY;\\nfloat[] EMPTY_FLOAT_ARRAY;\\nFloat[] EMPTY_FLOAT_OBJECT_ARRAY;\\nboolean[] EMPTY_BOOLEAN_ARRAY;\\nBoolean[] EMPTY_BOOLEAN_OBJECT_ARRAY;\\nchar[] EMPTY_CHAR_ARRAY;\\nCharacter[] EMPTY_CHARACTER_OBJECT_ARRAY;\\nint INDEX_NOT_FOUND;\\nArrayUtils();\\nclone(Object[] array);\\nclone(long[] array);\\nclone(int[] array);\\nclone(short[] array);\\nclone(char[] array);\\nclone(byte[] array);\\nclone(double[] array);\\nclone(float[] array);\\nclone(boolean[] array);\\nclone(String[] array);\\nnullToEmpty(Object[] array);\\nnullToEmpty(String[] array);\\nnullToEmpty(long[] array);\\nnullToEmpty(int[] array);\\nnullToEmpty(short[] array);\\nnullToEmpty(char[] array);\\nnullToEmpty(byte[] array);\\nnullToEmpty(double[] array);\\nnullToEmpty(float[] array);\\nnullToEmpty(boolean[] array);\\nnullToEmpty(Long[] array);\\nnullToEmpty(Integer[] array);\\nnullToEmpty(Short[] array);\\nnullToEmpty(Character[] array);\\nnullToEmpty(Byte[] array);\\nnullToEmpty(Double[] array);\\nnullToEmpty(Float[] array);\\nnullToEmpty(Boolean[] array);\\nsubarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nsubarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nisSameLength(Object[] array1,Object[] array2);\\nisSameLength(long[] array1,long[] array2);\\nisSameLength(int[] array1,int[] array2);\\nisSameLength(short[] array1,short[] array2);\\nisSameLength(char[] array1,char[] array2);\\nisSameLength(byte[] array1,byte[] array2);\\nisSameLength(double[] array1,double[] array2);\\nisSameLength(float[] array1,float[] array2);\\nisSameLength(boolean[] array1,boolean[] array2);\\ngetLength(Object array);\\nisSameType(Object array1,Object array2);\\nreverse(Object[] array);\\nreverse(long[] array);\\nreverse(int[] array);\\nreverse(short[] array);\\nreverse(char[] array);\\nreverse(byte[] array);\\nreverse(double[] array);\\nreverse(float[] array);\\nreverse(boolean[] array);\\nindexOf(Object[] array,Object objectToFind);\\nindexOf(Object[] array,Object objectToFind,int startIndex);\\nlastIndexOf(Object[] array,Object objectToFind);\\nlastIndexOf(Object[] array,Object objectToFind,int startIndex);\\ncontains(Object[] array,Object objectToFind);\\nindexOf(long[] array,long valueToFind);\\nindexOf(long[] array,long valueToFind,int startIndex);\\nlastIndexOf(long[] array,long valueToFind);\\nlastIndexOf(long[] array,long valueToFind,int startIndex);\\ncontains(long[] array,long valueToFind);\\nindexOf(int[] array,int valueToFind);\\nindexOf(int[] array,int valueToFind,int startIndex);\\nlastIndexOf(int[] array,int valueToFind);\\nlastIndexOf(int[] array,int valueToFind,int startIndex);\\ncontains(int[] array,int valueToFind);\\nindexOf(short[] array,short valueToFind);\\nindexOf(short[] array,short valueToFind,int startIndex);\\nlastIndexOf(short[] array,short valueToFind);\\nlastIndexOf(short[] array,short valueToFind,int startIndex);\\ncontains(short[] array,short valueToFind);\\nindexOf(char[] array,char valueToFind);\\nindexOf(char[] array,char valueToFind,int startIndex);\\nlastIndexOf(char[] array,char valueToFind);\\nlastIndexOf(char[] array,char valueToFind,int startIndex);\\ncontains(char[] array,char valueToFind);\\nindexOf(byte[] array,byte valueToFind);\\nindexOf(byte[] array,byte valueToFind,int startIndex);\\nlastIndexOf(byte[] array,byte valueToFind);\\nlastIndexOf(byte[] array,byte valueToFind,int startIndex);\\ncontains(byte[] array,byte valueToFind);\\nindexOf(double[] array,double valueToFind);\\nindexOf(double[] array,double valueToFind,double tolerance);\\nindexOf(double[] array,double valueToFind,int startIndex);\\nindexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nlastIndexOf(double[] array,double valueToFind);\\nlastIndexOf(double[] array,double valueToFind,double tolerance);\\nlastIndexOf(double[] array,double valueToFind,int startIndex);\\nlastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\ncontains(double[] array,double valueToFind);\\ncontains(double[] array,double valueToFind,double tolerance);\\nindexOf(float[] array,float valueToFind);\\nindexOf(float[] array,float valueToFind,int startIndex);\\nlastIndexOf(float[] array,float valueToFind);\\nlastIndexOf(float[] array,float valueToFind,int startIndex);\\ncontains(float[] array,float valueToFind);\\nindexOf(boolean[] array,boolean valueToFind);\\nindexOf(boolean[] array,boolean valueToFind,int startIndex);\\nlastIndexOf(boolean[] array,boolean valueToFind);\\nlastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\ncontains(boolean[] array,boolean valueToFind);\\ntoPrimitive(Character[] array);\\ntoPrimitive(Character[] array,char valueForNull);\\ntoObject(char[] array);\\ntoPrimitive(Long[] array);\\ntoPrimitive(Long[] array,long valueForNull);\\ntoObject(long[] array);\\ntoPrimitive(Integer[] array);\\ntoPrimitive(Integer[] array,int valueForNull);\\ntoObject(int[] array);\\ntoPrimitive(Short[] array);\\ntoPrimitive(Short[] array,short valueForNull);\\ntoObject(short[] array);\\ntoPrimitive(Byte[] array);\\ntoPrimitive(Byte[] array,byte valueForNull);\\ntoObject(byte[] array);\\ntoPrimitive(Double[] array);\\ntoPrimitive(Double[] array,double valueForNull);\\ntoObject(double[] array);\\ntoPrimitive(Float[] array);\\ntoPrimitive(Float[] array,float valueForNull);\\ntoObject(float[] array);\\ntoPrimitive(Boolean[] array);\\ntoPrimitive(Boolean[] array,boolean valueForNull);\\ntoObject(boolean[] array);\\nisEmpty(Object[] array);\\nisEmpty(long[] array);\\nisEmpty(int[] array);\\nisEmpty(short[] array);\\nisEmpty(char[] array);\\nisEmpty(byte[] array);\\nisEmpty(double[] array);\\nisEmpty(float[] array);\\nisEmpty(boolean[] array);\\nisNotEmpty(Object[] array);\\nisNotEmpty(long[] array);\\nisNotEmpty(int[] array);\\nisNotEmpty(short[] array);\\nisNotEmpty(char[] array);\\nisNotEmpty(byte[] array);\\nisNotEmpty(double[] array);\\nisNotEmpty(float[] array);\\nisNotEmpty(boolean[] array);\\naddAll(Object[] array1,Object[] array2);\\naddAll(boolean[] array1,boolean[] array2);\\naddAll(char[] array1,char[] array2);\\naddAll(byte[] array1,byte[] array2);\\naddAll(short[] array1,short[] array2);\\naddAll(int[] array1,int[] array2);\\naddAll(long[] array1,long[] array2);\\naddAll(float[] array1,float[] array2);\\naddAll(double[] array1,double[] array2);\\naddAll(String[] array1,String[] array2);\\nadd(T[] array,T element);\\nadd(boolean[] array,boolean element);\\nadd(byte[] array,byte element);\\nadd(char[] array,char element);\\nadd(double[] array,double element);\\nadd(float[] array,float element);\\nadd(int[] array,int element);\\nadd(long[] array,long element);\\nadd(short[] array,short element);\\ncopyArrayGrow1(Object array,Class newArrayComponentType);\\nadd(Object[] array,int index,Object element);\\nadd(boolean[] array,int index,boolean element);\\nadd(char[] array,int index,char element);\\nadd(byte[] array,int index,byte element);\\nadd(short[] array,int index,short element);\\nadd(int[] array,int index,int element);\\nadd(long[] array,int index,long element);\\nadd(float[] array,int index,float element);\\nadd(double[] array,int index,double element);\\nadd(Object array,int index,Object element,Class clss);\\nremove(Object[] array,int index);\\nremoveElement(Object[] array,Object element);\\nremove(boolean[] array,int index);\\nremoveElement(boolean[] array,boolean element);\\nremove(byte[] array,int index);\\nremoveElement(byte[] array,byte element);\\nremove(char[] array,int index);\\nremoveElement(char[] array,char element);\\nremove(double[] array,int index);\\nremoveElement(double[] array,double element);\\nremove(float[] array,int index);\\nremoveElement(float[] array,float element);\\nremove(int[] array,int index);\\nremoveElement(int[] array,int element);\\nremove(long[] array,int index);\\nremoveElement(long[] array,long element);\\nremove(short[] array,int index);\\nremoveElement(short[] array,short element);\\nremove(Object array,int index);\\nclearNull(Object[] arr);\\ntoMap(Object[] array);\\n\", \"repo_level\" : \"\" }", "class_name": "ArrayUtils", "code": "public static char[] clone(final char[] array){\n if (array == null) {\n return null;\n }\n return array.clone();\n}\n", "docstring": "/** \n *

          Clones an array returning a typecast result and handling null.

          This method returns null for a null input array.

          \n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n", "end_lineno": "236", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\nimport java.lang.reflect.Array;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n *

          Operations on arrays, primitive arrays (like int[]) and\n * primitive wrapper arrays (like Integer[]).

          \n *\n *

          This class tries to handle null input gracefully.\n * An exception will not be thrown for a null\n * array input. However, an Object array that contains a null\n * element may throw an exception. Each method documents its behaviour.

          \n *\n *

          #ThreadSafe#

          \n * @author Apache Software Foundation\n * @author Moritz Petersen\n * @author Fredrik Westermarck\n * @author Nikolay Metchev\n * @author Matthew Hawthorne\n * @author Tim O'Brien\n * @author Pete Gieser\n * @author Gary Gregory\n * @author Ashwin S\n * @author Maarten Coene\n * @since 2.0\n * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class ArrayUtils {\n /** An empty immutable Object array. */\n public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];\n /** An empty immutable Class array. */\n public static final Class[] EMPTY_CLASS_ARRAY = new Class[0];\n /** An empty immutable String array. */\n public static final String[] EMPTY_STRING_ARRAY = new String[0];\n /** An empty immutable long array. */\n public static final long[] EMPTY_LONG_ARRAY = new long[0];\n /** An empty immutable Long array. */\n public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];\n /** An empty immutable int array. */\n public static final int[] EMPTY_INT_ARRAY = new int[0];\n /** An empty immutable Integer array. */\n public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];\n /** An empty immutable short array. */\n public static final short[] EMPTY_SHORT_ARRAY = new short[0];\n /** An empty immutable Short array. */\n public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];\n /** An empty immutable byte array. */\n public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];\n /** An empty immutable Byte array. */\n public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];\n /** An empty immutable double array. */\n public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];\n /** An empty immutable Double array. */\n public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];\n /** An empty immutable float array. */\n public static final float[] EMPTY_FLOAT_ARRAY = new float[0];\n /** An empty immutable Float array. */\n public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];\n /** An empty immutable boolean array. */\n public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];\n /** An empty immutable Boolean array. */\n public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];\n /** An empty immutable char array. */\n public static final char[] EMPTY_CHAR_ARRAY = new char[0];\n /** An empty immutable Character array. */\n public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];\n /**\n * The index value when an element is not found in a list or array: -1.\n * This value is returned by methods in this class and can also be used in comparisons with values returned by\n * various method from {@link java.util.List}.\n */\n public static final int INDEX_NOT_FOUND = -1;\n\n /**\n *

          ArrayUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

          \n *\n *

          This constructor is public to permit tools that require a JavaBean instance\n * to operate.

          \n */\n public ArrayUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Converts the given array into a {@link Map}. Each element of the array\n * must be either a {@link Entry} or an Array, containing at least two\n * elements, where the first element is used as key and the second as\n * value.

          \n *\n *

          This method can be used to initialize:

          \n *
          \n     * // Create a Map mapping colors.\n     * Map colorMap = ArrayUtils.toMap(new String[][] {{\n     *     {\"RED\", \"#FF0000\"},\n     *     {\"GREEN\", \"#00FF00\"},\n     *     {\"BLUE\", \"#0000FF\"}});\n     * 
          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array an array whose elements are either a {@link Entry} or\n * an Array containing at least two elements, may be null\n * @return a Map that was created from the array\n * @throws IllegalArgumentException if one element of this Array is\n * itself an Array containing less then two elements\n * @throws IllegalArgumentException if the array contains elements other\n * than {@link Entry} and an Array\n */\n public static Map toMap(final Object[] array) {\n if (array == null) {\n return null;\n }\n final Map map = new HashMap((int) (array.length * 1.5));\n for (int i = 0; i < array.length; i++) {\n Object object = array[i];\n if (object instanceof Entry) {\n Entry entry = (Entry) object;\n map.put(entry.getKey(), entry.getValue());\n } else if (object instanceof Object[]) {\n Object[] entry = (Object[]) object;\n if (entry.length < 2) {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', has a length less than 2\");\n }\n map.put(entry[0], entry[1]);\n } else {\n throw new IllegalArgumentException(\"Array element \" + i + \", '\" + object + \"', is neither of type Map.Entry nor an Array\");\n }\n }\n return map;\n }\n // Clone\n //-----------------------------------------------------------------------\n\n /**\n *

          Shallow clones an array returning a typecast result and handling\n * null.

          \n *\n *

          The objects in the array are not cloned, thus there is no special\n * handling for multi-dimensional arrays.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to shallow clone, may be null\n * @return the cloned array, null if null input\n */\n public static Object[] clone(final Object[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static long[] clone(final long[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static int[] clone(final int[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static short[] clone(final short[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static char[] clone(final char[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static byte[] clone(final byte[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static double[] clone(final double[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static float[] clone(final float[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static boolean[] clone(final boolean[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n /**\n *

          Clones an array returning a typecast result and handling\n * null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array the array to clone, may be null\n * @return the cloned array, null if null input\n */\n public static String[] clone(final String[] array) {\n if (array == null) {\n return null;\n }\n return array.clone();\n }\n // nullToEmpty\n //-----------------------------------------------------------------------\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Object[] nullToEmpty(final Object[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static String[] nullToEmpty(final String[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static long[] nullToEmpty(final long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static int[] nullToEmpty(final int[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static short[] nullToEmpty(final short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static char[] nullToEmpty(final char[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static byte[] nullToEmpty(final byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static double[] nullToEmpty(final double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static float[] nullToEmpty(final float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static boolean[] nullToEmpty(final boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Long[] nullToEmpty(final Long[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Integer[] nullToEmpty(final Integer[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Short[] nullToEmpty(final Short[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Character[] nullToEmpty(final Character[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Byte[] nullToEmpty(final Byte[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Double[] nullToEmpty(final Double[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Float[] nullToEmpty(final Float[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n return array;\n }\n\n /**\n *

          Defensive programming technique to change a null\n * reference to an empty one.

          \n *\n *

          This method returns an empty array for a null input array.

          \n *\n *

          As a memory optimizing technique an empty array passed in will be overridden with\n * the empty public static references in this class.

          \n *\n * @param array the array to check for null or empty\n * @return the same array, public static empty array if null or empty input\n * @since 2.5\n */\n public static Boolean[] nullToEmpty(final Boolean[] array) {\n if (array == null || array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n return array;\n }\n // Subarrays\n //-----------------------------------------------------------------------\n\n /**\n *

          Produces a new array containing the elements between\n * the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n *

          The component type of the subarray is always the same as\n * that of the input array. Thus, if the input is an array of type\n * Date, the following usage is envisaged:

          \n *\n *
          \n     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);\n     * 
          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static Object[] subarray(final Object[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n Class type = array.getClass().getComponentType();\n if (newSize <= 0) {\n return (Object[]) Array.newInstance(type, 0);\n }\n Object[] subarray = (Object[]) Array.newInstance(type, newSize);\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new long array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static long[] subarray(final long[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n long[] subarray = new long[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new int array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static int[] subarray(final int[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n int[] subarray = new int[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new short array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static short[] subarray(final short[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n short[] subarray = new short[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new char array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static char[] subarray(final char[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n char[] subarray = new char[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new byte array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new double array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static double[] subarray(final double[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n double[] subarray = new double[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new float array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static float[] subarray(final float[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n float[] subarray = new float[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n\n /**\n *

          Produces a new boolean array containing the elements\n * between the start and end indices.

          \n *\n *

          The start index is inclusive, the end index exclusive.\n * Null array input produces null output.

          \n *\n * @param array the array\n * @param startIndexInclusive the starting index. Undervalue (<0)\n * is promoted to 0, overvalue (>array.length) results\n * in an empty array.\n * @param endIndexExclusive elements up to endIndex-1 are present in the\n * returned subarray. Undervalue (< startIndex) produces\n * empty array, overvalue (>array.length) is demoted to\n * array length.\n * @return a new array containing the elements between\n * the start and end indices.\n * @since 2.1\n */\n public static boolean[] subarray(final boolean[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n boolean[] subarray = new boolean[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n }\n // Is same length\n //-----------------------------------------------------------------------\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.\n *\n *

          Any multi-dimensional aspects of the arrays are ignored.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final Object[] array1, final Object[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final long[] array1, final long[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final int[] array1, final int[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final short[] array1, final short[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final char[] array1, final char[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final byte[] array1, final byte[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final double[] array1, final double[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final float[] array1, final float[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n\n /**\n *

          Checks whether two arrays are the same length, treating\n * null arrays as length 0.

          \n *\n * @param array1 the first array, may be null\n * @param array2 the second array, may be null\n * @return true if length of arrays matches, treating\n * null as an empty array\n */\n public static boolean isSameLength(final boolean[] array1, final boolean[] array2) {\n if (array1 == null && array2 != null && array2.length > 0 || array2 == null && array1 != null && array1.length > 0 || array1 != null && array2 != null && array1.length != array2.length) {\n return false;\n }\n return true;\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Returns the length of the specified array.\n * This method can deal with Object arrays and with primitive arrays.

          \n *\n *

          If the input array is null, 0 is returned.

          \n *\n *
          \n     * ArrayUtils.getLength(null)            = 0\n     * ArrayUtils.getLength([])              = 0\n     * ArrayUtils.getLength([null])          = 1\n     * ArrayUtils.getLength([true, false])   = 2\n     * ArrayUtils.getLength([1, 2, 3])       = 3\n     * ArrayUtils.getLength([\"a\", \"b\", \"c\"]) = 3\n     * 
          \n *\n * @param array the array to retrieve the length from, may be null\n * @return The length of the array, or 0 if the array is null\n * @throws IllegalArgumentException if the object arguement is not an array.\n * @since 2.1\n */\n public static int getLength(final Object array) {\n if (array == null) {\n return 0;\n }\n return Array.getLength(array);\n }\n\n /**\n *

          Checks whether two arrays are the same type taking into account\n * multi-dimensional arrays.

          \n *\n * @param array1 the first array, must not be null\n * @param array2 the second array, must not be null\n * @return true if type of arrays matches\n * @throws IllegalArgumentException if either array is null\n */\n public static boolean isSameType(final Object array1, final Object array2) {\n if (array1 == null || array2 == null) {\n throw new IllegalArgumentException(\"The Array must not be null\");\n }\n return array1.getClass().getName().equals(array2.getClass().getName());\n }\n // Reverse\n //-----------------------------------------------------------------------\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          There is no special handling for multi-dimensional arrays.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final Object[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n Object tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final long[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n long tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final int[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n int tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final short[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n short tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final char[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n char tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final byte[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n byte tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final double[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n double tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final float[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n float tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n\n /**\n *

          Reverses the order of the given array.

          \n *\n *

          This method does nothing for a null input array.

          \n *\n * @param array the array to reverse, may be null\n */\n public static void reverse(final boolean[] array) {\n if (array == null) {\n return;\n }\n int i = 0;\n int j = array.length - 1;\n boolean tmp;\n while (j > i) {\n tmp = array[j];\n array[j] = array[i];\n array[i] = tmp;\n j--;\n i++;\n }\n }\n // IndexOf search\n // ----------------------------------------------------------------------\n // Object IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given object in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind, 0);\n }\n\n /**\n *

          Finds the index of the given object in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the index to start searching at\n * @return the index of the object within the array starting at the index,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i < array.length; i++) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given object within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind) {\n return ArrayUtils.lastIndexOf(array, objectToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given object in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param objectToFind the object to find, may be null\n * @param startIndex the start index to travers backwards from\n * @return the last index of the object within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n if (objectToFind == null) {\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] == null) {\n return i;\n }\n }\n } else if (array.getClass().getComponentType().isInstance(objectToFind)) {\n for (int i = startIndex; i >= 0; i--) {\n if (objectToFind.equals(array[i])) {\n return i;\n }\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the object is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param objectToFind the object to find\n * @return true if the array contains the object\n */\n public static boolean contains(final Object[] array, final Object objectToFind) {\n return ArrayUtils.indexOf(array, objectToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // long IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final long[] array, final long valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // int IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final int[] array, final int valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // short IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final short[] array, final short valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // char IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int indexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n * @since 2.1\n */\n public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n * @since 2.1\n */\n public static boolean contains(final char[] array, final char valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // byte IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {\n if (array == null) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final byte[] array, final byte valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // double IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value within a given tolerance in the array.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.\n * This method will return the index of the first value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i < array.length; i++) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value within a given tolerance in the array.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param tolerance tolerance of the search\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.\n * This method will return the index of the last value which falls between the region\n * defined by valueToFind - tolerance and valueToFind + tolerance.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @param tolerance search for value within plus/minus this amount\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n double min = valueToFind - tolerance;\n double max = valueToFind + tolerance;\n for (int i = startIndex; i >= 0; i--) {\n if (array[i] >= min && array[i] <= max) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final double[] array, final double valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if a value falling within the given tolerance is in the\n * given array. If the array contains a value within the inclusive range\n * defined by (value - tolerance) to (value + tolerance).

          \n *\n *

          The method returns false if a null array\n * is passed in.

          \n *\n * @param array the array to search\n * @param valueToFind the value to find\n * @param tolerance the array contains the tolerance of the search\n * @return true if value falling within tolerance is in array\n */\n public static boolean contains(final double[] array, final double valueToFind, final double tolerance) {\n return ArrayUtils.indexOf(array, valueToFind, 0, tolerance) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // float IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the\n * array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final float[] array, final float valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // boolean IndexOf\n //-----------------------------------------------------------------------\n\n /**\n *

          Finds the index of the given value in the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind, 0);\n }\n\n /**\n *

          Finds the index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex is treated as zero. A startIndex larger than the array\n * length will return {@link #INDEX_NOT_FOUND} (-1).

          \n *\n * @param array the array to search through for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the index to start searching at\n * @return the index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null\n * array input\n */\n public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n startIndex = 0;\n }\n for (int i = startIndex; i < array.length; i++) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Finds the last index of the given value within the array.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) if\n * null array input.

          \n *\n * @param array the array to travers backwords looking for the object, may be null\n * @param valueToFind the object to find\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.lastIndexOf(array, valueToFind, Integer.MAX_VALUE);\n }\n\n /**\n *

          Finds the last index of the given value in the array starting at the given index.

          \n *\n *

          This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

          \n *\n *

          A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than\n * the array length will search from the end of the array.

          \n *\n * @param array the array to traverse for looking for the object, may be null\n * @param valueToFind the value to find\n * @param startIndex the start index to travers backwards from\n * @return the last index of the value within the array,\n * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input\n */\n public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {\n if (ArrayUtils.isEmpty(array)) {\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n if (startIndex < 0) {\n return ArrayUtils.INDEX_NOT_FOUND;\n } else if (startIndex >= array.length) {\n startIndex = array.length - 1;\n }\n for (int i = startIndex; i >= 0; i--) {\n if (valueToFind == array[i]) {\n return i;\n }\n }\n return ArrayUtils.INDEX_NOT_FOUND;\n }\n\n /**\n *

          Checks if the value is in the given array.

          \n *\n *

          The method returns false if a null array is passed in.

          \n *\n * @param array the array to search through\n * @param valueToFind the value to find\n * @return true if the array contains the object\n */\n public static boolean contains(final boolean[] array, final boolean valueToFind) {\n return ArrayUtils.indexOf(array, valueToFind) != ArrayUtils.INDEX_NOT_FOUND;\n }\n // Primitive/Object array converters\n // ----------------------------------------------------------------------\n // Character array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Characters to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Character array, may be null\n * @return a char array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static char[] toPrimitive(final Character[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].charValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Character to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Character array, may be null\n * @param valueForNull the value to insert if null found\n * @return a char array, null if null array input\n */\n public static char[] toPrimitive(final Character[] array, final char valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHAR_ARRAY;\n }\n final char[] result = new char[array.length];\n for (int i = 0; i < array.length; i++) {\n Character b = array[i];\n result[i] = b == null ? valueForNull : b.charValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive chars to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a char array\n * @return a Character array, null if null array input\n */\n public static Character[] toObject(final char[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY;\n }\n final Character[] result = new Character[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Character(array[i]);\n }\n return result;\n }\n // Long array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Longs to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Long array, may be null\n * @return a long array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static long[] toPrimitive(final Long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].longValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Long to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Long array, may be null\n * @param valueForNull the value to insert if null found\n * @return a long array, null if null array input\n */\n public static long[] toPrimitive(final Long[] array, final long valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_ARRAY;\n }\n final long[] result = new long[array.length];\n for (int i = 0; i < array.length; i++) {\n Long b = array[i];\n result[i] = b == null ? valueForNull : b.longValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive longs to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a long array\n * @return a Long array, null if null array input\n */\n public static Long[] toObject(final long[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_LONG_OBJECT_ARRAY;\n }\n final Long[] result = new Long[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Long(array[i]);\n }\n return result;\n }\n // Int array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Integers to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Integer array, may be null\n * @return an int array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static int[] toPrimitive(final Integer[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].intValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Integer to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Integer array, may be null\n * @param valueForNull the value to insert if null found\n * @return an int array, null if null array input\n */\n public static int[] toPrimitive(final Integer[] array, final int valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INT_ARRAY;\n }\n final int[] result = new int[array.length];\n for (int i = 0; i < array.length; i++) {\n Integer b = array[i];\n result[i] = b == null ? valueForNull : b.intValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive ints to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array an int array\n * @return an Integer array, null if null array input\n */\n public static Integer[] toObject(final int[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY;\n }\n final Integer[] result = new Integer[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Integer(array[i]);\n }\n return result;\n }\n // Short array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Shorts to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Short array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static short[] toPrimitive(final Short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].shortValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Short to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Short array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static short[] toPrimitive(final Short[] array, final short valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_ARRAY;\n }\n final short[] result = new short[array.length];\n for (int i = 0; i < array.length; i++) {\n Short b = array[i];\n result[i] = b == null ? valueForNull : b.shortValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive shorts to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a short array\n * @return a Short array, null if null array input\n */\n public static Short[] toObject(final short[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY;\n }\n final Short[] result = new Short[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Short(array[i]);\n }\n return result;\n }\n // Byte array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Bytes to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Byte array, may be null\n * @return a byte array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static byte[] toPrimitive(final Byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].byteValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Bytes to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Byte array, may be null\n * @param valueForNull the value to insert if null found\n * @return a byte array, null if null array input\n */\n public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_ARRAY;\n }\n final byte[] result = new byte[array.length];\n for (int i = 0; i < array.length; i++) {\n Byte b = array[i];\n result[i] = b == null ? valueForNull : b.byteValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive bytes to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a byte array\n * @return a Byte array, null if null array input\n */\n public static Byte[] toObject(final byte[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;\n }\n final Byte[] result = new Byte[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Byte(array[i]);\n }\n return result;\n }\n // Double array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Doubles to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Double array, may be null\n * @return a double array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static double[] toPrimitive(final Double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].doubleValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Doubles to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Double array, may be null\n * @param valueForNull the value to insert if null found\n * @return a double array, null if null array input\n */\n public static double[] toPrimitive(final Double[] array, final double valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_ARRAY;\n }\n final double[] result = new double[array.length];\n for (int i = 0; i < array.length; i++) {\n Double b = array[i];\n result[i] = b == null ? valueForNull : b.doubleValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive doubles to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a double array\n * @return a Double array, null if null array input\n */\n public static Double[] toObject(final double[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY;\n }\n final Double[] result = new Double[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Double(array[i]);\n }\n return result;\n }\n // Float array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Floats to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Float array, may be null\n * @return a float array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static float[] toPrimitive(final Float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].floatValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Floats to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Float array, may be null\n * @param valueForNull the value to insert if null found\n * @return a float array, null if null array input\n */\n public static float[] toPrimitive(final Float[] array, final float valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_ARRAY;\n }\n final float[] result = new float[array.length];\n for (int i = 0; i < array.length; i++) {\n Float b = array[i];\n result[i] = b == null ? valueForNull : b.floatValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive floats to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a float array\n * @return a Float array, null if null array input\n */\n public static Float[] toObject(final float[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY;\n }\n final Float[] result = new Float[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = new Float(array[i]);\n }\n return result;\n }\n // Boolean array converters\n // ----------------------------------------------------------------------\n\n /**\n *

          Converts an array of object Booleans to primitives.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Boolean array, may be null\n * @return a boolean array, null if null array input\n * @throws NullPointerException if array content is null\n */\n public static boolean[] toPrimitive(final Boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i].booleanValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of object Booleans to primitives handling null.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a Boolean array, may be null\n * @param valueForNull the value to insert if null found\n * @return a boolean array, null if null array input\n */\n public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_ARRAY;\n }\n final boolean[] result = new boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n Boolean b = array[i];\n result[i] = b == null ? valueForNull : b.booleanValue();\n }\n return result;\n }\n\n /**\n *

          Converts an array of primitive booleans to objects.

          \n *\n *

          This method returns null for a null input array.

          \n *\n * @param array a boolean array\n * @return a Boolean array, null if null array input\n */\n public static Boolean[] toObject(final boolean[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY;\n }\n final Boolean[] result = new Boolean[array.length];\n for (int i = 0; i < array.length; i++) {\n result[i] = array[i] ? Boolean.TRUE : Boolean.FALSE;\n }\n return result;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

          Checks if an array of Objects is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final Object[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive longs is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final long[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive ints is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final int[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive shorts is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final short[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive chars is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final char[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive bytes is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final byte[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive doubles is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final double[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive floats is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final float[] array) {\n return array == null || array.length == 0;\n }\n\n /**\n *

          Checks if an array of primitive booleans is empty or null.

          \n *\n * @param array the array to test\n * @return true if the array is empty or null\n * @since 2.1\n */\n public static boolean isEmpty(final boolean[] array) {\n return array == null || array.length == 0;\n }\n // ----------------------------------------------------------------------\n\n /**\n *

          Checks if an array of Objects is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final Object[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive longs is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final long[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive ints is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final int[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive shorts is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final short[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive chars is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final char[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive bytes is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final byte[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive doubles is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final double[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive floats is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final float[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Checks if an array of primitive booleans is not empty or not null.

          \n *\n * @param array the array to test\n * @return true if the array is not empty or not null\n * @since 2.5\n */\n public static boolean isNotEmpty(final boolean[] array) {\n return array != null && array.length != 0;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(null, null)     = null\n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * ArrayUtils.addAll([null], [null]) = [null, null]\n     * ArrayUtils.addAll([\"a\", \"b\", \"c\"], [\"1\", \"2\", \"3\"]) = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array, may be null\n * @param array2 the second array whose elements are added to the new array, may be null\n * @return The new array, null if both arrays are null.\n * The type of the new array is the type of the first array,\n * unless the first array is null, in which case the type is the same as the second array.\n * @since 2.1\n * @throws IllegalArgumentException if the array types are incompatible\n */\n public static Object[] addAll(final Object[] array1, final Object[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n // Check if problem was due to incompatible types\n /*\n * We do this here, rather than before the copy because:\n * - it would be a wasted check most of the time\n * - safer, in case check turns out to be too strict\n */\n final Class type1 = array1.getClass().getComponentType();\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)) {\n throw new IllegalArgumentException(\"Cannot store \" + type2.getName() + \" in an array of \" + type1.getName());\n }\n throw ase; // No, so rethrow original\n }\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new boolean[] array.\n * @since 2.1\n */\n public static boolean[] addAll(final boolean[] array1, final boolean[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n boolean[] joinedArray = new boolean[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new char[] array.\n * @since 2.1\n */\n public static char[] addAll(final char[] array1, final char[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n char[] joinedArray = new char[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new byte[] array.\n * @since 2.1\n */\n public static byte[] addAll(final byte[] array1, final byte[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n byte[] joinedArray = new byte[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new short[] array.\n * @since 2.1\n */\n public static short[] addAll(final short[] array1, final short[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n short[] joinedArray = new short[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new int[] array.\n * @since 2.1\n */\n public static int[] addAll(final int[] array1, final int[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n int[] joinedArray = new int[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new long[] array.\n * @since 2.1\n */\n public static long[] addAll(final long[] array1, final long[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n long[] joinedArray = new long[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new float[] array.\n * @since 2.1\n */\n public static float[] addAll(final float[] array1, final float[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n float[] joinedArray = new float[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new double[] array.\n * @since 2.1\n */\n public static double[] addAll(final double[] array1, final double[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n double[] joinedArray = new double[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

          Adds all the elements of the given arrays into a new array.

          \n *

          The new array contains all of the element of array1 followed\n * by all of the elements array2. When an array is returned, it is always\n * a new array.

          \n *\n *
          \n     * ArrayUtils.addAll(array1, null)   = cloned copy of array1\n     * ArrayUtils.addAll(null, array2)   = cloned copy of array2\n     * ArrayUtils.addAll([], [])         = []\n     * 
          \n *\n * @param array1 the first array whose elements are added to the new array.\n * @param array2 the second array whose elements are added to the new array.\n * @return The new String[] array.\n * @since 2.1\n */\n public static String[] addAll(final String[] array1, final String[] array2) {\n if (array1 == null) {\n return ArrayUtils.clone(array2);\n } else if (array2 == null) {\n return ArrayUtils.clone(array1);\n }\n String[] joinedArray = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element, unless the element itself is null,\n * in which case the return type is Object[]

          \n *\n *
          \n     * ArrayUtils.add(null, null)      = [null]\n     * ArrayUtils.add(null, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], \"c\") = [\"a\", \"b\", \"c\"]\n     * 
          \n *\n * @param array the array to \"add\" the element to, may be null\n * @param element the object to add, may be null\n * @return A new array containing the existing elements plus the new element\n * The returned array type will be that of the input array (unless null),\n * in which case it will have the same type as the element.\n * @since 2.1\n */\n public static T[] add(final T[] array, final T element) {\n Class type;\n if (array != null) {\n type = array.getClass();\n } else if (element != null) {\n type = element.getClass();\n } else {\n type = Object.class;\n }\n T[] newArray = (T[]) ArrayUtils.copyArrayGrow1(array, type);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, true)          = [true]\n     * ArrayUtils.add([true], false)       = [true, false]\n     * ArrayUtils.add([true, false], true) = [true, false, true]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static boolean[] add(final boolean[] array, final boolean element) {\n boolean[] newArray = (boolean[]) ArrayUtils.copyArrayGrow1(array, Boolean.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static byte[] add(final byte[] array, final byte element) {\n byte[] newArray = (byte[]) ArrayUtils.copyArrayGrow1(array, Byte.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, '0')       = ['0']\n     * ArrayUtils.add(['1'], '0')      = ['1', '0']\n     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static char[] add(final char[] array, final char element) {\n char[] newArray = (char[]) ArrayUtils.copyArrayGrow1(array, Character.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static double[] add(final double[] array, final double element) {\n double[] newArray = (double[]) ArrayUtils.copyArrayGrow1(array, Double.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static float[] add(final float[] array, final float element) {\n float[] newArray = (float[]) ArrayUtils.copyArrayGrow1(array, Float.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static int[] add(final int[] array, final int element) {\n int[] newArray = (int[]) ArrayUtils.copyArrayGrow1(array, Integer.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static long[] add(final long[] array, final long element) {\n long[] newArray = (long[]) ArrayUtils.copyArrayGrow1(array, Long.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n *

          Copies the given array and adds the given element at the end of the new array.

          \n *\n *

          The new array contains the same elements of the input\n * array plus the given element in the last position. The component type of\n * the new array is the same as that of the input array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0)   = [0]\n     * ArrayUtils.add([1], 0)    = [1, 0]\n     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]\n     * 
          \n *\n * @param array the array to copy and add the element to, may be null\n * @param element the object to add at the last index of the new array\n * @return A new array containing the existing elements plus the new element\n * @since 2.1\n */\n public static short[] add(final short[] array, final short element) {\n short[] newArray = (short[]) ArrayUtils.copyArrayGrow1(array, Short.TYPE);\n newArray[newArray.length - 1] = element;\n return newArray;\n }\n\n /**\n * Returns a copy of the given array of size 1 greater than the argument.\n * The last value of the array is left to the default value.\n *\n * @param array The array to copy, must not be null.\n * @param newArrayComponentType If array is null, create a\n * size 1 array of this type.\n * @return A new copy of the array of size 1 greater than the input.\n */\n private static Object copyArrayGrow1(final Object array, final Class newArrayComponentType) {\n if (array != null) {\n int arrayLength = Array.getLength(array);\n Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);\n System.arraycopy(array, 0, newArray, 0, arrayLength);\n return newArray;\n }\n return Array.newInstance(newArrayComponentType, 1);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0, null)      = [null]\n     * ArrayUtils.add(null, 0, \"a\")       = [\"a\"]\n     * ArrayUtils.add([\"a\"], 1, null)     = [\"a\", null]\n     * ArrayUtils.add([\"a\"], 1, \"b\")      = [\"a\", \"b\"]\n     * ArrayUtils.add([\"a\", \"b\"], 3, \"c\") = [\"a\", \"b\", \"c\"]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index > array.length).\n */\n public static Object[] add(final Object[] array, final int index, final Object element) {\n Class clss = null;\n if (array != null) {\n clss = array.getClass().getComponentType();\n } else if (element != null) {\n clss = element.getClass();\n } else {\n return new Object[] { null };\n }\n return (Object[]) ArrayUtils.add(array, index, element, clss);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0, true)          = [true]\n     * ArrayUtils.add([true], 0, false)       = [false, true]\n     * ArrayUtils.add([false], 1, true)       = [false, true]\n     * ArrayUtils.add([true, false], 1, true) = [true, true, false]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static boolean[] add(final boolean[] array, final int index, final boolean element) {\n Boolean booElement = element ? Boolean.TRUE : Boolean.FALSE;\n return (boolean[]) ArrayUtils.add(array, index, booElement, Boolean.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add(null, 0, 'a')            = ['a']\n     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']\n     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']\n     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']\n     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static char[] add(final char[] array, final int index, final char element) {\n return (char[]) ArrayUtils.add(array, index, new Character(element), Character.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]\n     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static byte[] add(final byte[] array, final int index, final byte element) {\n return (byte[]) ArrayUtils.add(array, index, new Byte(element), Byte.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static short[] add(final short[] array, final int index, final short element) {\n return (short[]) ArrayUtils.add(array, index, new Short(element), Short.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add([1], 0, 2)         = [2, 1]\n     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]\n     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]\n     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static int[] add(final int[] array, final int index, final int element) {\n return (int[]) ArrayUtils.add(array, index, new Integer(element), Integer.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]\n     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]\n     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]\n     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static long[] add(final long[] array, final int index, final long element) {\n return (long[]) ArrayUtils.add(array, index, new Long(element), Long.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]\n     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]\n     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]\n     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static float[] add(final float[] array, final int index, final float element) {\n return (float[]) ArrayUtils.add(array, index, new Float(element), Float.TYPE);\n }\n\n /**\n *

          Inserts the specified element at the specified position in the array.\n * Shifts the element currently at that position (if any) and any subsequent\n * elements to the right (adds one to their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array plus the given element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, a new one element array is returned\n * whose component type is the same as the element.

          \n *\n *
          \n     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]\n     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]\n     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]\n     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]\n     * 
          \n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @return A new array containing the existing elements and the new element\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index > array.length).\n */\n public static double[] add(final double[] array, final int index, final double element) {\n return (double[]) ArrayUtils.add(array, index, new Double(element), Double.TYPE);\n }\n\n /**\n * Underlying implementation of add(array, index, element) methods.\n * The last parameter is the class, which may not equal element.getClass\n * for primitives.\n *\n * @param array the array to add the element to, may be null\n * @param index the position of the new object\n * @param element the object to add\n * @param clss the type of the element being added\n * @return A new array containing the existing elements and the new element\n */\n private static Object add(final Object array, final int index, final Object element, final Class clss) {\n if (array == null) {\n if (index != 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: 0\");\n }\n Object joinedArray = Array.newInstance(clss, 1);\n Array.set(joinedArray, 0, element);\n return joinedArray;\n }\n int length = Array.getLength(array);\n if (index > length || index < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(clss, length + 1);\n System.arraycopy(array, 0, result, 0, index);\n Array.set(result, index, element);\n if (index < length) {\n System.arraycopy(array, index, result, index + 1, length - index);\n }\n return result;\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([\"a\"], 0)           = []\n     * ArrayUtils.remove([\"a\", \"b\"], 0)      = [\"b\"]\n     * ArrayUtils.remove([\"a\", \"b\"], 1)      = [\"a\"]\n     * ArrayUtils.remove([\"a\", \"b\", \"c\"], 1) = [\"a\", \"c\"]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static Object[] remove(final Object[] array, final int index) {\n return (Object[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, \"a\")            = null\n     * ArrayUtils.removeElement([], \"a\")              = []\n     * ArrayUtils.removeElement([\"a\"], \"b\")           = [\"a\"]\n     * ArrayUtils.removeElement([\"a\", \"b\"], \"a\")      = [\"b\"]\n     * ArrayUtils.removeElement([\"a\", \"b\", \"a\"], \"a\") = [\"b\", \"a\"]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static Object[] removeElement(final Object[] array, final Object element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([true], 0)              = []\n     * ArrayUtils.remove([true, false], 0)       = [false]\n     * ArrayUtils.remove([true, false], 1)       = [true]\n     * ArrayUtils.remove([true, true, false], 1) = [true, false]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static boolean[] remove(final boolean[] array, final int index) {\n return (boolean[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, true)                = null\n     * ArrayUtils.removeElement([], true)                  = []\n     * ArrayUtils.removeElement([true], false)             = [true]\n     * ArrayUtils.removeElement([true, false], false)      = [true]\n     * ArrayUtils.removeElement([true, false, true], true) = [false, true]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static boolean[] removeElement(final boolean[] array, final boolean element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([1], 0)          = []\n     * ArrayUtils.remove([1, 0], 0)       = [0]\n     * ArrayUtils.remove([1, 0], 1)       = [1]\n     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static byte[] remove(final byte[] array, final int index) {\n return (byte[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 1)        = null\n     * ArrayUtils.removeElement([], 1)          = []\n     * ArrayUtils.removeElement([1], 0)         = [1]\n     * ArrayUtils.removeElement([1, 0], 0)      = [1]\n     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static byte[] removeElement(final byte[] array, final byte element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove(['a'], 0)           = []\n     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']\n     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']\n     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static char[] remove(final char[] array, final int index) {\n return (char[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 'a')            = null\n     * ArrayUtils.removeElement([], 'a')              = []\n     * ArrayUtils.removeElement(['a'], 'b')           = ['a']\n     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']\n     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static char[] removeElement(final char[] array, final char element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static double[] remove(final double[] array, final int index) {\n return (double[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static double[] removeElement(final double[] array, final double element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([1.1], 0)           = []\n     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]\n     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]\n     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static float[] remove(final float[] array, final int index) {\n return (float[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 1.1)            = null\n     * ArrayUtils.removeElement([], 1.1)              = []\n     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]\n     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]\n     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static float[] removeElement(final float[] array, final float element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static int[] remove(final int[] array, final int index) {\n return (int[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static int[] removeElement(final int[] array, final int element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static long[] remove(final long[] array, final int index) {\n return (long[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static long[] removeElement(final long[] array, final long element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n *
          \n     * ArrayUtils.remove([1], 0)         = []\n     * ArrayUtils.remove([2, 6], 0)      = [6]\n     * ArrayUtils.remove([2, 6], 1)      = [2]\n     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]\n     * 
          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n public static short[] remove(final short[] array, final int index) {\n return (short[]) ArrayUtils.remove((Object) array, index);\n }\n\n /**\n *

          Removes the first occurrence of the specified element from the\n * specified array. All subsequent elements are shifted to the left\n * (substracts one from their indices). If the array doesn't contains\n * such an element, no elements are removed from the array.

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the first occurrence of the specified element. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *
          \n     * ArrayUtils.removeElement(null, 1)      = null\n     * ArrayUtils.removeElement([], 1)        = []\n     * ArrayUtils.removeElement([1], 2)       = [1]\n     * ArrayUtils.removeElement([1, 3], 1)    = [3]\n     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]\n     * 
          \n *\n * @param array the array to remove the element from, may be null\n * @param element the element to be removed\n * @return A new array containing the existing elements except the first\n * occurrence of the specified element.\n * @since 2.1\n */\n public static short[] removeElement(final short[] array, final short element) {\n int index = ArrayUtils.indexOf(array, element);\n if (index == ArrayUtils.INDEX_NOT_FOUND) {\n return ArrayUtils.clone(array);\n }\n return ArrayUtils.remove(array, index);\n }\n\n /**\n *

          Removes the element at the specified position from the specified array.\n * All subsequent elements are shifted to the left (substracts one from\n * their indices).

          \n *\n *

          This method returns a new array with the same elements of the input\n * array except the element on the specified position. The component\n * type of the returned array is always the same as that of the input\n * array.

          \n *\n *

          If the input array is null, an IndexOutOfBoundsException\n * will be thrown, because in that case no valid index can be specified.

          \n *\n * @param array the array to remove the element from, may not be null\n * @param index the position of the element to be removed\n * @return A new array containing the existing elements except the element\n * at the specified position.\n * @throws IndexOutOfBoundsException if the index is out of range\n * (index < 0 || index >= array.length), or if the array is null.\n * @since 2.1\n */\n private static Object remove(final Object array, final int index) {\n int length = ArrayUtils.getLength(array);\n if (index < 0 || index >= length) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Length: \" + length);\n }\n Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);\n System.arraycopy(array, 0, result, 0, index);\n if (index < length - 1) {\n System.arraycopy(array, index + 1, result, index, length - index - 1);\n }\n return result;\n }\n\n /**删除数组中空元素*/\n public static Object[] clearNull(final Object[] arr) {\n ArrayList list = new ArrayList();\n if (arr != null) {\n for (Object item : arr) {\n if (item != null) {\n list.add(item);\n }\n }\n }\n return list.toArray();\n }\n}\n", "file_name": "ArrayUtils.java", "human_label": "Return a clone of the given array.", "level": "self_contained", "lineno": "222", "name": "clone", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636766831a6d9265ec0174eb", "all_context": "{ \"class_level\" : \"import java.io.File;\\nimport java.io.IOException;\\nimport java.util.Deque;\\nimport java.util.LinkedList;\\nimport java.util.NoSuchElementException;\\nDeque stack;\\nint rootCount;\\nFile current;\\nFileIterator(File filesOrDirectories);\\ngetFile();\\nnext();\\naddReverse(File[] files);\\nisRootFile();\\n\", \"repo_level\" : \"\" }", "class_name": "FileIterator", "code": "private void addReverse(final File[] files){\n if (files == null) return;\n for (int i=files.length - 1; i >= 0; --i) {\n stack.add(files[i]);\n }\n}\n", "docstring": "/** \n * Add the specified files in reverse order.\n */\n", "end_lineno": "139", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n/* FileIterator.java\n * \n ******************************************************************************\n *\n * Created: Oct 10, 2011\n * Character encoding: UTF-8\n * \n * Copyright (c) 2011 - XIAM Solutions B.V. The Netherlands, http://www.xiam.nl\n * \n ********************************* LICENSE ************************************\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.atmosphere.util.annotation;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Deque;\nimport java.util.LinkedList;\nimport java.util.NoSuchElementException;\n\n/**\n * {@code FileIterator} enables iteration over all files in a directory and all\n * its sub directories.\n *
          \n * Usage:\n *
          \n * FileIterator iter = new FileIterator(new File(\"./src\"));\n * File f;\n * while ((f = iter.next()) != null) {\n *     // do something with f\n *     assert f == iter.getCurrent();\n * }\n * 
          \n * \n * @author Ronald K. Muller\n * @since annotation-detector 3.0.0\n */\npublic final class FileIterator {\n\n private final Deque stack = new LinkedList<>();\n private int rootCount;\n private File current;\n \n /**\n * Create a new {@code FileIterator} using the specified 'filesOrDirectories' as root.\n *
          \n * If 'filesOrDirectories' contains a file, the iterator just returns that single file. \n * If 'filesOrDirectories' contains a directory, all files in that directory \n * and its sub directories are returned (depth first).\n * \n * @param filesOrDirectories Zero or more {@link java.io.File} objects, which are iterated\n * in the specified order (depth first)\n */\n public FileIterator(final File... filesOrDirectories) {\n addReverse(filesOrDirectories);\n rootCount = stack.size();\n }\n\n /**\n * Return the last returned file or {@code null} if no more files are available.\n *\n * @see #next()\n */\n public File getFile() {\n return current;\n }\n\n /**\n * Return {@code true} if the current file is one of the files originally\n * specified as one of the constructor file parameters, i.e. is a root file\n * or directory.\n */\n public boolean isRootFile() {\n if (current == null) {\n throw new NoSuchElementException();\n }\n return stack.size() < rootCount;\n }\n\n /**\n * Return the next {@link java.io.File} object or {@code null} if no more files are\n * available.\n * \n * @see #getFile()\n */\n public File next() throws IOException {\n if (stack.isEmpty()) {\n current = null;\n return null;\n } else {\n current = stack.removeLast();\n if (current.isDirectory()) {\n if (stack.size() < rootCount) {\n rootCount = stack.size();\n }\n addReverse(current.listFiles());\n return next();\n } else {\n return current;\n }\n }\n }\n\n /**\n * Add the specified files in reverse order.\n */\n private void addReverse(final File[] files) {\n if (files == null) return;\n\n for (int i = files.length - 1; i >=0; --i) {\n stack.add(files[i]);\n }\n }\n\n}\n", "file_name": "FileIterator.java", "human_label": "Put the given array of files into a stack in reverse order. ", "level": "class_runnable", "lineno": "130", "name": "addReverse", "oracle_context": "{ \"apis\" : \"[add]\", \"classes\" : \"[]\", \"vars\" : \"[length, stack]\" }", "package": "org.atmosphere.util.annotation", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767841a6d9265ec0183ff", "all_context": "{ \"class_level\" : \"import java.awt.Adjustable;\\nimport javax.swing.JComponent;\\nimport javax.swing.JScrollPane;\\nimport javax.swing.JTable;\\nimport javax.swing.ListSelectionModel;\\nimport javax.swing.SwingUtilities;\\nimport javax.swing.table.TableModel;\\nmakeScrollBarTrack(Adjustable scrollBar);\\nmakeVerticalScrollBarTrack(JScrollPane pane);\\ncontains(int row,TableModel model);\\nselectRow(int row,ListSelectionModel model);\\nmoveAdjustable(int location,Adjustable scrollBar);\\nrepaintLater(JComponent component);\\nrun();\\n\", \"repo_level\" : \"\" }", "class_name": "LF5SwingUtils", "code": "public static void selectRow(int row,JTable table,JScrollPane pane){\n if (table == null || pane == null) {\n return;\n }\n if (contains(row,table.getModel()) == false) {\n return;\n }\n moveAdjustable(row * table.getRowHeight(),pane.getVerticalScrollBar());\n selectRow(row,table.getSelectionModel());\n repaintLater(table);\n}\n", "docstring": "/** \n * Selects a the specified row in the specified JTable and scrolls the specified JScrollpane to the newly selected row. More importantly, the call to repaint() delayed long enough to have the table properly paint the newly selected row which may be offscre\n * @param table should belong to the specified JScrollPane\n */\n", "end_lineno": "79", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.apache.log4j.lf5.viewer;\n\nimport java.awt.Adjustable;\n\nimport javax.swing.JComponent;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.ListSelectionModel;\nimport javax.swing.SwingUtilities;\nimport javax.swing.table.TableModel;\n\n/**\n * Provides methods to accomplish common yet non-trivial tasks\n * with Swing. Obvious implementations of these methods have been\n * tried and failed.\n *\n * @author Richard Wan\n */\n\n// Contributed by ThoughtWorks Inc.\n\npublic class LF5SwingUtils {\n //--------------------------------------------------------------------------\n // Constants:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Protected Variables:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Private Variables:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Constructors:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Public Methods:\n //--------------------------------------------------------------------------\n\n /**\n * Selects a the specified row in the specified JTable and scrolls\n * the specified JScrollpane to the newly selected row. More importantly,\n * the call to repaint() delayed long enough to have the table\n * properly paint the newly selected row which may be offscre\n * @param table should belong to the specified JScrollPane\n */\n public static void selectRow(int row, JTable table, JScrollPane pane) {\n if (table == null || pane == null) {\n return;\n }\n if (contains(row, table.getModel()) == false) {\n return;\n }\n moveAdjustable(row * table.getRowHeight(), pane.getVerticalScrollBar());\n selectRow(row, table.getSelectionModel());\n // repaint must be done later because moveAdjustable\n // posts requests to the swing thread which must execute before\n // the repaint logic gets executed.\n repaintLater(table);\n }\n\n /**\n * Makes the specified Adjustable track if the view area expands and\n * the specified Adjustable is located near the of the view.\n */\n public static void makeScrollBarTrack(Adjustable scrollBar) {\n if (scrollBar == null) {\n return;\n }\n scrollBar.addAdjustmentListener(new TrackingAdjustmentListener());\n }\n\n /**\n * Makes the vertical scroll bar of the specified JScrollPane\n * track if the view expands (e.g. if rows are added to an underlying\n * table).\n */\n public static void makeVerticalScrollBarTrack(JScrollPane pane) {\n if (pane == null) {\n return;\n }\n makeScrollBarTrack(pane.getVerticalScrollBar());\n }\n\n //--------------------------------------------------------------------------\n // Protected Methods:\n //--------------------------------------------------------------------------\n protected static boolean contains(int row, TableModel model) {\n if (model == null) {\n return false;\n }\n if (row < 0) {\n return false;\n }\n if (row >= model.getRowCount()) {\n return false;\n }\n return true;\n }\n\n protected static void selectRow(int row, ListSelectionModel model) {\n if (model == null) {\n return;\n }\n model.setSelectionInterval(row, row);\n }\n\n protected static void moveAdjustable(int location, Adjustable scrollBar) {\n if (scrollBar == null) {\n return;\n }\n scrollBar.setValue(location);\n }\n\n /**\n * Work around for JTable/viewport bug.\n * @link http://developer.java.sun.com/developer/bugParade/bugs/4205145.html\n */\n protected static void repaintLater(final JComponent component) {\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n component.repaint();\n }\n });\n }\n //--------------------------------------------------------------------------\n // Private Methods:\n //--------------------------------------------------------------------------\n\n //--------------------------------------------------------------------------\n // Nested Top-Level Classes or Interfaces\n //--------------------------------------------------------------------------\n}\n\n", "file_name": "LF5SwingUtils.java", "human_label": "Select the specified row in the given JTable and scroll the given JScrollPane to the row. ", "level": "project_runnable", "lineno": "59", "name": "selectRow", "oracle_context": "{ \"apis\" : \"[contains, getModel, moveAdjustable, getRowHeight, getVerticalScrollBar, getSelectionModel, repaintLater]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "org.apache.log4j.lf5.viewer", "project": "logging-log4j1-main" }, { "_id": "636766a81a6d9265ec017596", "all_context": "{ \"class_level\" : \"byte[] data;\\nint length;\\nByteVector(int initialCapacity);\\nput11(int byteValue1,int byteValue2);\\nputShort(int shortValue);\\nput12(int byteValue,int shortValue);\\nputInt(int intValue);\\nput122(int byteValue,int shortValue1,int shortValue2);\\nputLong(long longValue);\\nputUTF8(String stringValue);\\nencodeUtf8(String stringValue,int offset,int maxByteLength);\\nputByteArray(byte[] byteArrayValue,int byteOffset,int byteLength);\\nenlarge(int size);\\nputByte(int byteValue);\\n\", \"repo_level\" : \"\" }", "class_name": "ByteVector", "code": "public ByteVector putInt(final int intValue){\n int currentLength=length;\n if (currentLength + 4 > data.length) {\n enlarge(4);\n }\n byte[] currentData=data;\n currentData[currentLength++]=(byte)(intValue >>> 24);\n currentData[currentLength++]=(byte)(intValue >>> 16);\n currentData[currentLength++]=(byte)(intValue >>> 8);\n currentData[currentLength++]=(byte)intValue;\n length=currentLength;\n return this;\n}\n", "docstring": "/** \n * Puts an int into this byte vector. The byte vector is automatically enlarged if necessary.\n * @param intValue an int.\n * @return this byte vector.\n */\n", "end_lineno": "155", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage com.alibaba.fastjson2.internal.asm;\n\n/**\n * A dynamically extensible vector of bytes. This class is roughly equivalent to a DataOutputStream\n * on top of a ByteArrayOutputStream, but is more efficient.\n *\n * @author Eric Bruneton\n */\npublic class ByteVector {\n /**\n * The content of this vector. Only the first {@link #length} bytes contain real data.\n */\n byte[] data;\n\n /**\n * The actual number of bytes in this vector.\n */\n int length;\n//\n// /**\n// * Constructs a new {@link ByteVector} with a default initial capacity.\n// */\n// public ByteVector() {\n// data = new byte[64];\n// }\n\n /**\n * Constructs a new {@link ByteVector} with the given initial capacity.\n *\n * @param initialCapacity the initial capacity of the byte vector to be constructed.\n */\n public ByteVector(final int initialCapacity) {\n data = new byte[initialCapacity];\n }\n\n /**\n * Puts a byte into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param byteValue a byte.\n * @return this byte vector.\n */\n public ByteVector putByte(final int byteValue) {\n int currentLength = length;\n if (currentLength + 1 > data.length) {\n enlarge(1);\n }\n data[currentLength++] = (byte) byteValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts two bytes into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param byteValue1 a byte.\n * @param byteValue2 another byte.\n * @return this byte vector.\n */\n final ByteVector put11(final int byteValue1, final int byteValue2) {\n int currentLength = length;\n if (currentLength + 2 > data.length) {\n enlarge(2);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue1;\n currentData[currentLength++] = (byte) byteValue2;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a short into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param shortValue a short.\n * @return this byte vector.\n */\n public ByteVector putShort(final int shortValue) {\n int currentLength = length;\n if (currentLength + 2 > data.length) {\n enlarge(2);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a byte and a short into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteValue a byte.\n * @param shortValue a short.\n * @return this byte vector.\n */\n final ByteVector put12(final int byteValue, final int shortValue) {\n int currentLength = length;\n if (currentLength + 3 > data.length) {\n enlarge(3);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an int into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param intValue an int.\n * @return this byte vector.\n */\n public ByteVector putInt(final int intValue) {\n int currentLength = length;\n if (currentLength + 4 > data.length) {\n enlarge(4);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts one byte and two shorts into this byte vector. The byte vector is automatically enlarged\n * if necessary.\n *\n * @param byteValue a byte.\n * @param shortValue1 a short.\n * @param shortValue2 another short.\n * @return this byte vector.\n */\n final ByteVector put122(final int byteValue, final int shortValue1, final int shortValue2) {\n int currentLength = length;\n if (currentLength + 5 > data.length) {\n enlarge(5);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue;\n currentData[currentLength++] = (byte) (shortValue1 >>> 8);\n currentData[currentLength++] = (byte) shortValue1;\n currentData[currentLength++] = (byte) (shortValue2 >>> 8);\n currentData[currentLength++] = (byte) shortValue2;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a long into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param longValue a long.\n * @return this byte vector.\n */\n public ByteVector putLong(final long longValue) {\n int currentLength = length;\n if (currentLength + 8 > data.length) {\n enlarge(8);\n }\n byte[] currentData = data;\n int intValue = (int) (longValue >>> 32);\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n intValue = (int) longValue;\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param stringValue a String whose UTF8 encoded length must be less than 65536.\n * @return this byte vector.\n */\n // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility).\n public ByteVector putUTF8(final String stringValue) {\n int charLength = stringValue.length();\n if (charLength > 65535) {\n throw new IllegalArgumentException(\"UTF8 string too large\");\n }\n int currentLength = length;\n if (currentLength + 2 + charLength > data.length) {\n enlarge(2 + charLength);\n }\n byte[] currentData = data;\n // Optimistic algorithm: instead of computing the byte length and then serializing the string\n // (which requires two loops), we assume the byte length is equal to char length (which is the\n // most frequent case), and we start serializing the string right away. During the\n // serialization, if we find that this assumption is wrong, we continue with the general method.\n currentData[currentLength++] = (byte) (charLength >>> 8);\n currentData[currentLength++] = (byte) charLength;\n for (int i = 0; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= '\\u0001' && charValue <= '\\u007F') {\n currentData[currentLength++] = (byte) charValue;\n } else {\n length = currentLength;\n return encodeUtf8(stringValue, i, 65535);\n }\n }\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if\n * necessary. The string length is encoded in two bytes before the encoded characters, if there is\n * space for that (i.e. if this.length - offset - 2 >= 0).\n *\n * @param stringValue the String to encode.\n * @param offset the index of the first character to encode. The previous characters are supposed\n * to have already been encoded, using only one byte per character.\n * @param maxByteLength the maximum byte length of the encoded string, including the already\n * encoded characters.\n * @return this byte vector.\n */\n final ByteVector encodeUtf8(final String stringValue, final int offset, final int maxByteLength) {\n int charLength = stringValue.length();\n int byteLength = offset;\n for (int i = offset; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= 0x0001 && charValue <= 0x007F) {\n byteLength++;\n } else if (charValue <= 0x07FF) {\n byteLength += 2;\n } else {\n byteLength += 3;\n }\n }\n if (byteLength > maxByteLength) {\n throw new IllegalArgumentException(\"UTF8 string too large\");\n }\n // Compute where 'byteLength' must be stored in 'data', and store it at this location.\n int byteLengthOffset = length - offset - 2;\n if (byteLengthOffset >= 0) {\n data[byteLengthOffset] = (byte) (byteLength >>> 8);\n data[byteLengthOffset + 1] = (byte) byteLength;\n }\n if (length + byteLength - offset > data.length) {\n enlarge(byteLength - offset);\n }\n int currentLength = length;\n for (int i = offset; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= 0x0001 && charValue <= 0x007F) {\n data[currentLength++] = (byte) charValue;\n } else if (charValue <= 0x07FF) {\n data[currentLength++] = (byte) (0xC0 | charValue >> 6 & 0x1F);\n data[currentLength++] = (byte) (0x80 | charValue & 0x3F);\n } else {\n data[currentLength++] = (byte) (0xE0 | charValue >> 12 & 0xF);\n data[currentLength++] = (byte) (0x80 | charValue >> 6 & 0x3F);\n data[currentLength++] = (byte) (0x80 | charValue & 0x3F);\n }\n }\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an array of bytes into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteArrayValue an array of bytes. May be {@literal null} to put {@code byteLength} null\n * bytes into this byte vector.\n * @param byteOffset index of the first byte of byteArrayValue that must be copied.\n * @param byteLength number of bytes of byteArrayValue that must be copied.\n * @return this byte vector.\n */\n public ByteVector putByteArray(\n final byte[] byteArrayValue, final int byteOffset, final int byteLength) {\n if (length + byteLength > data.length) {\n enlarge(byteLength);\n }\n if (byteArrayValue != null) {\n System.arraycopy(byteArrayValue, byteOffset, data, length, byteLength);\n }\n length += byteLength;\n return this;\n }\n\n /**\n * Enlarges this byte vector so that it can receive 'size' more bytes.\n *\n * @param size number of additional bytes that this byte vector should be able to receive.\n */\n private void enlarge(final int size) {\n int doubleCapacity = 2 * data.length;\n int minimalCapacity = length + size;\n byte[] newData = new byte[doubleCapacity > minimalCapacity ? doubleCapacity : minimalCapacity];\n System.arraycopy(data, 0, newData, 0, length);\n data = newData;\n }\n}\n", "file_name": "ByteVector.java", "human_label": "Divide an int into four bytes and put the bytes into a byte vector called data in big endian order.The vector will be enlarged if necessary.And return the object.", "level": "class_runnable", "lineno": "137", "name": "putInt", "oracle_context": "{ \"apis\" : \"[enlarge, ByteVector]\", \"classes\" : \"[byte[], data]\", \"vars\" : \"[length, data]\" }", "package": "com.alibaba.fastjson2.internal.asm", "project": "fastjson2-main" }, { "_id": "636766fd1a6d9265ec017814", "all_context": "{ \"class_level\" : \"import net.hasor.web.upload.util.Streams;\\nimport java.io.*;\\nimport static java.lang.String.format;\\nimport static net.hasor.web.upload.FileUploadException.UploadErrorCodes.*;\\nbyte CR;\\nbyte LF;\\nbyte DASH;\\nint HEADER_PART_SIZE_MAX;\\nint DEFAULT_BUFSIZE;\\nbyte[] HEADER_SEPARATOR;\\nbyte[] FIELD_SEPARATOR;\\nbyte[] STREAM_TERMINATOR;\\nbyte[] BOUNDARY_PREFIX;\\nInputStream input;\\nint boundaryLength;\\nint keepRegion;\\nbyte[] boundary;\\nint bufSize;\\nbyte[] buffer;\\nint head;\\nint tail;\\nString headerEncoding;\\nlong total;\\nint pad;\\nint pos;\\nboolean closed;\\nint BYTE_POSITIVE_OFFSET;\\nMultipartStream(InputStream input,byte[] boundary,int bufSize);\\nMultipartStream(InputStream input,byte[] boundary);\\ngetHeaderEncoding();\\nsetHeaderEncoding(String encoding);\\nreadBoundary();\\nsetBoundary(byte[] boundary);\\nreadHeaders();\\nreadBodyData(OutputStream output);\\nnewInputStream();\\ndiscardBodyData();\\nskipPreamble();\\narrayequals(byte[] a,byte[] b,int count);\\nfindByte(byte value,int pos);\\nfindSeparator();\\nItemInputStream();\\ngetBytesRead();\\navailable();\\nread();\\nread(byte[] b,int off,int len);\\nclose();\\nclose(boolean pCloseUnderlying);\\nskip(long bytes);\\nmakeAvailable();\\nisClosed();\\nreadByte();\\n\", \"repo_level\" : \"public interface Streams {static long copy(InputStream inputStream,OutputStream outputStream,boolean closeOutputStream);\\nstatic long copy(InputStream inputStream,OutputStream outputStream,boolean closeOutputStream,byte[] buffer);\\nstatic String asString(InputStream inputStream);\\nstatic String asString(InputStream inputStream,String encoding);\\nstatic String checkFileName(String fileName);\\n }\\n\" }", "class_name": "MultipartStream", "code": "public static boolean arrayequals(byte[] a,byte[] b,int count){\n for (int i=0; i < count; i++) {\n if (a[i] != b[i]) {\n return false;\n }\n }\n return true;\n}\n", "docstring": "/** \n * Compares count first bytes in the arrays a and b.\n * @param a The first array to compare.\n * @param b The second array to compare.\n * @param count How many bytes should be compared.\n * @return true if count first bytes in arraysa and b are equal.\n */\n", "end_lineno": "377", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.web.upload;\nimport net.hasor.web.upload.util.Streams;\n\nimport java.io.*;\n\nimport static java.lang.String.format;\nimport static net.hasor.web.upload.FileUploadException.UploadErrorCodes.*;\n\n/**\n *

          Low level API for processing file uploads.\n *\n *

          This class can be used to process data streams conforming to MIME\n * 'multipart' format as defined in\n * RFC 1867. Arbitrarily\n * large amounts of data in the stream can be processed under constant\n * memory usage.\n *\n *

          The format of the stream is defined in the following way:
          \n *\n * \n * multipart-body := preamble 1*encapsulation close-delimiter epilogue
          \n * encapsulation := delimiter body CRLF
          \n * delimiter := \"--\" boundary CRLF
          \n * close-delimiter := \"--\" boundary \"--\"
          \n * preamble := <ignore>
          \n * epilogue := <ignore>
          \n * body := header-part CRLF body-part
          \n * header-part := 1*header CRLF
          \n * header := header-name \":\" header-value
          \n * header-name := <printable ascii characters except \":\">
          \n * header-value := <any ascii characters except CR & LF>
          \n * body-data := <arbitrary data>
          \n *
          \n *\n *

          Note that body-data can contain another mulipart entity. There\n * is limited support for single pass processing of such nested\n * streams. The nested stream is required to have a\n * boundary token of the same length as the parent stream (see {@link\n * #setBoundary(byte[])}).\n *\n *

          Here is an example of usage of this class.
          \n *\n *

          \n *   try {\n *     MultipartStream multipartStream = new MultipartStream(input, boundary);\n *     boolean nextPart = multipartStream.skipPreamble();\n *     OutputStream output;\n *     while(nextPart) {\n *       String header = multipartStream.readHeaders();\n *       // process headers\n *       // create some output stream\n *       multipartStream.readBodyData(output);\n *       nextPart = multipartStream.readBoundary();\n *     }\n *   } catch(MultipartStream.MalformedStreamException e) {\n *     // the stream failed to follow required syntax\n *   } catch(IOException e) {\n *     // a read or write error occurred\n *   }\n * 
          \n *\n * @version $Id: MultipartStream.java 1745065 2016-05-22 14:56:37Z britter $\n */\nclass MultipartStream {\n // ----------------------------------------------------- Manifest constants\n /** The Carriage Return ASCII character value. */\n public static final byte CR = 0x0D;\n /** The Line Feed ASCII character value. */\n public static final byte LF = 0x0A;\n /** The dash (-) ASCII character value. */\n public static final byte DASH = 0x2D;\n /** The maximum length of header-part that will be processed (10 kilobytes = 10240 bytes.). */\n public static final int HEADER_PART_SIZE_MAX = 10240;\n /** The default length of the buffer used for processing a request. */\n protected static final int DEFAULT_BUFSIZE = 4096;\n /** A byte sequence that marks the end of header-part (CRLFCRLF). */\n protected static final byte[] HEADER_SEPARATOR = { CR, LF, CR, LF };\n /** A byte sequence that that follows a delimiter that will be followed by an encapsulation (CRLF). */\n protected static final byte[] FIELD_SEPARATOR = { CR, LF };\n /** A byte sequence that that follows a delimiter of the last encapsulation in the stream (--). */\n protected static final byte[] STREAM_TERMINATOR = { DASH, DASH };\n /** A byte sequence that precedes a boundary (CRLF--). */\n protected static final byte[] BOUNDARY_PREFIX = { CR, LF, DASH, DASH };\n // ----------------------------------------------------------- Data members\n /** The input stream from which data is read. */\n private final InputStream input;\n /** The length of the boundary token plus the leading CRLF--. */\n private int boundaryLength;\n /** The amount of data, in bytes, that must be kept in the buffer in order to detect delimiters reliably. */\n private int keepRegion;\n /** The byte sequence that partitions the stream. */\n private byte[] boundary;\n /** The length of the buffer used for processing the request. */\n private final int bufSize;\n /** The buffer used for processing the request. */\n private final byte[] buffer;\n /** The index of first valid character in the buffer.
          0 <= head < bufSize */\n private int head;\n /** The index of last valid character in the buffer + 1.
          0 <= tail <= bufSize */\n private int tail;\n /** The content encoding to use when reading headers. */\n private String headerEncoding;\n // ----------------------------------------------------------- Constructors\n\n /**\n *

          Constructs a MultipartStream with a custom size buffer.\n *\n *

          Note that the buffer must be at least big enough to contain the\n * boundary string, plus 4 characters for CR/LF and double dash, plus at\n * least one byte of data. Too small a buffer size setting will degrade\n * performance.\n *\n * @param input The InputStream to serve as a data source.\n * @param boundary The token used for dividing the stream into\n * encapsulations.\n * @param bufSize The size of the buffer to be used, in bytes.\n * @throws IllegalArgumentException If the buffer size is too small\n * @since 1.3.1\n */\n public MultipartStream(InputStream input, byte[] boundary, int bufSize) {\n if (boundary == null) {\n throw new IllegalArgumentException(\"boundary may not be null\");\n }\n // We prepend CR/LF to the boundary to chop trailing CR/LF from body-data tokens.\n this.boundaryLength = boundary.length + BOUNDARY_PREFIX.length;\n if (bufSize < this.boundaryLength + 1) {\n throw new IllegalArgumentException(\"The buffer size specified for the MultipartStream is too small\");\n }\n this.input = input;\n this.bufSize = Math.max(bufSize, boundaryLength * 2);\n this.buffer = new byte[this.bufSize];\n this.boundary = new byte[this.boundaryLength];\n this.keepRegion = this.boundary.length;\n System.arraycopy(BOUNDARY_PREFIX, 0, this.boundary, 0, BOUNDARY_PREFIX.length);\n System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length);\n head = 0;\n tail = 0;\n }\n\n /**\n *

          Constructs a MultipartStream with a default size buffer.\n * @param input The InputStream to serve as a data source.\n * @param boundary The token used for dividing the stream into encapsulations.\n * @see #MultipartStream(InputStream, byte[], int)\n */\n MultipartStream(InputStream input, byte[] boundary) {\n this(input, boundary, DEFAULT_BUFSIZE);\n }\n // --------------------------------------------------------- Public methods\n\n /**\n * Retrieves the character encoding used when reading the headers of an\n * individual part. When not specified, or null, the platform default encoding is used.\n * @return The encoding used to read part headers.\n */\n public String getHeaderEncoding() {\n return headerEncoding;\n }\n\n /**\n * Specifies the character encoding to be used when reading the headers of\n * individual parts. When not specified, or null, the platform\n * default encoding is used.\n * @param encoding The encoding used to read part headers.\n */\n public void setHeaderEncoding(String encoding) {\n headerEncoding = encoding;\n }\n\n /**\n * Reads a byte from the buffer, and refills it as necessary.\n * @return The next byte from the input stream.\n * @throws IOException if there is no more data available.\n */\n public byte readByte() throws IOException {\n // Buffer depleted ?\n if (head == tail) {\n head = 0;\n // Refill.\n tail = input.read(buffer, head, bufSize);\n if (tail == -1) {\n // No more data available.\n throw new IOException(\"No more data is available\");\n }\n }\n return buffer[head++];\n }\n\n /**\n * Skips a boundary token, and checks whether more\n * encapsulations are contained in the stream.\n * @return true if there are more encapsulations in this stream; false otherwise.\n * @throws FileUploadException if the stream ends unexpectedly or fails to follow required syntax.\n */\n public boolean readBoundary() throws IOException {\n byte[] marker = new byte[2];\n boolean nextChunk = false;\n head += boundaryLength;\n marker[0] = readByte();\n if (marker[0] == LF) {\n // Work around IE5 Mac bug with input type=image.\n // Because the boundary delimiter, not including the trailing CRLF, \n // must not appear within any file (RFC 2046, section 5.1.1),\n // we know the missing CR is due to a buggy browser rather than a file \n // containing something similar to a boundary.\n return true;\n }\n marker[1] = readByte();\n if (arrayequals(marker, STREAM_TERMINATOR, 2)) {\n nextChunk = false;\n } else if (arrayequals(marker, FIELD_SEPARATOR, 2)) {\n nextChunk = true;\n } else {\n throw new FileUploadException(MalformedStreamException, \"Unexpected characters follow a boundary\");\n }\n return nextChunk;\n }\n\n /**\n *

          Changes the boundary token used for partitioning the stream.\n *

          This method allows single pass processing of nested multipart streams.\n *

          The boundary token of the nested stream is required to be of the same length as the boundary token in parent stream.\n *

          Restoring the parent stream boundary token after processing of a nested stream is left to the application.\n * @param boundary The boundary to be used for parsing of the nested stream.\n * @throws FileUploadException if the boundary has a different length than the one being currently parsed.\n */\n public void setBoundary(byte[] boundary) throws FileUploadException {\n if (boundary.length != boundaryLength - BOUNDARY_PREFIX.length) {\n throw new FileUploadException(IllegalBoundaryException, \"The length of a boundary token can not be changed\");\n }\n System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length);\n }\n\n /**\n *

          Reads the header-part of the current\n * encapsulation.\n *

          Headers are returned verbatim to the input stream, including the\n * trailing CRLF marker. Parsing is left to the application.\n *

          TODO allow limiting maximum header size to protect against abuse.\n *\n * @return The header-part of the current encapsulation.\n * @throws FileUploadException if the stream ends unexpectedly.\n */\n public String readHeaders() throws IOException {\n int i = 0;\n byte b;\n // to support multi-byte characters\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n int size = 0;\n while (i < HEADER_SEPARATOR.length) {\n try {\n b = readByte();\n } catch (IOException e) {\n throw e;\n }\n if (++size > HEADER_PART_SIZE_MAX) {\n String logMEssage = format(\"Header section has more than %s bytes (maybe it is not properly terminated)\", Integer.valueOf(HEADER_PART_SIZE_MAX));\n throw new FileUploadException(MalformedStreamException, logMEssage);\n }\n if (b == HEADER_SEPARATOR[i]) {\n i++;\n } else {\n i = 0;\n }\n baos.write(b);\n }\n String headers = null;\n if (headerEncoding != null) {\n try {\n headers = baos.toString(headerEncoding);\n } catch (UnsupportedEncodingException e) {\n // Fall back to platform default if specified encoding is not supported.\n headers = baos.toString();\n }\n } else {\n headers = baos.toString();\n }\n return headers;\n }\n\n /**\n *

          Reads body-data from the current encapsulation and writes its contents into the output Stream.\n *

          Arbitrary large amounts of data can be processed by this method using a constant size buffer. \n * @param output The Stream to write data into. May be null, in which case this method is equivalent to {@link #discardBodyData()}.\n * @return the amount of data written.\n * @throws FileUploadException if the stream ends unexpectedly.\n * @throws IOException if an i/o error occurs.\n */\n public int readBodyData(OutputStream output) throws IOException {\n final InputStream istream = newInputStream();\n return (int) Streams.copy(istream, output, false);\n }\n\n /**\n * Creates a new {@link ItemInputStream}.\n * @return A new instance of {@link ItemInputStream}.\n */\n ItemInputStream newInputStream() {\n return new ItemInputStream();\n }\n\n /**\n *

          Reads body-data from the current\n * encapsulation and discards it.\n *\n *

          Use this method to skip encapsulations you don't need or don't understand.\n *\n * @return The amount of data discarded.\n * @throws FileUploadException if the stream ends unexpectedly.\n * @throws IOException if an i/o error occurs.\n */\n public int discardBodyData() throws IOException {\n return readBodyData(null);\n }\n\n /**\n * Finds the beginning of the first encapsulation.\n * @return true if an encapsulation was found in the stream.\n *\n * @throws IOException if an i/o error occurs.\n */\n public boolean skipPreamble() throws IOException {\n // First delimiter may be not preceeded with a CRLF.\n System.arraycopy(boundary, 2, boundary, 0, boundary.length - 2);\n boundaryLength = boundary.length - 2;\n try {\n // Discard all data up to the delimiter.\n discardBodyData();\n // Read boundary - if succeeded, the stream contains an encapsulation.\n return readBoundary();\n } catch (FileUploadException e) {\n if (e.getErrorCode() == MalformedStreamException) {\n return false;\n }\n throw e;\n } finally {\n // Restore delimiter.\n System.arraycopy(boundary, 0, boundary, 2, boundary.length - 2);\n boundaryLength = boundary.length;\n boundary[0] = CR;\n boundary[1] = LF;\n }\n }\n\n /**\n * Compares count first bytes in the arrays a and b.\n * @param a The first array to compare.\n * @param b The second array to compare.\n * @param count How many bytes should be compared.\n *\n * @return true if count first bytes in arrays\n * a and b are equal.\n */\n public static boolean arrayequals(byte[] a, byte[] b, int count) {\n for (int i = 0; i < count; i++) {\n if (a[i] != b[i]) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Searches for a byte of specified value in the buffer,\n * starting at the specified position.\n *\n * @param value The value to find.\n * @param pos The starting position for searching.\n *\n * @return The position of byte found, counting from beginning of the\n * buffer, or -1 if not found.\n */\n protected int findByte(byte value, int pos) {\n for (int i = pos; i < tail; i++) {\n if (buffer[i] == value) {\n return i;\n }\n }\n return -1;\n }\n\n /**\n * Searches for the boundary in the buffer\n * region delimited by head and tail.\n *\n * @return The position of the boundary found, counting from the\n * beginning of the buffer, or -1 if not found.\n */\n protected int findSeparator() {\n int first;\n int match = 0;\n int maxpos = tail - boundaryLength;\n for (first = head; first <= maxpos && match != boundaryLength; first++) {\n first = findByte(boundary[0], first);\n if (first == -1 || first > maxpos) {\n return -1;\n }\n for (match = 1; match < boundaryLength; match++) {\n if (buffer[first + match] != boundary[match]) {\n break;\n }\n }\n }\n if (match == boundaryLength) {\n return first - 1;\n }\n return -1;\n }\n\n /** An {@link InputStream} for reading an items contents. */\n public class ItemInputStream extends InputStream implements net.hasor.web.upload.util.Closeable {\n /** The number of bytes, which have been read so far. */\n private long total;\n /** The number of bytes, which must be hold, because they might be a part of the boundary. */\n private int pad;\n /** The current offset in the buffer. */\n private int pos;\n /** Whether the stream is already closed. */\n private boolean closed;\n\n /** Creates a new instance. */\n ItemInputStream() {\n findSeparator();\n }\n\n /** Called for finding the separator. */\n private void findSeparator() {\n pos = MultipartStream.this.findSeparator();\n if (pos == -1) {\n if (tail - head > keepRegion) {\n pad = keepRegion;\n } else {\n pad = tail - head;\n }\n }\n }\n\n /** Returns the number of bytes, which have been read by the stream.\n * @return Number of bytes, which have been read so far.\n */\n public long getBytesRead() {\n return total;\n }\n\n /**\n * Returns the number of bytes, which are currently available, without blocking.\n * @return Number of bytes in the buffer.\n */\n @Override\n public int available() {\n if (pos == -1) {\n return tail - head - pad;\n }\n return pos - head;\n }\n\n /** Offset when converting negative bytes to integers. */\n private static final int BYTE_POSITIVE_OFFSET = 256;\n\n /**\n * Returns the next byte in the stream.\n * @return The next byte in the stream, as a non-negative integer, or -1 for EOF.\n * @throws IOException An I/O error occurred.\n */\n @Override\n public int read() throws IOException {\n if (closed) {\n throw new FileUploadException(ItemSkippedException);\n }\n if (available() == 0 && makeAvailable() == 0) {\n return -1;\n }\n ++total;\n int b = buffer[head++];\n if (b >= 0) {\n return b;\n }\n return b + BYTE_POSITIVE_OFFSET;\n }\n\n /**\n * Reads bytes into the given buffer.\n * @param b The destination buffer, where to write to.\n * @param off Offset of the first byte in the buffer.\n * @param len Maximum number of bytes to read.\n * @return Number of bytes, which have been actually read, or -1 for EOF.\n * @throws IOException An I/O error occurred.\n */\n @Override\n public int read(byte[] b, int off, int len) throws IOException {\n if (closed) {\n throw new FileUploadException(ItemSkippedException);\n }\n if (len == 0) {\n return 0;\n }\n int res = available();\n if (res == 0) {\n res = makeAvailable();\n if (res == 0) {\n return -1;\n }\n }\n res = Math.min(res, len);\n System.arraycopy(buffer, head, b, off, res);\n head += res;\n total += res;\n return res;\n }\n\n /**\n * Closes the input stream.\n * @throws IOException An I/O error occurred.\n */\n @Override\n public void close() throws IOException {\n close(false);\n }\n\n /**\n * Closes the input stream.\n * @param pCloseUnderlying Whether to close the underlying stream (hard close)\n * @throws IOException An I/O error occurred.\n */\n public void close(boolean pCloseUnderlying) throws IOException {\n if (closed) {\n return;\n }\n if (pCloseUnderlying) {\n closed = true;\n input.close();\n } else {\n for (; ; ) {\n int av = available();\n if (av == 0) {\n av = makeAvailable();\n if (av == 0) {\n break;\n }\n }\n skip(av);\n }\n }\n closed = true;\n }\n\n /**\n * Skips the given number of bytes.\n * @param bytes Number of bytes to skip.\n * @return The number of bytes, which have actually been skipped.\n * @throws IOException An I/O error occurred.\n */\n @Override\n public long skip(long bytes) throws IOException {\n if (closed) {\n throw new FileUploadException(ItemSkippedException);\n }\n int av = available();\n if (av == 0) {\n av = makeAvailable();\n if (av == 0) {\n return 0;\n }\n }\n long res = Math.min(av, bytes);\n head += res;\n return res;\n }\n\n /**\n * Attempts to read more data.\n * @return Number of available bytes\n * @throws IOException An I/O error occurred.\n */\n private int makeAvailable() throws IOException {\n if (pos != -1) {\n return 0;\n }\n // Move the data to the beginning of the buffer.\n total += tail - head - pad;\n System.arraycopy(buffer, tail - pad, buffer, 0, pad);\n // Refill buffer with new data.\n head = 0;\n tail = pad;\n for (; ; ) {\n int bytesRead = input.read(buffer, tail, bufSize - tail);\n if (bytesRead == -1) {\n // The last pad amount is left in the buffer. Boundary can't be in there so signal an error condition.\n final String msg = \"Stream ended unexpectedly\";\n throw new FileUploadException(MalformedStreamException, msg);\n }\n tail += bytesRead;\n findSeparator();\n int av = available();\n if (av > 0 || pos != -1) {\n return av;\n }\n }\n }\n\n /**\n * Returns, whether the stream is closed.\n * @return True, if the stream is closed, otherwise false.\n */\n public boolean isClosed() {\n return closed;\n }\n }\n}", "file_name": "MultipartStream.java", "human_label": "Given two arrays with the given length count,return true if the array a is equal to array b,otherwise return false.", "level": "self_contained", "lineno": "361", "name": "arrayequals", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.web.upload", "project": "hasor-master" }, { "_id": "636767861a6d9265ec018440", "all_context": "{ \"class_level\" : \"import java.util.ArrayList;\\nimport java.util.List;\\nNameAbbreviator DEFAULT;\\nint count;\\nint charCount;\\nchar ellipsis;\\nPatternAbbreviatorFragment[] fragments;\\ngetAbbreviator(String pattern);\\ngetDefaultAbbreviator();\\nNOPAbbreviator();\\nMaxElementAbbreviator(int count);\\nDropElementAbbreviator(int count);\\nPatternAbbreviatorFragment(int charCount,char ellipsis);\\nabbreviate(StringBuffer buf,int startPos);\\nPatternAbbreviator(List fragments);\\nabbreviate(int nameStart,StringBuffer buf);\\n\", \"repo_level\" : \"\" }", "class_name": "NameAbbreviator$DropElementAbbreviator", "code": "public void abbreviate(final int nameStart,final StringBuffer buf){\n int i=count;\n for (int pos=buf.indexOf(\".\",nameStart); pos != -1; pos=buf.indexOf(\".\",pos + 1)) {\n if (--i == 0) {\n buf.delete(nameStart,pos + 1);\n break;\n }\n }\n}\n", "docstring": "/** \n * Abbreviate name.\n * @param buf buffer to append abbreviation.\n * @param nameStart start of name to abbreviate.\n */\n", "end_lineno": "238", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.log4j.pattern;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n\n/**\n * NameAbbreviator generates abbreviated logger and class names.\n *\n */\npublic abstract class NameAbbreviator {\n /**\n * Default (no abbreviation) abbreviator.\n */\n private static final NameAbbreviator DEFAULT = new NOPAbbreviator();\n\n /**\n * Gets an abbreviator.\n *\n * For example, \"%logger{2}\" will output only 2 elements of the logger name,\n * %logger{-2} will drop 2 elements from the logger name,\n * \"%logger{1.}\" will output only the first character of the non-final elements in the name,\n * \"%logger{1~.2~} will output the first character of the first element, two characters of\n * the second and subsequent elements and will use a tilde to indicate abbreviated characters.\n *\n * @param pattern abbreviation pattern.\n * @return abbreviator, will not be null.\n */\n public static NameAbbreviator getAbbreviator(final String pattern) {\n if (pattern.length() > 0) {\n // if pattern is just spaces and numbers then\n // use MaxElementAbbreviator\n String trimmed = pattern.trim();\n\n if (trimmed.length() == 0) {\n return DEFAULT;\n }\n\n int i = 0;\n if (trimmed.length() > 0) {\n if (trimmed.charAt(0) == '-') {\n i++;\n }\n for (;\n (i < trimmed.length()) &&\n (trimmed.charAt(i) >= '0') &&\n (trimmed.charAt(i) <= '9');\n i++) {\n }\n }\n\n\n //\n // if all blanks and digits\n //\n if (i == trimmed.length()) {\n int elements = Integer.parseInt(trimmed);\n if (elements >= 0) {\n return new MaxElementAbbreviator(elements);\n } else {\n return new DropElementAbbreviator(-elements);\n }\n }\n\n ArrayList fragments = new ArrayList(5);\n char ellipsis;\n int charCount;\n int pos = 0;\n\n while ((pos < trimmed.length()) && (pos >= 0)) {\n int ellipsisPos = pos;\n\n if (trimmed.charAt(pos) == '*') {\n charCount = Integer.MAX_VALUE;\n ellipsisPos++;\n } else {\n if ((trimmed.charAt(pos) >= '0') && (trimmed.charAt(pos) <= '9')) {\n charCount = trimmed.charAt(pos) - '0';\n ellipsisPos++;\n } else {\n charCount = 0;\n }\n }\n\n ellipsis = '\\0';\n\n if (ellipsisPos < trimmed.length()) {\n ellipsis = trimmed.charAt(ellipsisPos);\n\n if (ellipsis == '.') {\n ellipsis = '\\0';\n }\n }\n\n fragments.add(new PatternAbbreviatorFragment(charCount, ellipsis));\n pos = trimmed.indexOf(\".\", pos);\n\n if (pos == -1) {\n break;\n }\n\n pos++;\n }\n\n return new PatternAbbreviator(fragments);\n }\n\n //\n // no matching abbreviation, return defaultAbbreviator\n //\n return DEFAULT;\n }\n\n /**\n * Gets default abbreviator.\n *\n * @return default abbreviator.\n */\n public static NameAbbreviator getDefaultAbbreviator() {\n return DEFAULT;\n }\n\n /**\n * Abbreviates a name in a StringBuffer.\n *\n * @param nameStart starting position of name in buf.\n * @param buf buffer, may not be null.\n */\n public abstract void abbreviate(final int nameStart, final StringBuffer buf);\n\n /**\n * Abbreviator that simply appends full name to buffer.\n */\n private static class NOPAbbreviator extends NameAbbreviator {\n /**\n * Constructor.\n */\n public NOPAbbreviator() {\n }\n\n /**\n * {@inheritDoc}\n */\n public void abbreviate(final int nameStart, final StringBuffer buf) {\n }\n }\n\n /**\n * Abbreviator that drops starting path elements.\n */\n private static class MaxElementAbbreviator extends NameAbbreviator {\n /**\n * Maximum number of path elements to output.\n */\n private final int count;\n\n /**\n * Create new instance.\n * @param count maximum number of path elements to output.\n */\n public MaxElementAbbreviator(final int count) {\n this.count = count;\n }\n\n /**\n * Abbreviate name.\n * @param buf buffer to append abbreviation.\n * @param nameStart start of name to abbreviate.\n */\n public void abbreviate(final int nameStart, final StringBuffer buf) {\n // We substract 1 from 'len' when assigning to 'end' to avoid out of\n // bounds exception in return r.substring(end+1, len). This can happen if\n // precision is 1 and the category name ends with a dot.\n int end = buf.length() - 1;\n\n String bufString = buf.toString();\n for (int i = count; i > 0; i--) {\n end = bufString.lastIndexOf(\".\", end - 1);\n\n if ((end == -1) || (end < nameStart)) {\n return;\n }\n }\n\n buf.delete(nameStart, end + 1);\n }\n }\n\n /**\n * Abbreviator that drops starting path elements.\n */\n private static class DropElementAbbreviator extends NameAbbreviator {\n /**\n * Maximum number of path elements to output.\n */\n private final int count;\n\n /**\n * Create new instance.\n * @param count maximum number of path elements to output.\n */\n public DropElementAbbreviator(final int count) {\n this.count = count;\n }\n\n /**\n * Abbreviate name.\n * @param buf buffer to append abbreviation.\n * @param nameStart start of name to abbreviate.\n */\n public void abbreviate(final int nameStart, final StringBuffer buf) {\n int i = count;\n for(int pos = buf.indexOf(\".\", nameStart);\n pos != -1;\n pos = buf.indexOf(\".\", pos + 1)) {\n if(--i == 0) {\n buf.delete(nameStart, pos + 1);\n break;\n }\n }\n }\n }\n\n\n /**\n * Fragment of an pattern abbreviator.\n *\n */\n private static class PatternAbbreviatorFragment {\n /**\n * Count of initial characters of element to output.\n */\n private final int charCount;\n\n /**\n * Character used to represent dropped characters.\n * '\\0' indicates no representation of dropped characters.\n */\n private final char ellipsis;\n\n /**\n * Creates a PatternAbbreviatorFragment.\n * @param charCount number of initial characters to preserve.\n * @param ellipsis character to represent elimination of characters,\n * '\\0' if no ellipsis is desired.\n */\n public PatternAbbreviatorFragment(\n final int charCount, final char ellipsis) {\n this.charCount = charCount;\n this.ellipsis = ellipsis;\n }\n\n /**\n * Abbreviate element of name.\n * @param buf buffer to receive element.\n * @param startPos starting index of name element.\n * @return starting index of next element.\n */\n public int abbreviate(final StringBuffer buf, final int startPos) {\n int nextDot = buf.toString().indexOf(\".\", startPos);\n\n if (nextDot != -1) {\n if ((nextDot - startPos) > charCount) {\n buf.delete(startPos + charCount, nextDot);\n nextDot = startPos + charCount;\n\n if (ellipsis != '\\0') {\n buf.insert(nextDot, ellipsis);\n nextDot++;\n }\n }\n\n nextDot++;\n }\n\n return nextDot;\n }\n }\n\n /**\n * Pattern abbreviator.\n *\n *\n */\n private static class PatternAbbreviator extends NameAbbreviator {\n /**\n * Element abbreviation patterns.\n */\n private final PatternAbbreviatorFragment[] fragments;\n\n /**\n * Create PatternAbbreviator.\n *\n * @param fragments element abbreviation patterns.\n */\n public PatternAbbreviator(List fragments) {\n if (fragments.size() == 0) {\n throw new IllegalArgumentException(\n \"fragments must have at least one element\");\n }\n\n this.fragments = new PatternAbbreviatorFragment[fragments.size()];\n fragments.toArray(this.fragments);\n }\n\n /**\n * Abbreviate name.\n * @param buf buffer that abbreviated name is appended.\n * @param nameStart start of name.\n */\n public void abbreviate(final int nameStart, final StringBuffer buf) {\n //\n // all non-terminal patterns are executed once\n //\n int pos = nameStart;\n\n for (int i = 0; (i < (fragments.length - 1)) && (pos < buf.length());\n i++) {\n pos = fragments[i].abbreviate(buf, pos);\n }\n\n //\n // last pattern in executed repeatedly\n //\n PatternAbbreviatorFragment terminalFragment =\n fragments[fragments.length - 1];\n\n while ((pos < buf.length()) && (pos >= 0)) {\n pos = terminalFragment.abbreviate(buf, pos);\n }\n }\n }\n}\n", "file_name": "NameAbbreviator.java", "human_label": "The given name can be split into several substrings by \".\",and abbreviate the name in the buf by deleting the first count substrings. ", "level": "class_runnable", "lineno": "223", "name": "abbreviate", "oracle_context": "{ \"apis\" : \"[indexOf, delete]\", \"classes\" : \"[]\", \"vars\" : \"[count]\" }", "package": "org.apache.log4j.pattern", "project": "logging-log4j1-main" }, { "_id": "6367667d1a6d9265ec01741d", "all_context": "{ \"class_level\" : \"import java.lang.ref.Reference;\\nimport java.lang.ref.WeakReference;\\nimport java.lang.reflect.Array;\\nimport java.lang.reflect.GenericArrayType;\\nimport java.lang.reflect.ParameterizedType;\\nimport java.lang.reflect.Type;\\nimport java.lang.reflect.TypeVariable;\\nimport java.util.Collections;\\nimport java.util.HashMap;\\nimport java.util.Map;\\nimport java.util.WeakHashMap;\\nMap,Reference,Type>>> typeVariableCache;\\nboolean cacheEnabled;\\nTypeResolver();\\nUnknown();\\ndisableCache();\\nresolveArgument(Class initialType,Class targetType);\\nresolveArgument(Type genericType,Class targetType);\\nresolveArguments(Class initialType,Class targetType);\\nresolveArguments(Type genericType,Class targetType);\\nresolveGenericType(Type initialType,Class targetType);\\nresolveClass(Type genericType,Class targetType);\\ngetTypeVariableMap(Class targetType);\\nbuildTypeVariableMap(Type[] types,Map map);\\nbuildTypeVariableMap(ParameterizedType type,Map typeVariableMap);\\nresolveBound(TypeVariable typeVariable);\\nenableCache();\\n\", \"repo_level\" : \"\" }", "class_name": "TypeResolver", "code": "public static Type resolveBound(TypeVariable typeVariable){\n Type[] bounds=typeVariable.getBounds();\n if (bounds.length == 0) return Unknown.class;\n Type bound=bounds[0];\n if (bound instanceof TypeVariable) bound=resolveBound((TypeVariable)bound);\n return bound == Object.class ? Unknown.class : bound;\n}\n", "docstring": "/** \n * Resolves the first bound for the {@code typeVariable}, returning {@code Unknown.class} if nonecan be resolved.\n */\n", "end_lineno": "314", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n/**\n * Copyright 2002-2011 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This class is from https://github.com/jhalterman/typetools\n */\npackage org.atmosphere.config.managed;\n\nimport java.lang.ref.Reference;\nimport java.lang.ref.WeakReference;\nimport java.lang.reflect.Array;\nimport java.lang.reflect.GenericArrayType;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.lang.reflect.TypeVariable;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.WeakHashMap;\n\n/**\n * Enhanced type resolution utilities. Based on org.springframework.core.GenericTypeResolver.\n *\n * @author Jonathan Halterman\n */\npublic final class TypeResolver {\n private TypeResolver() {\n }\n\n /** An unknown type. */\n public static final class Unknown {\n private Unknown() {\n }\n }\n\n /** Cache of type variable/argument pairs */\n private static final Map, Reference, Type>>> typeVariableCache = Collections.synchronizedMap(new WeakHashMap<>());\n private static boolean cacheEnabled = true;\n\n /**\n * Enables the internal caching of TypeVariables.\n */\n public static void enableCache() {\n cacheEnabled = true;\n }\n\n /**\n * Disables the internal caching of TypeVariables.\n */\n public static void disableCache() {\n typeVariableCache.clear();\n cacheEnabled = false;\n }\n\n /**\n * Returns the raw class representing the type argument for the {@code targetType} resolved\n * upwards from the {@code initialType}. If no arguments can be resolved then\n * {@code Unknown.class} is returned.\n *\n * @param initialType to resolve upwards from\n * @param targetType to resolve arguments for\n * @return type argument for {@code initialType} else {@code null} if no type arguments are\n * declared\n * @throws IllegalArgumentException if more or less than one type argument is resolved for the\n * give types\n */\n public static Class resolveArgument(Class initialType, Class targetType) {\n return resolveArgument(resolveGenericType(initialType, targetType), initialType);\n }\n\n /**\n * Resolves the type argument for the {@code genericType} using type variable information from the\n * {@code sourceType}. If {@code genericType} is an instance of class, then {@code genericType} is\n * returned. If no arguments can be resolved then {@code Unknown.class} is returned.\n *\n * @param genericType to resolve upwards from\n * @param targetType to resolve arguments for\n * @return type argument for {@code initialType} else {@code null} if no type arguments are\n * declared\n * @throws IllegalArgumentException if more or less than one type argument is resolved for the\n * give types\n */\n public static Class resolveArgument(Type genericType, Class targetType) {\n Class[] arguments = resolveArguments(genericType, targetType);\n if (arguments == null)\n return Unknown.class;\n\n if (arguments.length != 1)\n throw new IllegalArgumentException(\"Expected 1 type argument on generic type \"\n + targetType.getName() + \" but found \" + arguments.length);\n\n return arguments[0];\n }\n\n /**\n * Returns an array of raw classes representing type arguments for the {@code targetType} resolved\n * upwards from the {@code initialType}. Arguments for {@code targetType} that cannot be resolved\n * to a Class are returned as {@code Unknown.class}. If no arguments can be resolved then\n * {@code null} is returned.\n *\n * @param initialType to resolve upwards from\n * @param targetType to resolve arguments for\n * @return array of raw classes representing type arguments for {@code initialType} else\n * {@code null} if no type arguments are declared\n */\n public static Class[] resolveArguments(Class initialType,\n Class targetType) {\n return resolveArguments(resolveGenericType(initialType, targetType), initialType);\n }\n\n /**\n * Resolves the arguments for the {@code genericType} using the type variable information for the\n * {@code targetType}. Returns {@code null} if {@code genericType} is not parameterized or if\n * arguments cannot be resolved.\n */\n public static Class[] resolveArguments(Type genericType, Class targetType) {\n Class[] result = null;\n\n if (genericType instanceof ParameterizedType) {\n ParameterizedType paramType = (ParameterizedType) genericType;\n Type[] arguments = paramType.getActualTypeArguments();\n result = new Class[arguments.length];\n for (int i = 0; i < arguments.length; i++)\n result[i] = resolveClass(arguments[i], targetType);\n } else if (genericType instanceof TypeVariable) {\n result = new Class[1];\n result[0] = resolveClass(genericType, targetType);\n }\n\n return result;\n }\n\n /**\n * Resolves the generic Type for the {@code targetType} by walking the type hierarchy upwards from\n * the {@code initialType}.\n */\n public static Type resolveGenericType(Type initialType, Class targetType) {\n Class rawType;\n if (initialType instanceof ParameterizedType)\n rawType = (Class) ((ParameterizedType) initialType).getRawType();\n else\n rawType = (Class) initialType;\n\n if (targetType.equals(rawType))\n return initialType;\n\n Type result;\n if (targetType.isInterface()) {\n for (Type superInterface : rawType.getGenericInterfaces())\n if (superInterface != null && !superInterface.equals(Object.class))\n if ((result = resolveGenericType(superInterface, targetType)) != null)\n return result;\n }\n\n Type superType = rawType.getGenericSuperclass();\n if (superType != null && !superType.equals(Object.class))\n if ((result = resolveGenericType(superType, targetType)) != null)\n return result;\n\n return null;\n }\n\n /**\n * Resolves the raw class for the given {@code genericType}, using the type variable information\n * from the {@code targetType}.\n */\n public static Class resolveClass(Type genericType, Class targetType) {\n if (genericType instanceof Class) {\n return (Class) genericType;\n } else if (genericType instanceof ParameterizedType) {\n return resolveClass(((ParameterizedType) genericType).getRawType(), targetType);\n } else if (genericType instanceof GenericArrayType) {\n GenericArrayType arrayType = (GenericArrayType) genericType;\n Class compoment = resolveClass(arrayType.getGenericComponentType(), targetType);\n return Array.newInstance(compoment, 0).getClass();\n } else if (genericType instanceof TypeVariable) {\n TypeVariable variable = (TypeVariable) genericType;\n genericType = getTypeVariableMap(targetType).get(variable);\n genericType = genericType == null ? resolveBound(variable) : resolveClass(genericType,\n targetType);\n }\n\n return genericType instanceof Class ? (Class) genericType : Unknown.class;\n }\n\n private static Map, Type> getTypeVariableMap(final Class targetType) {\n Reference, Type>> ref = typeVariableCache.get(targetType);\n Map, Type> map = ref != null ? ref.get() : null;\n\n if (map == null) {\n map = new HashMap<>();\n\n // Populate interfaces\n buildTypeVariableMap(targetType.getGenericInterfaces(), map);\n\n // Populate super classes and interfaces\n Type genericType = targetType.getGenericSuperclass();\n Class type = targetType.getSuperclass();\n while (type != null && !Object.class.equals(type)) {\n if (genericType instanceof ParameterizedType)\n buildTypeVariableMap((ParameterizedType) genericType, map);\n buildTypeVariableMap(type.getGenericInterfaces(), map);\n\n genericType = type.getGenericSuperclass();\n type = type.getSuperclass();\n }\n\n // Populate enclosing classes\n type = targetType;\n while (type.isMemberClass()) {\n genericType = type.getGenericSuperclass();\n if (genericType instanceof ParameterizedType)\n buildTypeVariableMap((ParameterizedType) genericType, map);\n\n type = type.getEnclosingClass();\n }\n\n if (cacheEnabled)\n typeVariableCache.put(targetType, new WeakReference<>(map));\n }\n\n return map;\n }\n\n /**\n * Populates the {@code map} with with variable/argument pairs for the given {@code types}.\n */\n static void buildTypeVariableMap(final Type[] types, final Map, Type> map) {\n for (Type type : types) {\n if (type instanceof ParameterizedType) {\n ParameterizedType parameterizedType = (ParameterizedType) type;\n buildTypeVariableMap(parameterizedType, map);\n Type rawType = parameterizedType.getRawType();\n if (rawType instanceof Class)\n buildTypeVariableMap(((Class) rawType).getGenericInterfaces(), map);\n } else if (type instanceof Class) {\n buildTypeVariableMap(((Class) type).getGenericInterfaces(), map);\n }\n }\n }\n\n /**\n * Populates the {@code typeVariableMap} with type arguments and parameters for the given\n * {@code type}.\n */\n private static void buildTypeVariableMap(ParameterizedType type,\n Map, Type> typeVariableMap) {\n if (type.getRawType() instanceof Class) {\n TypeVariable[] typeVariables = ((Class) type.getRawType()).getTypeParameters();\n Type[] typeArguments = type.getActualTypeArguments();\n\n for (int i = 0; i < typeArguments.length; i++) {\n TypeVariable variable = typeVariables[i];\n Type typeArgument = typeArguments[i];\n\n if (typeArgument instanceof Class) {\n typeVariableMap.put(variable, typeArgument);\n } else if (typeArgument instanceof GenericArrayType) {\n typeVariableMap.put(variable, typeArgument);\n } else if (typeArgument instanceof ParameterizedType) {\n typeVariableMap.put(variable, typeArgument);\n } else if (typeArgument instanceof TypeVariable) {\n TypeVariable typeVariableArgument = (TypeVariable) typeArgument;\n Type resolvedType = typeVariableMap.get(typeVariableArgument);\n if (resolvedType == null)\n resolvedType = resolveBound(typeVariableArgument);\n typeVariableMap.put(variable, resolvedType);\n }\n }\n }\n }\n\n /**\n * Resolves the first bound for the {@code typeVariable}, returning {@code Unknown.class} if none\n * can be resolved.\n */\n public static Type resolveBound(TypeVariable typeVariable) {\n Type[] bounds = typeVariable.getBounds();\n if (bounds.length == 0)\n return Unknown.class;\n\n Type bound = bounds[0];\n if (bound instanceof TypeVariable)\n bound = resolveBound((TypeVariable) bound);\n\n return bound == Object.class ? Unknown.class : bound;\n }\n}\n", "file_name": "TypeResolver.java", "human_label": "Resolve the class of the first bound for the typeVariable recursively,return Unknown.class if it can't be resolved.Otherwise return the bound.", "level": "slib_runnable", "lineno": "300", "name": "resolveBound", "oracle_context": "{ \"apis\" : \"[getBounds, Unknown]\", \"classes\" : \"[Type[], Type]\", \"vars\" : \"[length]\" }", "package": "org.atmosphere.config.managed", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "6367675f1a6d9265ec0180cf", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.alg.connectivity.*;\\nimport org.jgrapht.graph.builder.*;\\nimport java.util.*;\\nimport java.util.Map.*;\\nGraph graph;\\nGraph chordalGraph;\\nSet fillEdges;\\nLinkedList meo;\\nList generators;\\nSet> separators;\\nSet> atoms;\\nMap,Integer> fullComponentCount;\\nCliqueMinimalSeparatorDecomposition(Graph g);\\ngetMaxLabelVertex(Map vertexLabels);\\naddToReach(Integer k,V v,HashMap r);\\ncomputeAtoms();\\nisClique(Graph graph,Set vertices);\\ncopyAsSimpleGraph(Graph graph);\\nisChordal();\\ngetFillEdges();\\ngetMinimalTriangulation();\\ngetGenerators();\\ngetMeo();\\ngetFullComponentCount();\\ngetAtoms();\\ngetSeparators();\\ngetGraph();\\ncomputeMinimalTriangulation();\\n\", \"repo_level\" : \"\" }", "class_name": "CliqueMinimalSeparatorDecomposition", "code": "private static boolean isClique(Graph graph,Set vertices){\n for ( V v1 : vertices) {\n for ( V v2 : vertices) {\n if (!v1.equals(v2) && (graph.getEdge(v1,v2) == null)) {\n return false;\n }\n }\n }\n return true;\n}\n", "docstring": "/** \n * Check whether the subgraph of graph induced by the given vertices is complete, i.e. a clique.\n * @param graph the graph.\n * @param vertices the vertices to induce the subgraph from.\n * @return true if the induced subgraph is a clique.\n */\n", "end_lineno": "309", "file_content": "/*\n * (C) Copyright 2015-2021, by Florian Buenzli and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.clique;\n\nimport org.jgrapht.*;\nimport org.jgrapht.alg.connectivity.*;\nimport org.jgrapht.graph.builder.*;\n\nimport java.util.*;\nimport java.util.Map.*;\n\n/**\n * Clique Minimal Separator Decomposition using MCS-M+ and Atoms algorithm as described in Berry et\n * al. An Introduction to Clique Minimal Separator Decomposition (2010), DOI:10.3390/a3020197,\n * http://www.mdpi.com/1999-4893/3/2/197\n *\n *

          \n * The Clique Minimal Separator (CMS) Decomposition is a procedure that splits a graph into a set of\n * subgraphs separated by minimal clique separators, adding the separating clique to each component\n * produced by the separation. At the end we have a set of atoms. The CMS decomposition is unique\n * and yields the set of the atoms independent of the order of the decomposition.\n *\n * @param the graph vertex type\n * @param the graph edge type\n *\n * @author Florian Buenzli (fbuenzli@student.ethz.ch)\n * @author Thomas Tschager (thomas.tschager@inf.ethz.ch)\n * @author Tomas Hruz (tomas.hruz@inf.ethz.ch)\n * @author Philipp Hoppen\n */\npublic class CliqueMinimalSeparatorDecomposition\n{\n /**\n * Source graph to operate on\n */\n private Graph graph;\n\n /**\n * Minimal triangulation of graph\n */\n private Graph chordalGraph;\n\n /**\n * Fill edges\n */\n private Set fillEdges;\n\n /**\n * Minimal elimination ordering on the vertices of graph\n */\n private LinkedList meo;\n\n /**\n * List of all vertices that generate a minimal separator of \n * chordGraph\n */\n private List generators;\n\n /**\n * Set of clique minimal separators\n */\n private Set> separators;\n\n /**\n * The atoms generated by the decomposition\n */\n private Set> atoms;\n\n /**\n * Map for each separator how many components it produces.\n */\n private Map, Integer> fullComponentCount = new HashMap<>();\n\n /**\n * Setup a clique minimal separator decomposition on undirected graph \n * g. Loops and multiple (parallel) edges are removed, i.e. the graph is transformed to a\n * simple graph.\n *\n * @param g The graph to decompose.\n */\n public CliqueMinimalSeparatorDecomposition(Graph g)\n {\n this.graph = GraphTests.requireUndirected(g);\n this.fillEdges = new HashSet<>();\n }\n\n /**\n * Compute the minimal triangulation of the graph. Implementation of Algorithm MCS-M+ as\n * described in Berry et al. (2010), DOI:10.3390/a3020197\n * http://www.mdpi.com/1999-4893/3/2/197\n */\n private void computeMinimalTriangulation()\n {\n // initialize chordGraph with same vertices as graph\n chordalGraph = GraphTypeBuilder\n . undirected().edgeSupplier(graph.getEdgeSupplier())\n .vertexSupplier(graph.getVertexSupplier()).allowingMultipleEdges(false)\n .allowingSelfLoops(false).buildGraph();\n\n for (V v : graph.vertexSet()) {\n chordalGraph.addVertex(v);\n }\n\n // initialize g' as subgraph of graph (same vertices and edges)\n final Graph gprime = copyAsSimpleGraph(graph);\n int s = -1;\n generators = new ArrayList<>();\n meo = new LinkedList<>();\n\n final Map vertexLabels = new HashMap<>();\n for (V v : gprime.vertexSet()) {\n vertexLabels.put(v, 0);\n }\n for (int i = 1, n = graph.vertexSet().size(); i <= n; i++) {\n V v = getMaxLabelVertex(vertexLabels);\n LinkedList neighborsY = new LinkedList<>(Graphs.neighborListOf(gprime, v));\n\n if (vertexLabels.get(v) <= s) {\n generators.add(v);\n }\n\n s = vertexLabels.get(v);\n\n // Mark x reached and all other vertices of gprime unreached\n HashSet reached = new HashSet<>();\n reached.add(v);\n\n // mark neighborhood of x reached and add to reach(label(y))\n HashMap> reach = new HashMap<>();\n\n // mark y reached and add y to reach\n for (V y : neighborsY) {\n reached.add(y);\n addToReach(vertexLabels.get(y), y, reach);\n }\n\n for (int j = 0; j < graph.vertexSet().size(); j++) {\n if (!reach.containsKey(j)) {\n continue;\n }\n while (reach.get(j).size() > 0) {\n // remove a vertex y from reach(j)\n V y = reach.get(j).iterator().next();\n reach.get(j).remove(y);\n\n for (V z : Graphs.neighborListOf(gprime, y)) {\n if (!reached.contains(z)) {\n reached.add(z);\n if (vertexLabels.get(z) > j) {\n neighborsY.add(z);\n E fillEdge = graph.getEdgeSupplier().get();\n fillEdges.add(fillEdge);\n addToReach(vertexLabels.get(z), z, reach);\n } else {\n addToReach(j, z, reach);\n }\n }\n }\n }\n }\n\n for (V y : neighborsY) {\n chordalGraph.addEdge(v, y);\n vertexLabels.put(y, vertexLabels.get(y) + 1);\n }\n\n meo.addLast(v);\n gprime.removeVertex(v);\n vertexLabels.remove(v);\n }\n }\n\n /**\n * Get the vertex with the maximal label.\n *\n * @param vertexLabels Map that gives a label for each vertex.\n *\n * @return Vertex with the maximal label.\n */\n private V getMaxLabelVertex(Map vertexLabels)\n {\n Iterator> iterator = vertexLabels.entrySet().iterator();\n Entry max = iterator.next();\n while (iterator.hasNext()) {\n Entry e = iterator.next();\n if (e.getValue() > max.getValue()) {\n max = e;\n }\n }\n return max.getKey();\n }\n\n /**\n * Add a vertex to reach.\n *\n * @param k vertex' label\n * @param v the vertex\n * @param r the reach structure.\n */\n private void addToReach(Integer k, V v, HashMap> r)\n {\n if (r.containsKey(k)) {\n r.get(k).add(v);\n } else {\n HashSet set = new HashSet<>();\n set.add(v);\n r.put(k, set);\n }\n }\n\n /**\n * Compute the unique decomposition of the input graph $G$ (atoms of $G$). Implementation of\n * algorithm Atoms as described in Berry et al. (2010), DOI:10.3390/a3020197,\n * http://www.mdpi.com/1999-4893/3/2/197\n */\n private void computeAtoms()\n {\n if (chordalGraph == null) {\n computeMinimalTriangulation();\n }\n\n separators = new HashSet<>();\n\n // initialize g' as subgraph of graph (same vertices and edges)\n Graph gprime = copyAsSimpleGraph(graph);\n\n // initialize h' as subgraph of chordalGraph (same vertices and edges)\n Graph hprime = copyAsSimpleGraph(chordalGraph);\n\n atoms = new HashSet<>();\n\n Iterator iterator = meo.descendingIterator();\n while (iterator.hasNext()) {\n V v = iterator.next();\n if (generators.contains(v)) {\n Set separator = new HashSet<>(Graphs.neighborListOf(hprime, v));\n\n if (isClique(graph, separator)) {\n if (separator.size() > 0) {\n if (separators.contains(separator)) {\n fullComponentCount\n .put(separator, fullComponentCount.get(separator) + 1);\n } else {\n fullComponentCount.put(separator, 2);\n separators.add(separator);\n }\n }\n Graph tmpGraph = copyAsSimpleGraph(gprime);\n\n tmpGraph.removeAllVertices(separator);\n ConnectivityInspector con = new ConnectivityInspector<>(tmpGraph);\n if (con.isConnected()) {\n throw new RuntimeException(\"separator did not separate the graph\");\n }\n for (Set component : con.connectedSets()) {\n if (component.contains(v)) {\n gprime.removeAllVertices(component);\n component.addAll(separator);\n atoms.add(new HashSet<>(component));\n assert (component.size() > 0);\n break;\n }\n }\n }\n }\n\n hprime.removeVertex(v);\n }\n\n if (gprime.vertexSet().size() > 0) {\n atoms.add(new HashSet<>(gprime.vertexSet()));\n }\n }\n\n /**\n * Check whether the subgraph of graph induced by the given vertices\n * is complete, i.e. a clique.\n *\n * @param graph the graph.\n * @param vertices the vertices to induce the subgraph from.\n *\n * @return true if the induced subgraph is a clique.\n */\n private static boolean isClique(Graph graph, Set vertices)\n {\n for (V v1 : vertices) {\n for (V v2 : vertices) {\n if (!v1.equals(v2) && (graph.getEdge(v1, v2) == null)) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Create a copy of a graph for internal use.\n *\n * @param graph the graph to copy.\n *\n * @return A copy of the graph projected to a SimpleGraph.\n */\n private static Graph copyAsSimpleGraph(Graph graph)\n {\n Graph copy = GraphTypeBuilder\n . undirected().edgeSupplier(graph.getEdgeSupplier())\n .vertexSupplier(graph.getVertexSupplier()).allowingMultipleEdges(false)\n .allowingSelfLoops(false).buildGraph();\n\n if (graph.getType().isSimple()) {\n Graphs.addGraph(copy, graph);\n } else {\n // project graph to SimpleGraph\n Graphs.addAllVertices(copy, graph.vertexSet());\n for (E e : graph.edgeSet()) {\n V v1 = graph.getEdgeSource(e);\n V v2 = graph.getEdgeTarget(e);\n if (!v1.equals(v2) && !copy.containsEdge(e)) {\n copy.addEdge(v1, v2);\n }\n }\n }\n return copy;\n }\n\n /**\n * Check if the graph is chordal.\n *\n * @return true if the graph is chordal, false otherwise.\n */\n public boolean isChordal()\n {\n if (chordalGraph == null) {\n computeMinimalTriangulation();\n }\n\n return (chordalGraph.edgeSet().size() == graph.edgeSet().size());\n }\n\n /**\n * Get the fill edges generated by the triangulation.\n *\n * @return Set of fill edges.\n */\n public Set getFillEdges()\n {\n if (fillEdges == null) {\n computeMinimalTriangulation();\n }\n\n return fillEdges;\n }\n\n /**\n * Get the minimal triangulation of the graph.\n *\n * @return Triangulated graph.\n */\n public Graph getMinimalTriangulation()\n {\n if (chordalGraph == null) {\n computeMinimalTriangulation();\n }\n\n return chordalGraph;\n }\n\n /**\n * Get the generators of the separators of the triangulated graph, i.e. all vertices that\n * generate a minimal separator of triangulated graph.\n *\n * @return List of generators.\n */\n public List getGenerators()\n {\n if (generators == null) {\n computeMinimalTriangulation();\n }\n\n return generators;\n }\n\n /**\n * Get the minimal elimination ordering produced by the triangulation.\n *\n * @return The minimal elimination ordering.\n */\n public LinkedList getMeo()\n {\n if (meo == null) {\n computeMinimalTriangulation();\n }\n\n return meo;\n }\n\n /**\n * Get a map to know for each separator how many components it produces.\n *\n * @return A map from separators to integers (component count).\n */\n public Map, Integer> getFullComponentCount()\n {\n if (fullComponentCount == null) {\n computeAtoms();\n }\n\n return fullComponentCount;\n }\n\n /**\n * Get the atoms generated by the decomposition.\n *\n * @return Set of atoms, where each atom is described as the set of its vertices.\n */\n public Set> getAtoms()\n {\n if (atoms == null) {\n computeAtoms();\n }\n\n return atoms;\n }\n\n /**\n * Get the clique minimal separators.\n *\n * @return Set of separators, where each separator is described as the set of its vertices.\n */\n public Set> getSeparators()\n {\n if (separators == null) {\n computeAtoms();\n }\n\n return separators;\n }\n\n /**\n * Get the original graph.\n *\n * @return Original graph.\n */\n public Graph getGraph()\n {\n return graph;\n }\n}\n", "file_name": "CliqueMinimalSeparatorDecomposition.java", "human_label": "Return true if the subgraph of the given graph induced by the given vertices is a clique,otherwise return false.", "level": "class_runnable", "lineno": "290", "name": "isClique", "oracle_context": "{ \"apis\" : \"[equals, getEdge]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "org.jgrapht.alg.clique", "project": "jgrapht-master" }, { "_id": "636767431a6d9265ec017c88", "all_context": "{ \"class_level\" : \"import org.jgrapht.alg.util.Pair;\\nimport java.util.*;\\nimport java.util.function.Function;\\nRandom rng;\\nList> lowerBounds;\\nList> upperBounds;\\nDistributor();\\nDistributor(long seed);\\nDistributor(Random rng);\\naddLowerBound(Function lowerBound);\\ncomputeLowerBounds(List keys);\\ncomputeUpperBounds(List keys);\\ncomputeSuffixSum(List bounds);\\ngetDistribution(List keys,int valueNum);\\naddUpperBound(Function upperBound);\\n\", \"repo_level\" : \"public interface Pair {public A getFirst();\\npublic B getSecond();\\npublic void setFirst(A f);\\npublic void setSecond(B s);\\npublic boolean hasElement(E e);\\npublic String toString();\\npublic boolean equals(Object o);\\npublic int hashCode();\\nstatic Pair of(A a,B b);\\n }\\n\" }", "class_name": "Distributor", "code": "private List computeLowerBounds(List keys){\n List keyLowerBounds=new ArrayList<>(keys.size());\n for ( K key : keys) {\n int lowerBound=0;\n for ( Function lowerBoundFunction : lowerBounds) {\n lowerBound=Math.max(lowerBound,lowerBoundFunction.apply(key));\n }\n keyLowerBounds.add(lowerBound);\n }\n return keyLowerBounds;\n}\n", "docstring": "/** \n * Finds a maximum lower bound for every key.\n * @param keys list of keys.\n * @return the computed key lower bounds.\n */\n", "end_lineno": "120", "file_content": "/*\n * (C) Copyright 2020-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.generate.netgen;\n\nimport org.jgrapht.alg.util.Pair;\n\nimport java.util.*;\nimport java.util.function.Function;\n\n/**\n * Distributes value units among keys given lower and upper bound constraints.\n *

          \n * Let's define a set of elements $\\{k_1, k_2, \\dots, k_n\\}$. For every element a set of lower\n * bounds $\\{l_1, l_2, \\dots, l_t\\}$ and upper bounds $\\{u_1, u_2, \\dots, u_p\\}$ is specified. The\n * problem is to randomly distribute a number of abstract value units $V$ among keys such that the\n * lower bound and upper bound constraints are satisfied. This class solves this problem.\n *\n * @param the element type.\n * @author Timofey Chudakov\n * @see NetworkGenerator\n */\npublic class Distributor\n{\n /**\n * Random number generator used by this distributor.\n */\n private final Random rng;\n /**\n * Lower bounds.\n */\n private final List> lowerBounds;\n /**\n * Upper bounds.\n */\n private final List> upperBounds;\n\n /**\n * Creates a Distributor using random seed.\n */\n public Distributor()\n {\n this(System.nanoTime());\n }\n\n /**\n * Creates a distributor using the specified {@code seed}.\n *\n * @param seed the seed for the random number generator.\n */\n public Distributor(long seed)\n {\n this(new Random(seed));\n }\n\n /**\n * Creates a distributor which uses the random number generatow {@code rng}.\n *\n * @param rng a random number generator to use.\n */\n public Distributor(Random rng)\n {\n this.rng = rng;\n this.lowerBounds = new ArrayList<>();\n this.upperBounds = new ArrayList<>();\n }\n\n /**\n * Adds an upper bounding function. This function must be defined for all keys.\n *\n * @param upperBound an upper bound function.\n */\n public void addUpperBound(Function upperBound)\n {\n this.upperBounds.add(upperBound);\n }\n\n /**\n * Adds a lower bound function. This function must be defined for all keys.\n *\n * @param lowerBound a lower bound function.\n */\n public void addLowerBound(Function lowerBound)\n {\n this.lowerBounds.add(lowerBound);\n }\n\n /**\n * Finds a maximum lower bound for every key.\n *\n * @param keys list of keys.\n * @return the computed key lower bounds.\n */\n private List computeLowerBounds(List keys)\n {\n List keyLowerBounds = new ArrayList<>(keys.size());\n for (K key : keys) {\n int lowerBound = 0;\n for (Function lowerBoundFunction : lowerBounds) {\n lowerBound = Math.max(lowerBound, lowerBoundFunction.apply(key));\n }\n keyLowerBounds.add(lowerBound);\n }\n\n return keyLowerBounds;\n }\n\n /**\n * Finds a minimum lower bound for every key.\n *\n * @param keys a list of keys.\n * @return the computed key upper bound.\n */\n private List computeUpperBounds(List keys)\n {\n List keyUpperBounds = new ArrayList<>(keys.size());\n for (K key : keys) {\n int upperBound = Integer.MAX_VALUE;\n for (Function upperBoundFunction : upperBounds) {\n upperBound = Math.min(upperBound, upperBoundFunction.apply(key));\n }\n keyUpperBounds.add(upperBound);\n }\n\n return keyUpperBounds;\n }\n\n /**\n * Computes a suffix sum of the {@code bounds}. Returns computed suffix sum and the sum of all\n * elements in the {@code bounds list}.\n *\n * @param bounds list of integers.\n * @return computed pair of suffix sum list and a sum of all elements.\n */\n private Pair, Long> computeSuffixSum(List bounds)\n {\n List suffixSum = new ArrayList<>(Collections.nCopies(bounds.size(), 0));\n long sum = 0;\n for (int i = bounds.size() - 1; i >= 0; i--) {\n suffixSum.set(i, (int) Math.min(Integer.MAX_VALUE, sum));\n sum += bounds.get(i);\n }\n\n return Pair.of(suffixSum, sum);\n }\n\n /**\n * Computes and returns a value distribution for the list of keys. The resulting distribution\n * will satisfy the (possibly empty) sets of lower and upper bound constraints. Distributed\n * values will be in the same order as the keys in the key list.\n *\n * @param keys the list of keys.\n * @param valueNum the number of abstract value units to distribute.\n * @return the computed value distribution.\n */\n public List getDistribution(List keys, final int valueNum)\n {\n List keyLowerBounds = computeLowerBounds(keys);\n List keyUpperBounds = computeUpperBounds(keys);\n\n Pair, Long> lbSufSumP = computeSuffixSum(keyLowerBounds);\n Pair, Long> ubSufSumP = computeSuffixSum(keyUpperBounds);\n\n List lbSufSum = lbSufSumP.getFirst();\n List ubSufSum = ubSufSumP.getFirst();\n\n long lbSum = lbSufSumP.getSecond();\n long ubSum = ubSufSumP.getSecond();\n\n if (lbSum > valueNum) {\n throw new IllegalArgumentException(\n \"Can't distribute values among keys: the sum of lower bounds is greater than the number of values\");\n } else if (ubSum < valueNum) {\n throw new IllegalArgumentException(\n \"Can't distribute values among keys: the sum of upper bounds is smaller than the number of values\");\n }\n\n int remainingValues = valueNum;\n List resultingDistribution = new ArrayList<>();\n for (int i = 0; i < keyLowerBounds.size(); i++) {\n int lowerBound = keyLowerBounds.get(i);\n int upperBound = keyUpperBounds.get(i);\n\n int valueNumUpperBound = remainingValues - lbSufSum.get(i);\n int valueNumLowerBound = remainingValues - ubSufSum.get(i);\n\n lowerBound = Math.max(lowerBound, valueNumLowerBound);\n upperBound = Math.min(upperBound, valueNumUpperBound);\n\n if (lowerBound > upperBound) {\n throw new IllegalArgumentException(\n \"Infeasible bound specified for the key: \" + keys.get(i));\n }\n\n int allocatedValues = rng.nextInt(upperBound - lowerBound + 1) + lowerBound;\n resultingDistribution.add(allocatedValues);\n remainingValues -= allocatedValues;\n }\n\n return resultingDistribution;\n }\n\n}\n", "file_name": "Distributor.java", "human_label": "The type of key has several lower bounds conducted by different function,this function will return a list of the maximum lower bound of each key in the given list.", "level": "class_runnable", "lineno": "102", "name": "computeLowerBounds", "oracle_context": "{ \"apis\" : \"[size, max, apply, add]\", \"classes\" : \"[List]\", \"vars\" : \"[lowerBounds]\" }", "package": "org.jgrapht.generate.netgen", "project": "jgrapht-master" }, { "_id": "636766a91a6d9265ec0175c4", "all_context": "{ \"class_level\" : \"int SAME_FRAME;\\nint SAME_LOCALS_1_STACK_ITEM_FRAME;\\nint SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED;\\nint CHOP_FRAME;\\nint SAME_FRAME_EXTENDED;\\nint APPEND_FRAME;\\nint FULL_FRAME;\\nint ITEM_TOP;\\nint ITEM_INTEGER;\\nint ITEM_FLOAT;\\nint ITEM_DOUBLE;\\nint ITEM_LONG;\\nint ITEM_NULL;\\nint ITEM_UNINITIALIZED_THIS;\\nint ITEM_OBJECT;\\nint ITEM_UNINITIALIZED;\\nint ITEM_ASM_BOOLEAN;\\nint ITEM_ASM_BYTE;\\nint ITEM_ASM_CHAR;\\nint ITEM_ASM_SHORT;\\nint DIM_SIZE;\\nint KIND_SIZE;\\nint FLAGS_SIZE;\\nint VALUE_SIZE;\\nint DIM_SHIFT;\\nint KIND_SHIFT;\\nint FLAGS_SHIFT;\\nint DIM_MASK;\\nint KIND_MASK;\\nint VALUE_MASK;\\nint ARRAY_OF;\\nint ELEMENT_OF;\\nint CONSTANT_KIND;\\nint REFERENCE_KIND;\\nint UNINITIALIZED_KIND;\\nint LOCAL_KIND;\\nint STACK_KIND;\\nint TOP_IF_LONG_OR_DOUBLE_FLAG;\\nint TOP;\\nint BOOLEAN;\\nint BYTE;\\nint CHAR;\\nint SHORT;\\nint INTEGER;\\nint FLOAT;\\nint LONG;\\nint DOUBLE;\\nint NULL;\\nint UNINITIALIZED_THIS;\\nLabel owner;\\nint[] inputLocals;\\nint[] inputStack;\\nint[] outputLocals;\\nint[] outputStack;\\nshort outputStackStart;\\nshort outputStackTop;\\nint initializationCount;\\nint[] initializations;\\nFrame(Label owner);\\ngetAbstractTypeFromDescriptor(SymbolTable symbolTable,String buffer,int offset);\\nsetInputFrameFromDescriptor(SymbolTable symbolTable,int access,String descriptor,int maxLocals);\\ngetLocal(int localIndex);\\nsetLocal(int localIndex,int abstractType);\\npush(SymbolTable symbolTable,String descriptor);\\npop();\\npop(int elements);\\npop(String descriptor);\\naddInitializedType(int abstractType);\\ngetInitializedType(SymbolTable symbolTable,int abstractType);\\nexecute(int opcode,int arg,Symbol argSymbol,SymbolTable symbolTable);\\ngetConcreteOutputType(int abstractOutputType,int numStack);\\nmerge(SymbolTable symbolTable,Frame dstFrame);\\nmerge(SymbolTable symbolTable,int sourceType,int[] dstTypes,int dstIndex);\\naccept(MethodWriter methodWriter);\\npush(int abstractType);\\n\", \"repo_level\" : \"\" }", "class_name": "Frame", "code": "private void pop(final String descriptor){\n char firstDescriptorChar=descriptor.charAt(0);\n if (firstDescriptorChar == '(') {\n pop((Type.getArgumentsAndReturnSizes(descriptor) >> 2) - 1);\n }\n else if (firstDescriptorChar == 'J' || firstDescriptorChar == 'D') {\n pop(2);\n }\n else {\n pop(1);\n }\n}\n", "docstring": "/** \n * Pops as many abstract types from the output frame stack as described by the given descriptor.\n * @param descriptor a type or method descriptor (in which case its argument types are popped).\n */\n", "end_lineno": "661", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage com.alibaba.fastjson2.internal.asm;\n\n/**\n * @author Eric Bruneton\n */\nclass Frame {\n // Constants used in the StackMapTable attribute.\n // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.4.\n\n static final int SAME_FRAME = 0;\n static final int SAME_LOCALS_1_STACK_ITEM_FRAME = 64;\n// static final int RESERVED = 128;\n static final int SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247;\n static final int CHOP_FRAME = 248;\n static final int SAME_FRAME_EXTENDED = 251;\n static final int APPEND_FRAME = 252;\n static final int FULL_FRAME = 255;\n\n static final int ITEM_TOP = 0;\n static final int ITEM_INTEGER = 1;\n static final int ITEM_FLOAT = 2;\n static final int ITEM_DOUBLE = 3;\n static final int ITEM_LONG = 4;\n static final int ITEM_NULL = 5;\n static final int ITEM_UNINITIALIZED_THIS = 6;\n static final int ITEM_OBJECT = 7;\n static final int ITEM_UNINITIALIZED = 8;\n // Additional, ASM specific constants used in abstract types below.\n static final int ITEM_ASM_BOOLEAN = 9;\n static final int ITEM_ASM_BYTE = 10;\n static final int ITEM_ASM_CHAR = 11;\n static final int ITEM_ASM_SHORT = 12;\n\n // The size and offset in bits of each field of an abstract type.\n\n static final int DIM_SIZE = 6;\n static final int KIND_SIZE = 4;\n static final int FLAGS_SIZE = 2;\n static final int VALUE_SIZE = 32 - DIM_SIZE - KIND_SIZE - FLAGS_SIZE;\n\n static final int DIM_SHIFT = KIND_SIZE + FLAGS_SIZE + VALUE_SIZE;\n static final int KIND_SHIFT = FLAGS_SIZE + VALUE_SIZE;\n static final int FLAGS_SHIFT = VALUE_SIZE;\n\n // Bitmasks to get each field of an abstract type.\n\n static final int DIM_MASK = ((1 << DIM_SIZE) - 1) << DIM_SHIFT;\n static final int KIND_MASK = ((1 << KIND_SIZE) - 1) << KIND_SHIFT;\n static final int VALUE_MASK = (1 << VALUE_SIZE) - 1;\n\n // Constants to manipulate the DIM field of an abstract type.\n\n /**\n * The constant to be added to an abstract type to get one with one more array dimension.\n */\n static final int ARRAY_OF = +1 << DIM_SHIFT;\n\n /**\n * The constant to be added to an abstract type to get one with one less array dimension.\n */\n static final int ELEMENT_OF = -1 << DIM_SHIFT;\n\n // Possible values for the KIND field of an abstract type.\n\n static final int CONSTANT_KIND = 1 << KIND_SHIFT;\n static final int REFERENCE_KIND = 2 << KIND_SHIFT;\n static final int UNINITIALIZED_KIND = 3 << KIND_SHIFT;\n static final int LOCAL_KIND = 4 << KIND_SHIFT;\n static final int STACK_KIND = 5 << KIND_SHIFT;\n\n // Possible flags for the FLAGS field of an abstract type.\n\n /**\n * A flag used for LOCAL_KIND and STACK_KIND abstract types, indicating that if the resolved,\n * concrete type is LONG or DOUBLE, TOP should be used instead (because the value has been\n * partially overridden with an xSTORE instruction).\n */\n private static final int TOP_IF_LONG_OR_DOUBLE_FLAG = 1 << FLAGS_SHIFT;\n\n // Useful predefined abstract types (all the possible CONSTANT_KIND types).\n\n private static final int TOP = CONSTANT_KIND | ITEM_TOP;\n private static final int BOOLEAN = CONSTANT_KIND | ITEM_ASM_BOOLEAN;\n private static final int BYTE = CONSTANT_KIND | ITEM_ASM_BYTE;\n private static final int CHAR = CONSTANT_KIND | ITEM_ASM_CHAR;\n private static final int SHORT = CONSTANT_KIND | ITEM_ASM_SHORT;\n private static final int INTEGER = CONSTANT_KIND | ITEM_INTEGER;\n private static final int FLOAT = CONSTANT_KIND | ITEM_FLOAT;\n private static final int LONG = CONSTANT_KIND | ITEM_LONG;\n private static final int DOUBLE = CONSTANT_KIND | ITEM_DOUBLE;\n private static final int NULL = CONSTANT_KIND | ITEM_NULL;\n private static final int UNINITIALIZED_THIS = CONSTANT_KIND | ITEM_UNINITIALIZED_THIS;\n\n // -----------------------------------------------------------------------------------------------\n // Instance fields\n // -----------------------------------------------------------------------------------------------\n\n /**\n * The basic block to which these input and output stack map frames correspond.\n */\n Label owner;\n\n /**\n * The input stack map frame locals. This is an array of abstract types.\n */\n private int[] inputLocals;\n\n /**\n * The input stack map frame stack. This is an array of abstract types.\n */\n int[] inputStack;\n\n /**\n * The output stack map frame locals. This is an array of abstract types.\n */\n private int[] outputLocals;\n\n /**\n * The output stack map frame stack. This is an array of abstract types.\n */\n private int[] outputStack;\n\n /**\n * The start of the output stack, relatively to the input stack. This offset is always negative or\n * null. A null offset means that the output stack must be appended to the input stack. A -n\n * offset means that the first n output stack elements must replace the top n input stack\n * elements, and that the other elements must be appended to the input stack.\n */\n private short outputStackStart;\n\n /**\n * The index of the top stack element in {@link #outputStack}.\n */\n private short outputStackTop;\n\n /**\n * The number of types that are initialized in the basic block. See {@link #initializations}.\n */\n private int initializationCount;\n\n /**\n * The abstract types that are initialized in the basic block. A constructor invocation on an\n * UNINITIALIZED or UNINITIALIZED_THIS abstract type must replace every occurrence of this\n * type in the local variables and in the operand stack. This cannot be done during the first step\n * of the algorithm since, during this step, the local variables and the operand stack types are\n * still abstract. It is therefore necessary to store the abstract types of the constructors which\n * are invoked in the basic block, in order to do this replacement during the second step of the\n * algorithm, where the frames are fully computed. Note that this array can contain abstract types\n * that are relative to the input locals or to the input stack.\n */\n private int[] initializations;\n\n // -----------------------------------------------------------------------------------------------\n // Constructor\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Constructs a new Frame.\n *\n * @param owner the basic block to which these input and output stack map frames correspond.\n */\n Frame(final Label owner) {\n this.owner = owner;\n }\n//\n// /**\n// * Returns the abstract type corresponding to the internal name of a class.\n// *\n// * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n// * @param internalName the internal name of a class. This must not be an array type\n// * descriptor.\n// * @return the abstract type value corresponding to the given internal name.\n// */\n// static int getAbstractTypeFromInternalName(\n// final SymbolTable symbolTable, final String internalName) {\n// return REFERENCE_KIND | symbolTable.addType(internalName);\n// }\n\n /**\n * Returns the abstract type corresponding to the given type descriptor.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param buffer a string ending with a type descriptor.\n * @param offset the start offset of the type descriptor in buffer.\n * @return the abstract type corresponding to the given type descriptor.\n */\n private static int getAbstractTypeFromDescriptor(\n final SymbolTable symbolTable, final String buffer, final int offset) {\n String internalName = null;\n switch (buffer.charAt(offset)) {\n case 'V':\n return 0;\n case 'Z':\n case 'C':\n case 'B':\n case 'S':\n case 'I':\n return INTEGER;\n case 'F':\n return FLOAT;\n case 'J':\n return LONG;\n case 'D':\n return DOUBLE;\n case 'L':\n if (offset == 0) {\n switch (buffer) {\n case \"Ljava/lang/Object;\":\n internalName = \"java/lang/Object\";\n break;\n case \"Ljava/lang/Class;\":\n internalName = \"java/lang/Class\";\n break;\n case \"Ljava/lang/String;\":\n internalName = \"java/lang/String\";\n break;\n case \"Ljava/util/List;\":\n internalName = \"java/util/List\";\n break;\n case \"Ljava/lang/reflect/Type;\":\n internalName = \"java/lang/reflect/Type\";\n break;\n case \"Ljava/util/function/Supplier;\":\n internalName = \"java/util/function/Supplier\";\n break;\n case \"Lsun/misc/Unsafe;\":\n internalName = \"sun/misc/Unsafe\";\n break;\n case \"Lcom/alibaba/fastjson2/JSONReader;\":\n internalName = \"com/alibaba/fastjson2/JSONReader\";\n break;\n case \"Lcom/alibaba/fastjson2/reader/FieldReader;\":\n internalName = \"com/alibaba/fastjson2/reader/FieldReader\";\n break;\n case \"Lcom/alibaba/fastjson2/reader/ObjectReader;\":\n internalName = \"com/alibaba/fastjson2/reader/ObjectReader\";\n break;\n case \"Lcom/alibaba/fastjson2/JSONWriter;\":\n internalName = \"com/alibaba/fastjson2/JSONWriter\";\n break;\n case \"Lcom/alibaba/fastjson2/writer/FieldWriter;\":\n internalName = \"com/alibaba/fastjson2/writer/FieldWriter\";\n break;\n default:\n break;\n }\n } else if (offset == 2) {\n switch (buffer) {\n case \"()Ljava/lang/Class;\":\n internalName = \"java/lang/Class\";\n break;\n case \"()Ljava/lang/String;\":\n internalName = \"java/lang/String\";\n break;\n default:\n break;\n }\n } else if (offset == 3) {\n switch (buffer) {\n case \"(J)Lcom/alibaba/fastjson2/reader/FieldReader;\":\n internalName = \"com/alibaba/fastjson2/reader/FieldReader\";\n break;\n case \"(I)Ljava/lang/Object;\":\n internalName = \"java/lang/Object\";\n break;\n case \"(I)Ljava/lang/Integer;\":\n internalName = \"java/lang/Integer\";\n break;\n default:\n break;\n }\n } else if (offset == 36) {\n switch (buffer) {\n case \"(Lcom/alibaba/fastjson2/JSONReader;)Lcom/alibaba/fastjson2/reader/ObjectReader;\":\n internalName = \"com/alibaba/fastjson2/reader/ObjectReader\";\n break;\n case \"(Lcom/alibaba/fastjson2/JSONReader;)Ljava/lang/Object;\":\n internalName = \"java/lang/Object\";\n break;\n default:\n break;\n }\n } else if (offset == 54) {\n switch (buffer) {\n case \"(Lcom/alibaba/fastjson2/JSONReader;Ljava/lang/Class;J)Lcom/alibaba/fastjson2/reader/ObjectReader;\":\n internalName = \"com/alibaba/fastjson2/reader/ObjectReader\";\n break;\n case \"(Lcom/alibaba/fastjson2/JSONReader;Ljava/lang/Class;J)Ljava/lang/Object;\":\n internalName = \"java/lang/Object\";\n break;\n default:\n break;\n }\n } else {\n switch (buffer) {\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/Class;)Lcom/alibaba/fastjson2/writer/ObjectWriter;\":\n if (offset == 53) {\n internalName = \"com/alibaba/fastjson2/writer/ObjectWriter\";\n }\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/reflect/Type;)Lcom/alibaba/fastjson2/writer/ObjectWriter;\":\n if (offset == 60) {\n internalName = \"com/alibaba/fastjson2/writer/ObjectWriter\";\n }\n break;\n case \"(Lcom/alibaba/fastjson2/writer/FieldWriter;Ljava/lang/Object;)Ljava/lang/String;\":\n if (offset == 62) {\n internalName = \"java/lang/String\";\n }\n break;\n case \"(Lcom/alibaba/fastjson2/JSONReader;Ljava/lang/reflect/Type;Ljava/lang/Object;J)Ljava/lang/Object;\":\n if (offset == 79) {\n internalName = \"java/lang/Object\";\n }\n break;\n default:\n break;\n }\n }\n\n if (internalName == null) {\n internalName = buffer.substring(offset + 1, buffer.length() - 1);\n }\n return REFERENCE_KIND | symbolTable.addType(internalName);\n case '[':\n int elementDescriptorOffset = offset + 1;\n while (buffer.charAt(elementDescriptorOffset) == '[') {\n ++elementDescriptorOffset;\n }\n int typeValue;\n switch (buffer.charAt(elementDescriptorOffset)) {\n case 'Z':\n typeValue = BOOLEAN;\n break;\n case 'C':\n typeValue = CHAR;\n break;\n case 'B':\n typeValue = BYTE;\n break;\n case 'S':\n typeValue = SHORT;\n break;\n case 'I':\n typeValue = INTEGER;\n break;\n case 'F':\n typeValue = FLOAT;\n break;\n case 'J':\n typeValue = LONG;\n break;\n case 'D':\n typeValue = DOUBLE;\n break;\n case 'L':\n if (offset == 0) {\n switch (buffer) {\n case \"[Lcom/alibaba/fastjson2/writer/FieldWriter;\":\n internalName = \"com/alibaba/fastjson2/reader/FieldReader\";\n break;\n case \"[Lcom/alibaba/fastjson2/reader/FieldReader;\":\n internalName = \"Lcom/alibaba/fastjson2/reader/FieldReader\";\n break;\n default:\n break;\n }\n }\n if (internalName == null) {\n internalName = buffer.substring(elementDescriptorOffset + 1, buffer.length() - 1);\n }\n typeValue = REFERENCE_KIND | symbolTable.addType(internalName);\n break;\n default:\n throw new IllegalArgumentException();\n }\n return ((elementDescriptorOffset - offset) << DIM_SHIFT) | typeValue;\n default:\n throw new IllegalArgumentException();\n }\n }\n\n // -----------------------------------------------------------------------------------------------\n // Methods related to the input frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Sets the input frame from the given method description. This method is used to initialize the\n * first frame of a method, which is implicit (i.e. not stored explicitly in the StackMapTable\n * attribute).\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param access the method's access flags.\n * @param descriptor the method descriptor.\n * @param maxLocals the maximum number of local variables of the method.\n */\n final void setInputFrameFromDescriptor(\n final SymbolTable symbolTable,\n final int access,\n final String descriptor,\n final int maxLocals) {\n inputLocals = new int[maxLocals];\n inputStack = new int[0];\n int inputLocalIndex = 0;\n if ((access & Opcodes.ACC_STATIC) == 0) {\n if ((access & Constants.ACC_CONSTRUCTOR) == 0) {\n inputLocals[inputLocalIndex++] =\n REFERENCE_KIND | symbolTable.addType(symbolTable.className);\n } else {\n inputLocals[inputLocalIndex++] = UNINITIALIZED_THIS;\n }\n }\n for (Type argumentType : Type.getArgumentTypes(descriptor)) {\n int abstractType =\n getAbstractTypeFromDescriptor(symbolTable, argumentType.getDescriptor(), 0);\n inputLocals[inputLocalIndex++] = abstractType;\n if (abstractType == LONG || abstractType == DOUBLE) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n }\n while (inputLocalIndex < maxLocals) {\n inputLocals[inputLocalIndex++] = TOP;\n }\n }\n\n // -----------------------------------------------------------------------------------------------\n // Methods related to the output frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Returns the abstract type stored at the given local variable index in the output frame.\n *\n * @param localIndex the index of the local variable whose value must be returned.\n * @return the abstract type stored at the given local variable index in the output frame.\n */\n private int getLocal(final int localIndex) {\n if (outputLocals == null || localIndex >= outputLocals.length) {\n // If this local has never been assigned in this basic block, it is still equal to its value\n // in the input frame.\n return LOCAL_KIND | localIndex;\n } else {\n int abstractType = outputLocals[localIndex];\n if (abstractType == 0) {\n // If this local has never been assigned in this basic block, so it is still equal to its\n // value in the input frame.\n abstractType = outputLocals[localIndex] = LOCAL_KIND | localIndex;\n }\n return abstractType;\n }\n }\n\n /**\n * Replaces the abstract type stored at the given local variable index in the output frame.\n *\n * @param localIndex the index of the output frame local variable that must be set.\n * @param abstractType the value that must be set.\n */\n private void setLocal(final int localIndex, final int abstractType) {\n // Create and/or resize the output local variables array if necessary.\n if (outputLocals == null) {\n outputLocals = new int[10];\n }\n int outputLocalsLength = outputLocals.length;\n if (localIndex >= outputLocalsLength) {\n int[] newOutputLocals = new int[Math.max(localIndex + 1, 2 * outputLocalsLength)];\n System.arraycopy(outputLocals, 0, newOutputLocals, 0, outputLocalsLength);\n outputLocals = newOutputLocals;\n }\n // Set the local variable.\n outputLocals[localIndex] = abstractType;\n }\n\n /**\n * Pushes the given abstract type on the output frame stack.\n *\n * @param abstractType an abstract type.\n */\n private void push(final int abstractType) {\n // Create and/or resize the output stack array if necessary.\n if (outputStack == null) {\n outputStack = new int[10];\n }\n int outputStackLength = outputStack.length;\n if (outputStackTop >= outputStackLength) {\n int[] newOutputStack = new int[Math.max(outputStackTop + 1, 2 * outputStackLength)];\n System.arraycopy(outputStack, 0, newOutputStack, 0, outputStackLength);\n outputStack = newOutputStack;\n }\n // Pushes the abstract type on the output stack.\n outputStack[outputStackTop++] = abstractType;\n // Updates the maximum size reached by the output stack, if needed (note that this size is\n // relative to the input stack size, which is not known yet).\n short outputStackSize = (short) (outputStackStart + outputStackTop);\n if (outputStackSize > owner.outputStackMax) {\n owner.outputStackMax = outputStackSize;\n }\n }\n\n /**\n * Pushes the abstract type corresponding to the given descriptor on the output frame stack.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param descriptor a type or method descriptor (in which case its return type is pushed).\n */\n private void push(final SymbolTable symbolTable, final String descriptor) {\n final int typeDescriptorOffset;\n switch (descriptor) {\n case \"()J\":\n case \"()V\":\n case \"()Z\":\n case \"()I\":\n case \"()Ljava/lang/Class;\":\n typeDescriptorOffset = 2;\n break;\n case \"(I)V\":\n case \"(J)V\":\n case \"(J)Z\":\n case \"(I)Ljava/lang/Object;\":\n case \"(I)Ljava/lang/Integer;\":\n typeDescriptorOffset = 3;\n break;\n case \"(Ljava/lang/Enum;)V\":\n typeDescriptorOffset = 18;\n break;\n case \"(Ljava/lang/Object;)Z\":\n case \"(Ljava/lang/String;)V\":\n case \"(Ljava/lang/Object;)V\":\n typeDescriptorOffset = 20;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;)V\":\n case \"(Lcom/alibaba/fastjson2/JSONWriter;)Z\":\n typeDescriptorOffset = 36;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;I)V\":\n case \"(Lcom/alibaba/fastjson2/JSONWriter;J)V\":\n typeDescriptorOffset = 37;\n break;\n case \"(Ljava/lang/Object;Ljava/lang/reflect/Type;)Z\":\n typeDescriptorOffset = 44;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/Enum;)V\":\n typeDescriptorOffset = 52;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/Class;)Lcom/alibaba/fastjson2/writer/ObjectWriter;\":\n case \"(Lcom/alibaba/fastjson2/JSONWriter;ZLjava/util/List;)V\":\n typeDescriptorOffset = 53;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/reflect/Type;)Lcom/alibaba/fastjson2/writer/ObjectWriter;\":\n typeDescriptorOffset = 60;\n break;\n case \"(Lcom/alibaba/fastjson2/writer/FieldWriter;Ljava/lang/Object;)Ljava/lang/String;\":\n typeDescriptorOffset = 62;\n break;\n case \"(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;JLjava/util/List;)V\":\n typeDescriptorOffset = 72;\n break;\n case \"(Lcom/alibaba/fastjson2/JSONWriter;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/reflect/Type;J)V\":\n typeDescriptorOffset = 97;\n break;\n default:\n if (descriptor.charAt(0) == '(') {\n int currentOffset = 1;\n // Skip the argument types, one at a each loop iteration.\n while (descriptor.charAt(currentOffset) != ')') {\n while (descriptor.charAt(currentOffset) == '[') {\n currentOffset++;\n }\n if (descriptor.charAt(currentOffset++) == 'L') {\n // Skip the argument descriptor content.\n int semiColumnOffset = descriptor.indexOf(';', currentOffset);\n currentOffset = Math.max(currentOffset, semiColumnOffset + 1);\n }\n }\n typeDescriptorOffset = currentOffset + 1;\n } else {\n typeDescriptorOffset = 0;\n }\n break;\n }\n\n int abstractType = getAbstractTypeFromDescriptor(symbolTable, descriptor, typeDescriptorOffset);\n if (abstractType != 0) {\n push(abstractType);\n if (abstractType == LONG || abstractType == DOUBLE) {\n push(TOP);\n }\n }\n }\n\n /**\n * Pops an abstract type from the output frame stack and returns its value.\n *\n * @return the abstract type that has been popped from the output frame stack.\n */\n private int pop() {\n if (outputStackTop > 0) {\n return outputStack[--outputStackTop];\n } else {\n // If the output frame stack is empty, pop from the input stack.\n return STACK_KIND | -(--outputStackStart);\n }\n }\n\n /**\n * Pops the given number of abstract types from the output frame stack.\n *\n * @param elements the number of abstract types that must be popped.\n */\n private void pop(final int elements) {\n if (outputStackTop >= elements) {\n outputStackTop -= elements;\n } else {\n // If the number of elements to be popped is greater than the number of elements in the output\n // stack, clear it, and pop the remaining elements from the input stack.\n outputStackStart -= elements - outputStackTop;\n outputStackTop = 0;\n }\n }\n\n /**\n * Pops as many abstract types from the output frame stack as described by the given descriptor.\n *\n * @param descriptor a type or method descriptor (in which case its argument types are popped).\n */\n private void pop(final String descriptor) {\n char firstDescriptorChar = descriptor.charAt(0);\n if (firstDescriptorChar == '(') {\n pop((Type.getArgumentsAndReturnSizes(descriptor) >> 2) - 1);\n } else if (firstDescriptorChar == 'J' || firstDescriptorChar == 'D') {\n pop(2);\n } else {\n pop(1);\n }\n }\n\n // -----------------------------------------------------------------------------------------------\n // Methods to handle uninitialized types\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Adds an abstract type to the list of types on which a constructor is invoked in the basic\n * block.\n *\n * @param abstractType an abstract type on a which a constructor is invoked.\n */\n private void addInitializedType(final int abstractType) {\n // Create and/or resize the initializations array if necessary.\n if (initializations == null) {\n initializations = new int[2];\n }\n int initializationsLength = initializations.length;\n if (initializationCount >= initializationsLength) {\n int[] newInitializations =\n new int[Math.max(initializationCount + 1, 2 * initializationsLength)];\n System.arraycopy(initializations, 0, newInitializations, 0, initializationsLength);\n initializations = newInitializations;\n }\n // Store the abstract type.\n initializations[initializationCount++] = abstractType;\n }\n\n /**\n * Returns the \"initialized\" abstract type corresponding to the given abstract type.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param abstractType an abstract type.\n * @return the REFERENCE_KIND abstract type corresponding to abstractType if it is\n * UNINITIALIZED_THIS or an UNINITIALIZED_KIND abstract type for one of the types on which a\n * constructor is invoked in the basic block. Otherwise returns abstractType.\n */\n private int getInitializedType(final SymbolTable symbolTable, final int abstractType) {\n if (abstractType == UNINITIALIZED_THIS\n || (abstractType & (DIM_MASK | KIND_MASK)) == UNINITIALIZED_KIND) {\n for (int i = 0; i < initializationCount; ++i) {\n int initializedType = initializations[i];\n int dim = initializedType & DIM_MASK;\n int kind = initializedType & KIND_MASK;\n int value = initializedType & VALUE_MASK;\n if (kind == LOCAL_KIND) {\n initializedType = dim + inputLocals[value];\n } else if (kind == STACK_KIND) {\n initializedType = dim + inputStack[inputStack.length - value];\n }\n if (abstractType == initializedType) {\n if (abstractType == UNINITIALIZED_THIS) {\n return REFERENCE_KIND | symbolTable.addType(symbolTable.className);\n } else {\n return REFERENCE_KIND\n | symbolTable.addType(symbolTable.typeTable[abstractType & VALUE_MASK].value);\n }\n }\n }\n }\n return abstractType;\n }\n\n // -----------------------------------------------------------------------------------------------\n // Main method, to simulate the execution of each instruction on the output frame\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Simulates the action of the given instruction on the output stack frame.\n *\n * @param opcode the opcode of the instruction.\n * @param arg the numeric operand of the instruction, if any.\n * @param argSymbol the Symbol operand of the instruction, if any.\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n */\n void execute(\n final int opcode, final int arg, final Symbol argSymbol, final SymbolTable symbolTable) {\n final int CONSTANT_INTEGER_TAG = 3;\n final int CONSTANT_FLOAT_TAG = 4;\n final int CONSTANT_LONG_TAG = 5;\n final int CONSTANT_DOUBLE_TAG = 6;\n final int CONSTANT_CLASS_TAG = 7;\n final int CONSTANT_STRING_TAG = 8;\n final int CONSTANT_METHOD_HANDLE_TAG = 15;\n final int CONSTANT_METHOD_TYPE_TAG = 16;\n final int CONSTANT_DYNAMIC_TAG = 17;\n\n // Abstract types popped from the stack or read from local variables.\n int abstractType1;\n int abstractType2;\n int abstractType3;\n int abstractType4;\n switch (opcode) {\n case Opcodes.NOP:\n case Opcodes.INEG:\n case Opcodes.LNEG:\n case Opcodes.FNEG:\n case Opcodes.DNEG:\n case Opcodes.I2B:\n case Opcodes.I2C:\n case Opcodes.I2S:\n case Opcodes.GOTO:\n case Opcodes.RETURN:\n break;\n case Opcodes.ACONST_NULL:\n push(NULL);\n break;\n case Opcodes.ICONST_M1:\n case Opcodes.ICONST_0:\n case Opcodes.ICONST_1:\n case Opcodes.ICONST_2:\n case Opcodes.ICONST_3:\n case Opcodes.ICONST_4:\n case Opcodes.ICONST_5:\n case Opcodes.BIPUSH:\n case Opcodes.SIPUSH:\n case Opcodes.ILOAD:\n push(INTEGER);\n break;\n case Opcodes.LCONST_0:\n case Opcodes.LCONST_1:\n case Opcodes.LLOAD:\n push(LONG);\n push(TOP);\n break;\n case Opcodes.FCONST_0:\n case Opcodes.FCONST_1:\n case Opcodes.FCONST_2:\n case Opcodes.FLOAD:\n push(FLOAT);\n break;\n case Opcodes.DCONST_0:\n case Opcodes.DCONST_1:\n case Opcodes.DLOAD:\n push(DOUBLE);\n push(TOP);\n break;\n case Opcodes.LDC:\n switch (argSymbol.tag) {\n case CONSTANT_INTEGER_TAG:\n push(INTEGER);\n break;\n case CONSTANT_LONG_TAG:\n push(LONG);\n push(TOP);\n break;\n case CONSTANT_FLOAT_TAG:\n push(FLOAT);\n break;\n case CONSTANT_DOUBLE_TAG:\n push(DOUBLE);\n push(TOP);\n break;\n case CONSTANT_CLASS_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/Class\"));\n break;\n case CONSTANT_STRING_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/String\"));\n break;\n case CONSTANT_METHOD_TYPE_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/invoke/MethodType\"));\n break;\n case CONSTANT_METHOD_HANDLE_TAG:\n push(REFERENCE_KIND | symbolTable.addType(\"java/lang/invoke/MethodHandle\"));\n break;\n case CONSTANT_DYNAMIC_TAG:\n push(symbolTable, argSymbol.value);\n break;\n default:\n throw new AssertionError();\n }\n break;\n case Opcodes.ALOAD:\n push(getLocal(arg));\n break;\n case Opcodes.LALOAD:\n case Opcodes.D2L:\n pop(2);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.AALOAD:\n pop(1);\n abstractType1 = pop();\n push(abstractType1 == NULL ? abstractType1 : ELEMENT_OF + abstractType1);\n break;\n case Opcodes.ISTORE:\n case Opcodes.FSTORE:\n case Opcodes.ASTORE:\n abstractType1 = pop();\n setLocal(arg, abstractType1);\n if (arg > 0) {\n int previousLocalType = getLocal(arg - 1);\n if (previousLocalType == LONG || previousLocalType == DOUBLE) {\n setLocal(arg - 1, TOP);\n } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND\n || (previousLocalType & KIND_MASK) == STACK_KIND) {\n // The type of the previous local variable is not known yet, but if it later appears\n // to be LONG or DOUBLE, we should then use TOP instead.\n setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG);\n }\n }\n break;\n case Opcodes.LSTORE:\n case Opcodes.DSTORE:\n pop(1);\n abstractType1 = pop();\n setLocal(arg, abstractType1);\n setLocal(arg + 1, TOP);\n if (arg > 0) {\n int previousLocalType = getLocal(arg - 1);\n if (previousLocalType == LONG || previousLocalType == DOUBLE) {\n setLocal(arg - 1, TOP);\n } else if ((previousLocalType & KIND_MASK) == LOCAL_KIND\n || (previousLocalType & KIND_MASK) == STACK_KIND) {\n // The type of the previous local variable is not known yet, but if it later appears\n // to be LONG or DOUBLE, we should then use TOP instead.\n setLocal(arg - 1, previousLocalType | TOP_IF_LONG_OR_DOUBLE_FLAG);\n }\n }\n break;\n case Opcodes.POP:\n case Opcodes.IFEQ:\n case Opcodes.IFNE:\n case Opcodes.IFLT:\n case Opcodes.IFGE:\n case Opcodes.IFGT:\n case Opcodes.IFLE:\n case Opcodes.IRETURN:\n case Opcodes.FRETURN:\n case Opcodes.ARETURN:\n case Opcodes.TABLESWITCH:\n case Opcodes.LOOKUPSWITCH:\n case Opcodes.ATHROW:\n case Opcodes.MONITORENTER:\n case Opcodes.MONITOREXIT:\n case Opcodes.IFNULL:\n case Opcodes.IFNONNULL:\n pop(1);\n break;\n case Opcodes.POP2:\n case Opcodes.IF_ICMPEQ:\n case Opcodes.IF_ICMPNE:\n case Opcodes.IF_ICMPLT:\n case Opcodes.IF_ICMPGE:\n case Opcodes.IF_ICMPGT:\n case Opcodes.IF_ICMPLE:\n case Opcodes.IF_ACMPEQ:\n case Opcodes.IF_ACMPNE:\n case Opcodes.LRETURN:\n case Opcodes.DRETURN:\n pop(2);\n break;\n case Opcodes.DUP:\n abstractType1 = pop();\n push(abstractType1);\n push(abstractType1);\n break;\n case Opcodes.DUP2:\n abstractType1 = pop();\n abstractType2 = pop();\n push(abstractType2);\n push(abstractType1);\n push(abstractType2);\n push(abstractType1);\n break;\n case Opcodes.SWAP:\n abstractType1 = pop();\n abstractType2 = pop();\n push(abstractType1);\n push(abstractType2);\n break;\n case Opcodes.IALOAD:\n case Opcodes.BALOAD:\n case Opcodes.CALOAD:\n case Opcodes.SALOAD:\n case Opcodes.IADD:\n case Opcodes.ISUB:\n case Opcodes.IMUL:\n case Opcodes.IDIV:\n case Opcodes.IREM:\n case Opcodes.IAND:\n case Opcodes.IOR:\n case Opcodes.IXOR:\n case Opcodes.ISHL:\n case Opcodes.ISHR:\n case Opcodes.IUSHR:\n case Opcodes.L2I:\n case Opcodes.D2I:\n case Opcodes.FCMPL:\n case Opcodes.FCMPG:\n pop(2);\n push(INTEGER);\n break;\n case Opcodes.LADD:\n case Opcodes.LSUB:\n case Opcodes.LMUL:\n case Opcodes.LDIV:\n case Opcodes.LREM:\n case Opcodes.LAND:\n case Opcodes.LOR:\n case Opcodes.LXOR:\n pop(4);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.LSHL:\n case Opcodes.LSHR:\n case Opcodes.LUSHR:\n pop(3);\n push(LONG);\n push(TOP);\n break;\n case Opcodes.IINC:\n setLocal(arg, INTEGER);\n break;\n case Opcodes.F2I:\n case Opcodes.ARRAYLENGTH:\n case Opcodes.INSTANCEOF:\n pop(1);\n push(INTEGER);\n break;\n case Opcodes.LCMP:\n case Opcodes.DCMPL:\n case Opcodes.DCMPG:\n pop(4);\n push(INTEGER);\n break;\n case Opcodes.GETSTATIC:\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.PUTSTATIC:\n pop(argSymbol.value);\n break;\n case Opcodes.GETFIELD:\n pop(1);\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.PUTFIELD:\n pop(argSymbol.value);\n pop();\n break;\n case Opcodes.INVOKEVIRTUAL:\n case Opcodes.INVOKESPECIAL:\n case Opcodes.INVOKESTATIC:\n case Opcodes.INVOKEINTERFACE:\n pop(argSymbol.value);\n if (opcode != Opcodes.INVOKESTATIC) {\n abstractType1 = pop();\n if (opcode == Opcodes.INVOKESPECIAL && argSymbol.name.charAt(0) == '<') {\n addInitializedType(abstractType1);\n }\n }\n push(symbolTable, argSymbol.value);\n break;\n case Opcodes.NEW:\n push(UNINITIALIZED_KIND | symbolTable.addUninitializedType(argSymbol.value, arg));\n break;\n case Opcodes.CHECKCAST:\n String castType = argSymbol.value;\n pop();\n if (castType.charAt(0) == '[') {\n push(symbolTable, castType);\n } else {\n push(REFERENCE_KIND | symbolTable.addType(castType));\n }\n break;\n default:\n throw new IllegalArgumentException();\n }\n }\n\n // -----------------------------------------------------------------------------------------------\n // Frame merging methods, used in the second step of the stack map frame computation algorithm\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Computes the concrete output type corresponding to a given abstract output type.\n *\n * @param abstractOutputType an abstract output type.\n * @param numStack the size of the input stack, used to resolve abstract output types of\n * STACK_KIND kind.\n * @return the concrete output type corresponding to 'abstractOutputType'.\n */\n private int getConcreteOutputType(final int abstractOutputType, final int numStack) {\n int dim = abstractOutputType & DIM_MASK;\n int kind = abstractOutputType & KIND_MASK;\n if (kind == LOCAL_KIND) {\n // By definition, a LOCAL_KIND type designates the concrete type of a local variable at\n // the beginning of the basic block corresponding to this frame (which is known when\n // this method is called, but was not when the abstract type was computed).\n int concreteOutputType = dim + inputLocals[abstractOutputType & VALUE_MASK];\n if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0\n && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) {\n concreteOutputType = TOP;\n }\n return concreteOutputType;\n } else if (kind == STACK_KIND) {\n // By definition, a STACK_KIND type designates the concrete type of a local variable at\n // the beginning of the basic block corresponding to this frame (which is known when\n // this method is called, but was not when the abstract type was computed).\n int concreteOutputType = dim + inputStack[numStack - (abstractOutputType & VALUE_MASK)];\n if ((abstractOutputType & TOP_IF_LONG_OR_DOUBLE_FLAG) != 0\n && (concreteOutputType == LONG || concreteOutputType == DOUBLE)) {\n concreteOutputType = TOP;\n }\n return concreteOutputType;\n } else {\n return abstractOutputType;\n }\n }\n\n final boolean merge(\n final SymbolTable symbolTable, final Frame dstFrame) {\n boolean frameChanged = false;\n\n // Compute the concrete types of the local variables at the end of the basic block corresponding\n // to this frame, by resolving its abstract output types, and merge these concrete types with\n // those of the local variables in the input frame of dstFrame.\n int numLocal = inputLocals.length;\n int numStack = inputStack.length;\n if (dstFrame.inputLocals == null) {\n dstFrame.inputLocals = new int[numLocal];\n frameChanged = true;\n }\n for (int i = 0; i < numLocal; ++i) {\n int concreteOutputType;\n if (outputLocals != null && i < outputLocals.length) {\n int abstractOutputType = outputLocals[i];\n if (abstractOutputType == 0) {\n // If the local variable has never been assigned in this basic block, it is equal to its\n // value at the beginning of the block.\n concreteOutputType = inputLocals[i];\n } else {\n concreteOutputType = getConcreteOutputType(abstractOutputType, numStack);\n }\n } else {\n // If the local variable has never been assigned in this basic block, it is equal to its\n // value at the beginning of the block.\n concreteOutputType = inputLocals[i];\n }\n // concreteOutputType might be an uninitialized type from the input locals or from the input\n // stack. However, if a constructor has been called for this class type in the basic block,\n // then this type is no longer uninitialized at the end of basic block.\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputLocals, i);\n }\n\n // Compute the concrete types of the stack operands at the end of the basic block corresponding\n // to this frame, by resolving its abstract output types, and merge these concrete types with\n // those of the stack operands in the input frame of dstFrame.\n int numInputStack = inputStack.length + outputStackStart;\n if (dstFrame.inputStack == null) {\n dstFrame.inputStack = new int[numInputStack + outputStackTop];\n frameChanged = true;\n }\n // First, do this for the stack operands that have not been popped in the basic block\n // corresponding to this frame, and which are therefore equal to their value in the input\n // frame (except for uninitialized types, which may have been initialized).\n for (int i = 0; i < numInputStack; ++i) {\n int concreteOutputType = inputStack[i];\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |= merge(symbolTable, concreteOutputType, dstFrame.inputStack, i);\n }\n // Then, do this for the stack operands that have pushed in the basic block (this code is the\n // same as the one above for local variables).\n for (int i = 0; i < outputStackTop; ++i) {\n int abstractOutputType = outputStack[i];\n int concreteOutputType = getConcreteOutputType(abstractOutputType, numStack);\n if (initializations != null) {\n concreteOutputType = getInitializedType(symbolTable, concreteOutputType);\n }\n frameChanged |=\n merge(symbolTable, concreteOutputType, dstFrame.inputStack, numInputStack + i);\n }\n return frameChanged;\n }\n\n /**\n * Merges the type at the given index in the given abstract type array with the given type.\n * Returns {@literal true} if the type array has been modified by this operation.\n *\n * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n * @param sourceType the abstract type with which the abstract type array element must be merged.\n * This type should be of {@link #CONSTANT_KIND}, {@link #REFERENCE_KIND} or {@link\n * #UNINITIALIZED_KIND} kind, with positive or {@literal null} array dimensions.\n * @param dstTypes an array of abstract types. These types should be of {@link #CONSTANT_KIND},\n * {@link #REFERENCE_KIND} or {@link #UNINITIALIZED_KIND} kind, with positive or {@literal\n * null} array dimensions.\n * @param dstIndex the index of the type that must be merged in dstTypes.\n * @return {@literal true} if the type array has been modified by this operation.\n */\n private static boolean merge(\n final SymbolTable symbolTable,\n final int sourceType,\n final int[] dstTypes,\n final int dstIndex) {\n int dstType = dstTypes[dstIndex];\n if (dstType == sourceType) {\n // If the types are equal, merge(sourceType, dstType) = dstType, so there is no change.\n return false;\n }\n int srcType = sourceType;\n if ((sourceType & ~DIM_MASK) == NULL) {\n if (dstType == NULL) {\n return false;\n }\n srcType = NULL;\n }\n if (dstType == 0) {\n // If dstTypes[dstIndex] has never been assigned, merge(srcType, dstType) = srcType.\n dstTypes[dstIndex] = srcType;\n return true;\n }\n int mergedType;\n if ((dstType & DIM_MASK) != 0 || (dstType & KIND_MASK) == REFERENCE_KIND) {\n // If dstType is a reference type of any array dimension.\n if (srcType == NULL) {\n // If srcType is the NULL type, merge(srcType, dstType) = dstType, so there is no change.\n return false;\n } else if ((srcType & (DIM_MASK | KIND_MASK)) == (dstType & (DIM_MASK | KIND_MASK))) {\n // If srcType has the same array dimension and the same kind as dstType.\n if ((dstType & KIND_MASK) == REFERENCE_KIND) {\n // If srcType and dstType are reference types with the same array dimension,\n // merge(srcType, dstType) = dim(srcType) | common super class of srcType and dstType.\n mergedType =\n (srcType & DIM_MASK)\n | REFERENCE_KIND\n | symbolTable.addMergedType(srcType & VALUE_MASK, dstType & VALUE_MASK);\n } else {\n // If srcType and dstType are array types of equal dimension but different element types,\n // merge(srcType, dstType) = dim(srcType) - 1 | java/lang/Object.\n int mergedDim = ELEMENT_OF + (srcType & DIM_MASK);\n mergedType = mergedDim | REFERENCE_KIND | symbolTable.addType(\"java/lang/Object\");\n }\n } else if ((srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND) {\n // If srcType is any other reference or array type,\n // merge(srcType, dstType) = min(srcDdim, dstDim) | java/lang/Object\n // where srcDim is the array dimension of srcType, minus 1 if srcType is an array type\n // with a non reference element type (and similarly for dstDim).\n int srcDim = srcType & DIM_MASK;\n if (srcDim != 0 && (srcType & KIND_MASK) != REFERENCE_KIND) {\n srcDim = ELEMENT_OF + srcDim;\n }\n int dstDim = dstType & DIM_MASK;\n if (dstDim != 0 && (dstType & KIND_MASK) != REFERENCE_KIND) {\n dstDim = ELEMENT_OF + dstDim;\n }\n mergedType =\n Math.min(srcDim, dstDim) | REFERENCE_KIND | symbolTable.addType(\"java/lang/Object\");\n } else {\n // If srcType is any other type, merge(srcType, dstType) = TOP.\n mergedType = TOP;\n }\n } else if (dstType == NULL) {\n // If dstType is the NULL type, merge(srcType, dstType) = srcType, or TOP if srcType is not a\n // an array type or a reference type.\n mergedType =\n (srcType & DIM_MASK) != 0 || (srcType & KIND_MASK) == REFERENCE_KIND ? srcType : TOP;\n } else {\n // If dstType is any other type, merge(srcType, dstType) = TOP whatever srcType.\n mergedType = TOP;\n }\n if (mergedType != dstType) {\n dstTypes[dstIndex] = mergedType;\n return true;\n }\n return false;\n }\n\n // -----------------------------------------------------------------------------------------------\n // Frame output methods, to generate StackMapFrame attributes\n // -----------------------------------------------------------------------------------------------\n\n /**\n * Makes the given {@link MethodWriter} visit the input frame of this {@link Frame}. The visit is\n * done with the {@link MethodWriter#visitFrameStart}, {@link MethodWriter#visitAbstractType} and\n * {@link MethodWriter#visitFrameEnd} methods.\n *\n * @param methodWriter the {@link MethodWriter} that should visit the input frame of this {@link\n * Frame}.\n */\n final void accept(final MethodWriter methodWriter) {\n // Compute the number of locals, ignoring TOP types that are just after a LONG or a DOUBLE, and\n // all trailing TOP types.\n int[] localTypes = inputLocals;\n int numLocal = 0;\n int numTrailingTop = 0;\n int i = 0;\n while (i < localTypes.length) {\n int localType = localTypes[i];\n i += (localType == LONG || localType == DOUBLE) ? 2 : 1;\n if (localType == TOP) {\n numTrailingTop++;\n } else {\n numLocal += numTrailingTop + 1;\n numTrailingTop = 0;\n }\n }\n // Compute the stack size, ignoring TOP types that are just after a LONG or a DOUBLE.\n int[] stackTypes = inputStack;\n int numStack = 0;\n i = 0;\n while (i < stackTypes.length) {\n int stackType = stackTypes[i];\n i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1;\n numStack++;\n }\n // Visit the frame and its content.\n int frameIndex = methodWriter.visitFrameStart(owner.bytecodeOffset, numLocal, numStack);\n i = 0;\n while (numLocal-- > 0) {\n int localType = localTypes[i];\n i += (localType == LONG || localType == DOUBLE) ? 2 : 1;\n methodWriter.visitAbstractType(frameIndex++, localType);\n }\n i = 0;\n while (numStack-- > 0) {\n int stackType = stackTypes[i];\n i += (stackType == LONG || stackType == DOUBLE) ? 2 : 1;\n methodWriter.visitAbstractType(frameIndex++, stackType);\n }\n methodWriter.visitFrameEnd();\n }\n//\n// /**\n// * Put the given abstract type in the given ByteVector, using the JVMS verification_type_info\n// * format used in StackMapTable attributes.\n// *\n// * @param symbolTable the type table to use to lookup and store type {@link Symbol}.\n// * @param abstractType an abstract type, restricted to {@link Frame#CONSTANT_KIND}, {@link\n// * Frame#REFERENCE_KIND} or {@link Frame#UNINITIALIZED_KIND} types.\n// * @param output where the abstract type must be put.\n// * @see JVMS\n// * 4.7.4\n// */\n// static void putAbstractType(\n// final SymbolTable symbolTable, final int abstractType, final ByteVector output) {\n// int arrayDimensions = (abstractType & Frame.DIM_MASK) >> DIM_SHIFT;\n// if (arrayDimensions == 0) {\n// int typeValue = abstractType & VALUE_MASK;\n// switch (abstractType & KIND_MASK) {\n// case CONSTANT_KIND:\n// output.putByte(typeValue);\n// break;\n// case REFERENCE_KIND:\n// output\n// .putByte(ITEM_OBJECT)\n// .putShort(symbolTable.addConstantUtf8Reference(/*CONSTANT_CLASS_TAG*/ 7, symbolTable.typeTable[typeValue].value).index);\n// break;\n// case UNINITIALIZED_KIND:\n// output.putByte(ITEM_UNINITIALIZED).putShort((int) symbolTable.typeTable[typeValue].data);\n// break;\n// default:\n// throw new AssertionError();\n// }\n// } else {\n// // Case of an array type, we need to build its descriptor first.\n// StringBuilder typeDescriptor = new StringBuilder();\n// while (arrayDimensions-- > 0) {\n// typeDescriptor.append('[');\n// }\n// if ((abstractType & KIND_MASK) == REFERENCE_KIND) {\n// typeDescriptor\n// .append('L')\n// .append(symbolTable.typeTable[abstractType & VALUE_MASK].value)\n// .append(';');\n// } else {\n// switch (abstractType & VALUE_MASK) {\n// case Frame.ITEM_ASM_BOOLEAN:\n// typeDescriptor.append('Z');\n// break;\n// case Frame.ITEM_ASM_BYTE:\n// typeDescriptor.append('B');\n// break;\n// case Frame.ITEM_ASM_CHAR:\n// typeDescriptor.append('C');\n// break;\n// case Frame.ITEM_ASM_SHORT:\n// typeDescriptor.append('S');\n// break;\n// case Frame.ITEM_INTEGER:\n// typeDescriptor.append('I');\n// break;\n// case Frame.ITEM_FLOAT:\n// typeDescriptor.append('F');\n// break;\n// case Frame.ITEM_LONG:\n// typeDescriptor.append('J');\n// break;\n// case Frame.ITEM_DOUBLE:\n// typeDescriptor.append('D');\n// break;\n// default:\n// throw new AssertionError();\n// }\n// }\n// output\n// .putByte(ITEM_OBJECT)\n// .putShort(symbolTable.addConstantUtf8Reference(/*CONSTANT_CLASS_TAG*/ 7, typeDescriptor.toString()).index);\n// }\n// }\n}\n", "file_name": "Frame.java", "human_label": "Pop different value of type based on the first character of the given descriptor.", "level": "class_runnable", "lineno": "647", "name": "pop", "oracle_context": "{ \"apis\" : \"[charAt, getArgumentsAndReturnSizes]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "com.alibaba.fastjson2.internal.asm", "project": "fastjson2-main" }, { "_id": "636766fb1a6d9265ec0177c3", "all_context": "{ \"class_level\" : \"String CHAR_STRING;\\nString[] CHAR_STRING_ARRAY;\\nCharacter[] CHAR_ARRAY;\\nchar LF;\\nchar CR;\\nCharUtils();\\ntoCharacterObject(String str);\\ntoChar(Character ch);\\ntoChar(Character ch,char defaultValue);\\ntoChar(String str);\\ntoChar(String str,char defaultValue);\\ntoIntValue(char ch);\\ntoIntValue(char ch,int defaultValue);\\ntoIntValue(Character ch);\\ntoIntValue(Character ch,int defaultValue);\\ntoString(char ch);\\ntoString(Character ch);\\nunicodeEscaped(char ch);\\nunicodeEscaped(Character ch);\\nisAscii(char ch);\\nisAsciiPrintable(char ch);\\nisAsciiControl(char ch);\\nisAsciiAlpha(char ch);\\nisAsciiAlphaUpper(char ch);\\nisAsciiAlphaLower(char ch);\\nisAsciiNumeric(char ch);\\nisAsciiAlphanumeric(char ch);\\nisHighSurrogate(char ch);\\nisCharType(Class targetType);\\ntoCharacterObject(char ch);\\n\", \"repo_level\" : \"\" }", "class_name": "CharUtils", "code": "public static boolean isAscii(final char ch){\n return ch < 128;\n}\n", "docstring": "/** \n *

          Checks whether the character is ASCII 7 bit.

           CharUtils.isAscii('a')  = true CharUtils.isAscii('A')  = true CharUtils.isAscii('3')  = true CharUtils.isAscii('-')  = true CharUtils.isAscii('\\n') = true CharUtils.isAscii('©') = false 
          \n * @param ch the character to check\n * @return true if less than 128\n */\n", "end_lineno": "421", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\n/**\n *

          Operations on char primitives and Character objects.

          \n *\n *

          This class tries to handle null input gracefully.\n * An exception will not be thrown for a null input.\n * Each method documents its behaviour in more detail.

          \n *\n *

          #ThreadSafe#

          \n * @author Apache Software Foundation\n * @since 2.1\n * @version $Id: CharUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class CharUtils {\n private static final String CHAR_STRING = //\n \"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\" +//\n \"\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\" + //\n \"\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\" + //\n \"\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\" +//\n \"\\u0020\\u0021\\\"\\u0023\\u0024\\u0025\\u0026\\u0027\" + //\n \"\\u0028\\u0029\\u002a\\u002b\\u002c\\u002d\\u002e\\u002f\" + //\n \"\\u0030\\u0031\\u0032\\u0033\\u0034\\u0035\\u0036\\u0037\" + //\n \"\\u0038\\u0039\\u003a\\u003b\\u003c\\u003d\\u003e\\u003f\" + //\n \"\\u0040\\u0041\\u0042\\u0043\\u0044\\u0045\\u0046\\u0047\" + //\n \"\\u0048\\u0049\\u004a\\u004b\\u004c\\u004d\\u004e\\u004f\" + //\n \"\\u0050\\u0051\\u0052\\u0053\\u0054\\u0055\\u0056\\u0057\" +//\n \"\\u0058\\u0059\\u005a\\u005b\\\\\\u005d\\u005e\\u005f\" + //\n \"\\u0060\\u0061\\u0062\\u0063\\u0064\\u0065\\u0066\\u0067\" +//\n \"\\u0068\\u0069\\u006a\\u006b\\u006c\\u006d\\u006e\\u006f\" +//\n \"\\u0070\\u0071\\u0072\\u0073\\u0074\\u0075\\u0076\\u0077\" +//\n \"\\u0078\\u0079\\u007a\\u007b\\u007c\\u007d\\u007e\\u007f\";\n private static final String[] CHAR_STRING_ARRAY = new String[128];\n private static final Character[] CHAR_ARRAY = new Character[128];\n /**\n * \n linefeed LF ('\\n').\n *\n * @see JLF: Escape Sequences\n * for Character and String Literals\n * @since 2.2\n */\n public static final char LF = '\\n';\n /**\n * carriage return CR ('\\r').\n *\n * @see JLF: Escape Sequences\n * for Character and String Literals\n * @since 2.2\n */\n public static final char CR = '\\r';\n\n static {\n for (int i = 127; i >= 0; i--) {\n CharUtils.CHAR_STRING_ARRAY[i] = CharUtils.CHAR_STRING.substring(i, i + 1);\n CharUtils.CHAR_ARRAY[i] = new Character((char) i);\n }\n }\n\n /**\n *

          CharUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as CharUtils.toString('c');.

          \n *\n *

          This constructor i public to permit tools that require a JavaBean instance\n * to operate.

          \n */\n public CharUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Converts the character to a Character.

          \n *\n *

          For ASCII 7 bit characters, this uses a cache that will return the\n * same Character object each time.

          \n *\n *
          \n     *   CharUtils.toCharacterObject(' ')  = ' '\n     *   CharUtils.toCharacterObject('A')  = 'A'\n     * 
          \n *\n * @param ch the character to convert\n * @return a Character of the specified character\n */\n public static Character toCharacterObject(final char ch) {\n if (ch < CharUtils.CHAR_ARRAY.length) {\n return CharUtils.CHAR_ARRAY[ch];\n }\n return new Character(ch);\n }\n\n /**\n *

          Converts the String to a Character using the first character, returning\n * null for empty Strings.

          \n *\n *

          For ASCII 7 bit characters, this uses a cache that will return the\n * same Character object each time.

          \n *\n *
          \n     *   CharUtils.toCharacterObject(null) = null\n     *   CharUtils.toCharacterObject(\"\")   = null\n     *   CharUtils.toCharacterObject(\"A\")  = 'A'\n     *   CharUtils.toCharacterObject(\"BA\") = 'B'\n     * 
          \n *\n * @param str the character to convert\n * @return the Character value of the first letter of the String\n */\n public static Character toCharacterObject(final String str) {\n if (StringUtils.isEmpty(str)) {\n return null;\n }\n return CharUtils.toCharacterObject(str.charAt(0));\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Converts the Character to a char throwing an exception for null.

          \n *\n *
          \n     *   CharUtils.toChar(null) = IllegalArgumentException\n     *   CharUtils.toChar(' ')  = ' '\n     *   CharUtils.toChar('A')  = 'A'\n     * 
          \n *\n * @param ch the character to convert\n * @return the char value of the Character\n * @throws IllegalArgumentException if the Character is null\n */\n public static char toChar(final Character ch) {\n if (ch == null) {\n throw new IllegalArgumentException(\"The Character must not be null\");\n }\n return ch.charValue();\n }\n\n /**\n *

          Converts the Character to a char handling null.

          \n *\n *
          \n     *   CharUtils.toChar(null, 'X') = 'X'\n     *   CharUtils.toChar(' ', 'X')  = ' '\n     *   CharUtils.toChar('A', 'X')  = 'A'\n     * 
          \n *\n * @param ch the character to convert\n * @param defaultValue the value to use if the Character is null\n * @return the char value of the Character or the default if null\n */\n public static char toChar(final Character ch, final char defaultValue) {\n if (ch == null) {\n return defaultValue;\n }\n return ch.charValue();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Converts the String to a char using the first character, throwing\n * an exception on empty Strings.

          \n *\n *
          \n     *   CharUtils.toChar(null) = IllegalArgumentException\n     *   CharUtils.toChar(\"\")   = IllegalArgumentException\n     *   CharUtils.toChar(\"A\")  = 'A'\n     *   CharUtils.toChar(\"BA\") = 'B'\n     * 
          \n *\n * @param str the character to convert\n * @return the char value of the first letter of the String\n * @throws IllegalArgumentException if the String is empty\n */\n public static char toChar(final String str) {\n if (StringUtils.isEmpty(str)) {\n throw new IllegalArgumentException(\"The String must not be empty\");\n }\n return str.charAt(0);\n }\n\n /**\n *

          Converts the String to a char using the first character, defaulting\n * the value on empty Strings.

          \n *\n *
          \n     *   CharUtils.toChar(null, 'X') = 'X'\n     *   CharUtils.toChar(\"\", 'X')   = 'X'\n     *   CharUtils.toChar(\"A\", 'X')  = 'A'\n     *   CharUtils.toChar(\"BA\", 'X') = 'B'\n     * 
          \n *\n * @param str the character to convert\n * @param defaultValue the value to use if the Character is null\n * @return the char value of the first letter of the String or the default if null\n */\n public static char toChar(final String str, final char defaultValue) {\n if (StringUtils.isEmpty(str)) {\n return defaultValue;\n }\n return str.charAt(0);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

          \n *\n *

          This method coverts the char '1' to the int 1 and so on.

          \n *\n *
          \n     *   CharUtils.toIntValue('3')  = 3\n     *   CharUtils.toIntValue('A')  = IllegalArgumentException\n     * 
          \n *\n * @param ch the character to convert\n * @return the int value of the character\n * @throws IllegalArgumentException if the character is not ASCII numeric\n */\n public static int toIntValue(final char ch) {\n if (CharUtils.isAsciiNumeric(ch) == false) {\n throw new IllegalArgumentException(\"The character \" + ch + \" is not in the range '0' - '9'\");\n }\n return ch - 48;\n }\n\n /**\n *

          Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

          \n *\n *

          This method coverts the char '1' to the int 1 and so on.

          \n *\n *
          \n     *   CharUtils.toIntValue('3', -1)  = 3\n     *   CharUtils.toIntValue('A', -1)  = -1\n     * 
          \n *\n * @param ch the character to convert\n * @param defaultValue the default value to use if the character is not numeric\n * @return the int value of the character\n */\n public static int toIntValue(final char ch, final int defaultValue) {\n if (CharUtils.isAsciiNumeric(ch) == false) {\n return defaultValue;\n }\n return ch - 48;\n }\n\n /**\n *

          Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

          \n *\n *

          This method coverts the char '1' to the int 1 and so on.

          \n *\n *
          \n     *   CharUtils.toIntValue(null) = IllegalArgumentException\n     *   CharUtils.toIntValue('3')  = 3\n     *   CharUtils.toIntValue('A')  = IllegalArgumentException\n     * 
          \n *\n * @param ch the character to convert, not null\n * @return the int value of the character\n * @throws IllegalArgumentException if the Character is not ASCII numeric or is null\n */\n public static int toIntValue(final Character ch) {\n if (ch == null) {\n throw new IllegalArgumentException(\"The character must not be null\");\n }\n return CharUtils.toIntValue(ch.charValue());\n }\n\n /**\n *

          Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

          \n *\n *

          This method coverts the char '1' to the int 1 and so on.

          \n *\n *
          \n     *   CharUtils.toIntValue(null, -1) = -1\n     *   CharUtils.toIntValue('3', -1)  = 3\n     *   CharUtils.toIntValue('A', -1)  = -1\n     * 
          \n *\n * @param ch the character to convert\n * @param defaultValue the default value to use if the character is not numeric\n * @return the int value of the character\n */\n public static int toIntValue(final Character ch, final int defaultValue) {\n if (ch == null) {\n return defaultValue;\n }\n return CharUtils.toIntValue(ch.charValue(), defaultValue);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Converts the character to a String that contains the one character.

          \n *\n *

          For ASCII 7 bit characters, this uses a cache that will return the\n * same String object each time.

          \n *\n *
          \n     *   CharUtils.toString(' ')  = \" \"\n     *   CharUtils.toString('A')  = \"A\"\n     * 
          \n *\n * @param ch the character to convert\n * @return a String containing the one specified character\n */\n public static String toString(final char ch) {\n if (ch < 128) {\n return CharUtils.CHAR_STRING_ARRAY[ch];\n }\n return new String(new char[] { ch });\n }\n\n /**\n *

          Converts the character to a String that contains the one character.

          \n *\n *

          For ASCII 7 bit characters, this uses a cache that will return the\n * same String object each time.

          \n *\n *

          If null is passed in, null will be returned.

          \n *\n *
          \n     *   CharUtils.toString(null) = null\n     *   CharUtils.toString(' ')  = \" \"\n     *   CharUtils.toString('A')  = \"A\"\n     * 
          \n *\n * @param ch the character to convert\n * @return a String containing the one specified character\n */\n public static String toString(final Character ch) {\n if (ch == null) {\n return null;\n }\n return CharUtils.toString(ch.charValue());\n }\n //--------------------------------------------------------------------------\n\n /**\n *

          Converts the string to the unicode format '\\u0020'.

          \n *\n *

          This format is the Java source code format.

          \n *\n *
          \n     *   CharUtils.unicodeEscaped(' ') = \"\\u0020\"\n     *   CharUtils.unicodeEscaped('A') = \"\\u0041\"\n     * 
          \n *\n * @param ch the character to convert\n * @return the escaped unicode string\n */\n public static String unicodeEscaped(final char ch) {\n if (ch < 0x10) {\n return \"\\\\u000\" + Integer.toHexString(ch);\n } else if (ch < 0x100) {\n return \"\\\\u00\" + Integer.toHexString(ch);\n } else if (ch < 0x1000) {\n return \"\\\\u0\" + Integer.toHexString(ch);\n }\n return \"\\\\u\" + Integer.toHexString(ch);\n }\n\n /**\n *

          Converts the string to the unicode format '\\u0020'.

          \n *\n *

          This format is the Java source code format.

          \n *\n *

          If null is passed in, null will be returned.

          \n *\n *
          \n     *   CharUtils.unicodeEscaped(null) = null\n     *   CharUtils.unicodeEscaped(' ')  = \"\\u0020\"\n     *   CharUtils.unicodeEscaped('A')  = \"\\u0041\"\n     * 
          \n *\n * @param ch the character to convert, may be null\n * @return the escaped unicode string, null if null input\n */\n public static String unicodeEscaped(final Character ch) {\n if (ch == null) {\n return null;\n }\n return CharUtils.unicodeEscaped(ch.charValue());\n }\n //--------------------------------------------------------------------------\n\n /**\n *

          Checks whether the character is ASCII 7 bit.

          \n *\n *
          \n     *   CharUtils.isAscii('a')  = true\n     *   CharUtils.isAscii('A')  = true\n     *   CharUtils.isAscii('3')  = true\n     *   CharUtils.isAscii('-')  = true\n     *   CharUtils.isAscii('\\n') = true\n     *   CharUtils.isAscii('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if less than 128\n */\n public static boolean isAscii(final char ch) {\n return ch < 128;\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit printable.

          \n *\n *
          \n     *   CharUtils.isAsciiPrintable('a')  = true\n     *   CharUtils.isAsciiPrintable('A')  = true\n     *   CharUtils.isAsciiPrintable('3')  = true\n     *   CharUtils.isAsciiPrintable('-')  = true\n     *   CharUtils.isAsciiPrintable('\\n') = false\n     *   CharUtils.isAsciiPrintable('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if between 32 and 126 inclusive\n */\n public static boolean isAsciiPrintable(final char ch) {\n return ch >= 32 && ch < 127;\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit control.

          \n *\n *
          \n     *   CharUtils.isAsciiControl('a')  = false\n     *   CharUtils.isAsciiControl('A')  = false\n     *   CharUtils.isAsciiControl('3')  = false\n     *   CharUtils.isAsciiControl('-')  = false\n     *   CharUtils.isAsciiControl('\\n') = true\n     *   CharUtils.isAsciiControl('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if less than 32 or equals 127\n */\n public static boolean isAsciiControl(final char ch) {\n return ch < 32 || ch == 127;\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit alphabetic.

          \n *\n *
          \n     *   CharUtils.isAsciiAlpha('a')  = true\n     *   CharUtils.isAsciiAlpha('A')  = true\n     *   CharUtils.isAsciiAlpha('3')  = false\n     *   CharUtils.isAsciiAlpha('-')  = false\n     *   CharUtils.isAsciiAlpha('\\n') = false\n     *   CharUtils.isAsciiAlpha('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if between 65 and 90 or 97 and 122 inclusive\n */\n public static boolean isAsciiAlpha(final char ch) {\n return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z';\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit alphabetic upper case.

          \n *\n *
          \n     *   CharUtils.isAsciiAlphaUpper('a')  = false\n     *   CharUtils.isAsciiAlphaUpper('A')  = true\n     *   CharUtils.isAsciiAlphaUpper('3')  = false\n     *   CharUtils.isAsciiAlphaUpper('-')  = false\n     *   CharUtils.isAsciiAlphaUpper('\\n') = false\n     *   CharUtils.isAsciiAlphaUpper('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if between 65 and 90 inclusive\n */\n public static boolean isAsciiAlphaUpper(final char ch) {\n return ch >= 'A' && ch <= 'Z';\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit alphabetic lower case.

          \n *\n *
          \n     *   CharUtils.isAsciiAlphaLower('a')  = true\n     *   CharUtils.isAsciiAlphaLower('A')  = false\n     *   CharUtils.isAsciiAlphaLower('3')  = false\n     *   CharUtils.isAsciiAlphaLower('-')  = false\n     *   CharUtils.isAsciiAlphaLower('\\n') = false\n     *   CharUtils.isAsciiAlphaLower('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if between 97 and 122 inclusive\n */\n public static boolean isAsciiAlphaLower(final char ch) {\n return ch >= 'a' && ch <= 'z';\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit numeric.

          \n *\n *
          \n     *   CharUtils.isAsciiNumeric('a')  = false\n     *   CharUtils.isAsciiNumeric('A')  = false\n     *   CharUtils.isAsciiNumeric('3')  = true\n     *   CharUtils.isAsciiNumeric('-')  = false\n     *   CharUtils.isAsciiNumeric('\\n') = false\n     *   CharUtils.isAsciiNumeric('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if between 48 and 57 inclusive\n */\n public static boolean isAsciiNumeric(final char ch) {\n return ch >= '0' && ch <= '9';\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit numeric.

          \n *\n *
          \n     *   CharUtils.isAsciiAlphanumeric('a')  = true\n     *   CharUtils.isAsciiAlphanumeric('A')  = true\n     *   CharUtils.isAsciiAlphanumeric('3')  = true\n     *   CharUtils.isAsciiAlphanumeric('-')  = false\n     *   CharUtils.isAsciiAlphanumeric('\\n') = false\n     *   CharUtils.isAsciiAlphanumeric('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive\n */\n public static boolean isAsciiAlphanumeric(final char ch) {\n return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9';\n }\n // ----------------- Following code copied from Apache Harmony (Character class)\n\n /**\n * Indicates whether {@code ch} is a high- (or leading-) surrogate code unit\n * that is used for representing supplementary characters in UTF-16\n * encoding.\n *\n * @param ch\n * the character to test.\n * @return {@code true} if {@code ch} is a high-surrogate code unit;\n * {@code false} otherwise.\n */\n static boolean isHighSurrogate(final char ch) {\n return '\\uD800' <= ch && '\\uDBFF' >= ch;\n }\n\n //\n public static boolean isCharType(Class targetType) {\n return targetType.equals(Character.class) || targetType.equals(Character.TYPE);\n }\n}\n", "file_name": "CharUtils.java", "human_label": "Return true if the given character is a ASCII seven bit character,otherwise return false.", "level": "self_contained", "lineno": "404", "name": "isAscii", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636767581a6d9265ec017fb4", "all_context": "{ \"class_level\" : \"import org.jgrapht.alg.util.Pair;\\nimport java.util.*;\\nimport java.util.function.Function;\\nRandom rng;\\nList> lowerBounds;\\nList> upperBounds;\\nDistributor();\\nDistributor(long seed);\\nDistributor(Random rng);\\naddLowerBound(Function lowerBound);\\ncomputeLowerBounds(List keys);\\ncomputeUpperBounds(List keys);\\ncomputeSuffixSum(List bounds);\\ngetDistribution(List keys,int valueNum);\\naddUpperBound(Function upperBound);\\n\", \"repo_level\" : \"public interface Pair {public A getFirst();\\npublic B getSecond();\\npublic void setFirst(A f);\\npublic void setSecond(B s);\\npublic boolean hasElement(E e);\\npublic String toString();\\npublic boolean equals(Object o);\\npublic int hashCode();\\nstatic Pair of(A a,B b);\\n }\\n\" }", "class_name": "Distributor", "code": "private List computeUpperBounds(List keys){\n List keyUpperBounds=new ArrayList<>(keys.size());\n for ( K key : keys) {\n int upperBound=Integer.MAX_VALUE;\n for ( Function upperBoundFunction : upperBounds) {\n upperBound=Math.min(upperBound,upperBoundFunction.apply(key));\n }\n keyUpperBounds.add(upperBound);\n }\n return keyUpperBounds;\n}\n", "docstring": "/** \n * Finds a minimum lower bound for every key.\n * @param keys a list of keys.\n * @return the computed key upper bound.\n */\n", "end_lineno": "140", "file_content": "/*\n * (C) Copyright 2020-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.generate.netgen;\n\nimport org.jgrapht.alg.util.Pair;\n\nimport java.util.*;\nimport java.util.function.Function;\n\n/**\n * Distributes value units among keys given lower and upper bound constraints.\n *

          \n * Let's define a set of elements $\\{k_1, k_2, \\dots, k_n\\}$. For every element a set of lower\n * bounds $\\{l_1, l_2, \\dots, l_t\\}$ and upper bounds $\\{u_1, u_2, \\dots, u_p\\}$ is specified. The\n * problem is to randomly distribute a number of abstract value units $V$ among keys such that the\n * lower bound and upper bound constraints are satisfied. This class solves this problem.\n *\n * @param the element type.\n * @author Timofey Chudakov\n * @see NetworkGenerator\n */\npublic class Distributor\n{\n /**\n * Random number generator used by this distributor.\n */\n private final Random rng;\n /**\n * Lower bounds.\n */\n private final List> lowerBounds;\n /**\n * Upper bounds.\n */\n private final List> upperBounds;\n\n /**\n * Creates a Distributor using random seed.\n */\n public Distributor()\n {\n this(System.nanoTime());\n }\n\n /**\n * Creates a distributor using the specified {@code seed}.\n *\n * @param seed the seed for the random number generator.\n */\n public Distributor(long seed)\n {\n this(new Random(seed));\n }\n\n /**\n * Creates a distributor which uses the random number generatow {@code rng}.\n *\n * @param rng a random number generator to use.\n */\n public Distributor(Random rng)\n {\n this.rng = rng;\n this.lowerBounds = new ArrayList<>();\n this.upperBounds = new ArrayList<>();\n }\n\n /**\n * Adds an upper bounding function. This function must be defined for all keys.\n *\n * @param upperBound an upper bound function.\n */\n public void addUpperBound(Function upperBound)\n {\n this.upperBounds.add(upperBound);\n }\n\n /**\n * Adds a lower bound function. This function must be defined for all keys.\n *\n * @param lowerBound a lower bound function.\n */\n public void addLowerBound(Function lowerBound)\n {\n this.lowerBounds.add(lowerBound);\n }\n\n /**\n * Finds a maximum lower bound for every key.\n *\n * @param keys list of keys.\n * @return the computed key lower bounds.\n */\n private List computeLowerBounds(List keys)\n {\n List keyLowerBounds = new ArrayList<>(keys.size());\n for (K key : keys) {\n int lowerBound = 0;\n for (Function lowerBoundFunction : lowerBounds) {\n lowerBound = Math.max(lowerBound, lowerBoundFunction.apply(key));\n }\n keyLowerBounds.add(lowerBound);\n }\n\n return keyLowerBounds;\n }\n\n /**\n * Finds a minimum lower bound for every key.\n *\n * @param keys a list of keys.\n * @return the computed key upper bound.\n */\n private List computeUpperBounds(List keys)\n {\n List keyUpperBounds = new ArrayList<>(keys.size());\n for (K key : keys) {\n int upperBound = Integer.MAX_VALUE;\n for (Function upperBoundFunction : upperBounds) {\n upperBound = Math.min(upperBound, upperBoundFunction.apply(key));\n }\n keyUpperBounds.add(upperBound);\n }\n\n return keyUpperBounds;\n }\n\n /**\n * Computes a suffix sum of the {@code bounds}. Returns computed suffix sum and the sum of all\n * elements in the {@code bounds list}.\n *\n * @param bounds list of integers.\n * @return computed pair of suffix sum list and a sum of all elements.\n */\n private Pair, Long> computeSuffixSum(List bounds)\n {\n List suffixSum = new ArrayList<>(Collections.nCopies(bounds.size(), 0));\n long sum = 0;\n for (int i = bounds.size() - 1; i >= 0; i--) {\n suffixSum.set(i, (int) Math.min(Integer.MAX_VALUE, sum));\n sum += bounds.get(i);\n }\n\n return Pair.of(suffixSum, sum);\n }\n\n /**\n * Computes and returns a value distribution for the list of keys. The resulting distribution\n * will satisfy the (possibly empty) sets of lower and upper bound constraints. Distributed\n * values will be in the same order as the keys in the key list.\n *\n * @param keys the list of keys.\n * @param valueNum the number of abstract value units to distribute.\n * @return the computed value distribution.\n */\n public List getDistribution(List keys, final int valueNum)\n {\n List keyLowerBounds = computeLowerBounds(keys);\n List keyUpperBounds = computeUpperBounds(keys);\n\n Pair, Long> lbSufSumP = computeSuffixSum(keyLowerBounds);\n Pair, Long> ubSufSumP = computeSuffixSum(keyUpperBounds);\n\n List lbSufSum = lbSufSumP.getFirst();\n List ubSufSum = ubSufSumP.getFirst();\n\n long lbSum = lbSufSumP.getSecond();\n long ubSum = ubSufSumP.getSecond();\n\n if (lbSum > valueNum) {\n throw new IllegalArgumentException(\n \"Can't distribute values among keys: the sum of lower bounds is greater than the number of values\");\n } else if (ubSum < valueNum) {\n throw new IllegalArgumentException(\n \"Can't distribute values among keys: the sum of upper bounds is smaller than the number of values\");\n }\n\n int remainingValues = valueNum;\n List resultingDistribution = new ArrayList<>();\n for (int i = 0; i < keyLowerBounds.size(); i++) {\n int lowerBound = keyLowerBounds.get(i);\n int upperBound = keyUpperBounds.get(i);\n\n int valueNumUpperBound = remainingValues - lbSufSum.get(i);\n int valueNumLowerBound = remainingValues - ubSufSum.get(i);\n\n lowerBound = Math.max(lowerBound, valueNumLowerBound);\n upperBound = Math.min(upperBound, valueNumUpperBound);\n\n if (lowerBound > upperBound) {\n throw new IllegalArgumentException(\n \"Infeasible bound specified for the key: \" + keys.get(i));\n }\n\n int allocatedValues = rng.nextInt(upperBound - lowerBound + 1) + lowerBound;\n resultingDistribution.add(allocatedValues);\n remainingValues -= allocatedValues;\n }\n\n return resultingDistribution;\n }\n\n}\n", "file_name": "Distributor.java", "human_label": "The type of key has several upper bounds conducted by different function,this function will return a list of the minimum upper bound of each key in the given list.", "level": "class_runnable", "lineno": "122", "name": "computeUpperBounds", "oracle_context": "{ \"apis\" : \"[size, min, apply, add]\", \"classes\" : \"[List, Integer]\", \"vars\" : \"[MAX_VALUE, upperBounds]\" }", "package": "org.jgrapht.generate.netgen", "project": "jgrapht-master" }, { "_id": "636766801a6d9265ec017487", "all_context": "{ \"class_level\" : \"import java.io.UnsupportedEncodingException;\\nimport java.net.URI;\\nimport java.net.URLDecoder;\\nimport java.nio.Buffer;\\nimport java.nio.ByteBuffer;\\nimport java.nio.CharBuffer;\\nimport java.nio.charset.Charset;\\nimport java.nio.charset.StandardCharsets;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collections;\\nimport java.util.HashMap;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Map;\\nchar[] HEX_DIGITS;\\nString[] SCHEME;\\nString[] UNRESERVED;\\nString[] SUB_DELIMS;\\nboolean[][] ENCODING_TABLES;\\nCharset UTF_8_CHARSET;\\nPathSegmentImpl EMPTY_PATH_SEGMENT;\\nString path;\\nMap matrixParameters;\\nint[] HEX_TABLE;\\nUriComponent();\\nvalidate(String s,Type t,boolean template);\\nvalid(String s,Type t);\\nvalid(String s,Type t,boolean template);\\n_valid(String s,Type t,boolean template);\\ncontextualEncode(String s,Type t);\\ncontextualEncode(String s,Type t,boolean template);\\nencode(String s,Type t);\\nencode(String s,Type t,boolean template);\\nencodeTemplateNames(String s);\\n_encode(String s,Type t,boolean template,boolean contextualEncode);\\nappendPercentEncodedOctet(StringBuilder sb,int b);\\nappendUTF8EncodedCharacter(StringBuilder sb,char c);\\ncreatingEncodingTables();\\ncreatingEncodingTable(List allowed);\\ndecode(String s,Type t);\\ndecodeQuery(URI u,boolean decode);\\ndecodeQuery(String q,boolean decode);\\ndecodeQueryParam(Map params,String param,boolean decode);\\nPathSegmentImpl(String path,boolean decode);\\nPathSegmentImpl(String path,boolean decode,Map matrixParameters);\\ngetPath();\\ngetMatrixParameters();\\ndecodePath(URI u,boolean decode);\\ndecodePath(String path,boolean decode);\\ndecodePathSegment(List segments,String segment,boolean decode);\\ndecodeMatrix(String pathSegment,boolean decode);\\ndecodeMatrixParam(Map params,String param,boolean decode);\\ndecode(String s,int n);\\ndecodeQueryParam(String s,int n);\\ndecodeHost(String s,int n);\\ndecodePercentEncodedOctets(String s,int i,ByteBuffer bb);\\ndecodeOctets(int i,ByteBuffer bb,StringBuilder sb);\\ndecodeHex(String s,int i);\\ncreateHexTable();\\ndecodeHex(char c);\\nisHexCharacter(char c);\\nvalidate(String s,Type t);\\n\", \"repo_level\" : \"\" }", "class_name": "UriComponent", "code": "public static String encodeTemplateNames(String s){\n int i=s.indexOf('{');\n if (i != -1) s=s.replace(\"{\",\"%7B\");\n i=s.indexOf('}');\n if (i != -1) s=s.replace(\"}\",\"%7D\");\n return s;\n}\n", "docstring": "/** \n * Encodes a string with template parameters names present, specifically the characters '{' and '}' will be percent-encoded.\n * @param s the string with zero or more template parameters names\n * @return the string with encoded template parameters names.\n */\n", "end_lineno": "288", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n/*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.\n *\n * Copyright (c) 2010-2018 Oracle and/or its affiliates. All rights reserved.\n *\n * The contents of this file are subject to the terms of either the GNU\n * General Public License Version 2 only (\"GPL\") or the Common Development\n * and Distribution License(\"CDDL\") (collectively, the \"License\"). You\n * may not use this file except in compliance with the License. You can\n * obtain a copy of the License at\n * http://glassfish.java.net/public/CDDL+GPL_1_1.html\n * or packager/legal/LICENSE.txt. See the License for the specific\n * language governing permissions and limitations under the License.\n *\n * When distributing the software, include this License Header Notice in each\n * file and include the License file at packager/legal/LICENSE.txt.\n *\n * GPL Classpath Exception:\n * Oracle designates this particular file as subject to the \"Classpath\"\n * exception as provided by Oracle in the GPL Version 2 section of the License\n * file that accompanied this code.\n *\n * Modifications:\n * If applicable, add the following below the License Header, with the fields\n * enclosed by brackets [] replaced by your own identifying information:\n * \"Portions Copyright [year] [name of copyright owner]\"\n *\n * Contributor(s):\n * If you wish your version of this file to be governed by only the CDDL or\n * only the GPL Version 2, indicate your decision by adding \"[Contributor]\n * elects to include this software in this distribution under the [CDDL or GPL\n * Version 2] license.\" If you don't indicate a single choice of license, a\n * recipient has the option to distribute your version of this file under\n * either the CDDL, the GPL Version 2 or to extend the choice of license to\n * its licensees as provided above. However, if you add GPL Version 2 code\n * and therefore, elected the GPL Version 2 license, then the option applies\n * only if the new code is made subject to such option by the copyright\n * holder.\n */\npackage org.atmosphere.util.uri;\n\nimport java.io.UnsupportedEncodingException;\nimport java.net.URI;\nimport java.net.URLDecoder;\nimport java.nio.Buffer;\nimport java.nio.ByteBuffer;\nimport java.nio.CharBuffer;\nimport java.nio.charset.Charset;\nimport java.nio.charset.StandardCharsets;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Utility class for validating, encoding and decoding components\n * of a URI.\n *\n * @author Paul.Sandoz@Sun.Com\n */\npublic class UriComponent {\n\n // TODO rewrite to use masks and not lookup tables\n /**\n * The URI component type.\n */\n public enum Type {\n\n /**\n * ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\" characters\n */\n UNRESERVED,\n /**\n * The URI scheme component type.\n */\n SCHEME,\n /**\n * The URI authority component type.\n */\n AUTHORITY,\n /**\n * The URI user info component type.\n */\n USER_INFO,\n /**\n * The URI host component type.\n */\n HOST,\n /**\n * The URI port component type.\n */\n PORT,\n /**\n * The URI path component type.\n */\n PATH,\n /**\n * The URI path component type that is a path segment.\n */\n PATH_SEGMENT,\n /**\n * The URI path component type that is a matrix parameter.\n */\n MATRIX_PARAM,\n /**\n * The URI query component type.\n */\n QUERY,\n /**\n * The URI query component type that is a query parameter.\n */\n QUERY_PARAM,\n /**\n * The URI fragment component type.\n */\n FRAGMENT,\n }\n\n private UriComponent() {\n }\n\n /**\n * Validates the legal characters of a percent-encoded string that \n * represents a URI component type.\n *\n * @param s the encoded string.\n * @param t the URI compontent type identifying the legal characters.\n * @throws IllegalArgumentException if the encoded string contains illegal\n * characters.\n */\n public static void validate(String s, Type t) {\n validate(s, t, false);\n }\n\n /**\n * Validates the legal characters of a percent-encoded string that \n * represents a URI component type.\n *\n * @param s the encoded string.\n * @param t the URI compontent type identifying the legal characters.\n * @param template true if the encoded string contains URI template variables\n * @throws IllegalArgumentException if the encoded string contains illegal\n * characters.\n */\n public static void validate(String s, Type t, boolean template) {\n int i = _valid(s, t, template);\n if (i > -1) // TODO localize\n {\n throw new IllegalArgumentException(\"The string '\" + s +\n \"' for the URI component \" + t +\n \" contains an invalid character, '\" + s.charAt(i) + \"', at index \" + i);\n }\n }\n\n /**\n * Validates the legal characters of a percent-encoded string that \n * represents a URI component type.\n *\n * @param s the encoded string.\n * @param t the URI compontent type identifying the legal characters.\n * @return true if the encoded string is valid, otherwise false.\n */\n public static boolean valid(String s, Type t) {\n return valid(s, t, false);\n }\n\n /**\n * Validates the legal characters of a percent-encoded string that \n * represents a URI component type.\n *\n * @param s the encoded string.\n * @param t the URI compontent type identifying the legal characters.\n * @param template true if the encoded string contains URI template variables\n * @return true if the encoded string is valid, otherwise false.\n */\n public static boolean valid(String s, Type t, boolean template) {\n return _valid(s, t, template) == -1;\n }\n\n private static int _valid(String s, Type t, boolean template) {\n boolean[] table = ENCODING_TABLES[t.ordinal()];\n\n for (int i = 0; i < s.length(); i++) {\n final char c = s.charAt(i);\n if (c >= 0x80 || (c != '%' && !table[c])) {\n if (!template || (c != '{' && c != '}')) {\n return i;\n }\n }\n }\n return -1;\n }\n\n /**\n * Contextually encodes the characters of string that are either non-ASCII\n * characters or are ASCII characters that must be percent-encoded using the\n * UTF-8 encoding. Percent-encoded characters will be recognized and not\n * double encoded.\n *\n * @param s the string to be encoded.\n * @param t the URI compontent type identifying the ASCII characters that \n * must be percent-encoded.\n * @return the encoded string.\n */\n public static String contextualEncode(String s, Type t) {\n return _encode(s, t, false, true);\n }\n\n /**\n * Contextually encodes the characters of string that are either non-ASCII\n * characters or are ASCII characters that must be percent-encoded using the\n * UTF-8 encoding. Percent-encoded characters will be recognized and not\n * double encoded.\n *\n * @param s the string to be encoded.\n * @param t the URI compontent type identifying the ASCII characters that \n * must be percent-encoded.\n * @param template true if the encoded string contains URI template variables\n * @return the encoded string.\n */\n public static String contextualEncode(String s, Type t, boolean template) {\n return _encode(s, t, template, true);\n }\n\n /**\n * Encodes the characters of string that are either non-ASCII characters \n * or are ASCII characters that must be percent-encoded using the \n * UTF-8 encoding.\n *\n * @param s the string to be encoded.\n * @param t the URI compontent type identifying the ASCII characters that \n * must be percent-encoded.\n * @return the encoded string.\n */\n public static String encode(String s, Type t) {\n return _encode(s, t, false, false);\n }\n\n /**\n * Encodes the characters of string that are either non-ASCII characters \n * or are ASCII characters that must be percent-encoded using the \n * UTF-8 encoding.\n *\n * @param s the string to be encoded.\n * @param t the URI compontent type identifying the ASCII characters that \n * must be percent-encoded.\n * @param template true if the encoded string contains URI template variables\n * @return the encoded string.\n */\n public static String encode(String s, Type t, boolean template) {\n return _encode(s, t, template, false);\n }\n\n /**\n * Encodes a string with template parameters names present, specifically the\n * characters '{' and '}' will be percent-encoded.\n * \n * @param s the string with zero or more template parameters names\n * @return the string with encoded template parameters names.\n */\n public static String encodeTemplateNames(String s) {\n int i = s.indexOf('{');\n if (i != -1)\n s = s.replace(\"{\", \"%7B\");\n i = s.indexOf('}');\n if (i != -1)\n s = s.replace(\"}\", \"%7D\");\n\n return s;\n }\n\n private static String _encode(String s, Type t, boolean template, boolean contextualEncode) {\n final boolean[] table = ENCODING_TABLES[t.ordinal()];\n\n StringBuilder sb = null;\n for (int i = 0; i < s.length(); i++) {\n final char c = s.charAt(i);\n if (c < 0x80 && table[c]) {\n if (sb != null) sb.append(c);\n } else {\n if (template && (c == '{' || c == '}')) {\n if (sb != null) sb.append(c);\n continue;\n } else if (contextualEncode) {\n if (c == '%' && i + 2 < s.length()) {\n if (isHexCharacter(s.charAt(i + 1)) &&\n isHexCharacter(s.charAt(i + 2))) {\n if (sb != null)\n sb.append('%').append(s.charAt(i + 1)).append(s.charAt(i + 2));\n i += 2;\n continue;\n }\n }\n }\n\n if (sb == null) {\n sb = new StringBuilder();\n sb.append(s, 0, i);\n }\n\n if (c < 0x80) {\n if (c == ' ' && (t == Type.QUERY_PARAM)) {\n sb.append('+');\n } else {\n appendPercentEncodedOctet(sb, c);\n }\n } else {\n appendUTF8EncodedCharacter(sb, c);\n }\n }\n }\n\n return (sb == null) ? s : sb.toString();\n }\n private final static char[] HEX_DIGITS = {\n '0', '1', '2', '3', '4', '5', '6', '7',\n '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'\n };\n\n private static void appendPercentEncodedOctet(StringBuilder sb, int b) {\n sb.append('%');\n sb.append(HEX_DIGITS[b >> 4]);\n sb.append(HEX_DIGITS[b & 0x0F]);\n }\n\n private static void appendUTF8EncodedCharacter(StringBuilder sb, char c) {\n final ByteBuffer bb = UTF_8_CHARSET.encode(\"\" + c);\n\n while (bb.hasRemaining()) {\n appendPercentEncodedOctet(sb, bb.get() & 0xFF);\n }\n }\n private static final String[] SCHEME = {\"0-9\", \"A-Z\", \"a-z\", \"+\", \"-\", \".\"};\n private static final String[] UNRESERVED = {\"0-9\", \"A-Z\", \"a-z\", \"-\", \".\", \"_\", \"~\"};\n private static final String[] SUB_DELIMS = {\"!\", \"$\", \"&\", \"'\", \"(\", \")\", \"*\", \"+\", \",\", \";\", \"=\"};\n private static final boolean[][] ENCODING_TABLES = creatingEncodingTables();\n\n private static boolean[][] creatingEncodingTables() {\n boolean[][] tables = new boolean[Type.values().length][];\n\n List l = new ArrayList<>(Arrays.asList(SCHEME));\n tables[Type.SCHEME.ordinal()] = creatingEncodingTable(l);\n\n l.clear();\n\n l.addAll(Arrays.asList(UNRESERVED));\n tables[Type.UNRESERVED.ordinal()] = creatingEncodingTable(l);\n\n l.addAll(Arrays.asList(SUB_DELIMS));\n\n tables[Type.HOST.ordinal()] = creatingEncodingTable(l);\n\n tables[Type.PORT.ordinal()] = creatingEncodingTable(Collections.singletonList(\"0-9\"));\n\n l.add(\":\");\n\n tables[Type.USER_INFO.ordinal()] = creatingEncodingTable(l);\n\n l.add(\"@\");\n\n tables[Type.AUTHORITY.ordinal()] = creatingEncodingTable(l);\n\n tables[Type.PATH_SEGMENT.ordinal()] = creatingEncodingTable(l);\n tables[Type.PATH_SEGMENT.ordinal()][';'] = false;\n\n tables[Type.MATRIX_PARAM.ordinal()] = tables[Type.PATH_SEGMENT.ordinal()].clone();\n tables[Type.MATRIX_PARAM.ordinal()]['='] = false;\n\n l.add(\"/\");\n\n tables[Type.PATH.ordinal()] = creatingEncodingTable(l);\n\n l.add(\"?\");\n\n tables[Type.QUERY.ordinal()] = creatingEncodingTable(l);\n\n tables[Type.FRAGMENT.ordinal()] = tables[Type.QUERY.ordinal()];\n\n tables[Type.QUERY_PARAM.ordinal()] = creatingEncodingTable(l);\n tables[Type.QUERY_PARAM.ordinal()]['='] = false;\n tables[Type.QUERY_PARAM.ordinal()]['+'] = false;\n tables[Type.QUERY_PARAM.ordinal()]['&'] = false;\n\n return tables;\n }\n\n private static boolean[] creatingEncodingTable(List allowed) {\n boolean[] table = new boolean[0x80];\n for (String range : allowed) {\n if (range.length() == 1) {\n table[range.charAt(0)] = true;\n } else if (range.length() == 3 && range.charAt(1) == '-') {\n for (int i = range.charAt(0); i <= range.charAt(2); i++) {\n table[i] = true;\n }\n }\n }\n\n return table;\n }\n private static final Charset UTF_8_CHARSET = StandardCharsets.UTF_8;\n\n /**\n * Decodes characters of a string that are percent-encoded octets using \n * UTF-8 decoding (if needed).\n *

          \n * It is assumed that the string is valid according to an (unspecified) URI \n * component type. If a sequence of contiguous percent-encoded octets is \n * not a valid UTF-8 character then the octets are replaced with '\\uFFFD'.\n *

          \n * If the URI component is of type HOST then any \"%\" found between \"[]\" is \n * left alone. It is an IPv6 literal with a scope_id.\n *

          \n * If the URI component is of type QUERY_PARAM then any \"+\" is decoded as\n * as ' '.\n *

          \n * @param s the string to be decoded.\n * @param t the URI component type, may be null.\n * @return the decoded string.\n * @throws IllegalArgumentException if a malformed percent-encoded octet is\n * detected\n */\n public static String decode(String s, Type t) {\n if (s == null) {\n throw new IllegalArgumentException();\n }\n\n final int n = s.length();\n if (n == 0) {\n return s;\n }\n\n // If there are no percent-escaped octets\n if (s.indexOf('%') < 0) {\n // If there are no '+' characters for query param\n if (t == Type.QUERY_PARAM) {\n if (s.indexOf('+') < 0) {\n return s;\n }\n } else {\n return s;\n }\n } else {\n // Malformed percent-escaped octet at the end\n if (n < 2) // TODO localize\n {\n throw new IllegalArgumentException(\"Malformed percent-encoded octet at index 1\");\n }\n\n // Malformed percent-escaped octet at the end\n if (s.charAt(n - 2) == '%') // TODO localize\n {\n throw new IllegalArgumentException(\"Malformed percent-encoded octet at index \" + (n - 2));\n }\n }\n\n if (t == null)\n return decode(s, n);\n \n switch (t) {\n case HOST :\n return decodeHost(s, n);\n case QUERY_PARAM :\n return decodeQueryParam(s, n);\n default :\n return decode(s, n);\n }\n }\n\n /**\n * Decode the query component of a URI.\n * \n * @param u the URI.\n * @param decode true if the query parameters of the query component\n * should be in decoded form.\n * @return the multivalued map of query parameters.\n */\n public static Map decodeQuery(URI u, boolean decode) {\n return decodeQuery(u.getRawQuery(), decode);\n }\n\n /**\n * Decode the query component of a URI.\n * \n * @param q the query component in encoded form.\n * @param decode true of the query parameters of the query component\n * should be in decoded form.\n * @return the multivalued map of query parameters.\n */\n public static Map decodeQuery(String q, boolean decode) {\n Map queryParameters = new HashMap<>();\n\n if (q == null || q.length() == 0) {\n return queryParameters;\n }\n\n int s = 0, e;\n do {\n e = q.indexOf('&', s);\n\n if (e == -1) {\n decodeQueryParam(queryParameters, q.substring(s), decode);\n } else if (e > s) {\n decodeQueryParam(queryParameters, q.substring(s, e), decode);\n }\n s = e + 1;\n } while (s > 0 && s < q.length());\n\n return queryParameters;\n }\n\n private static void decodeQueryParam(Map params,\n String param, boolean decode) {\n try {\n int equals = param.indexOf('=');\n if (equals > 0) {\n params.put(\n URLDecoder.decode(param.substring(0, equals), \"UTF-8\"),\n (decode) ? URLDecoder.decode(param.substring(equals + 1), \"UTF-8\") : param.substring(equals + 1));\n } else if (equals == 0) {\n // no key declared, ignore\n } else if (param.length() > 0) {\n params.put(\n URLDecoder.decode(param, \"UTF-8\"),\n \"\");\n }\n } catch (UnsupportedEncodingException ex) {\n // This should never occur\n throw new IllegalArgumentException(ex);\n }\n }\n\n private static final class PathSegmentImpl {\n\n private static final PathSegmentImpl EMPTY_PATH_SEGMENT = new PathSegmentImpl(\"\", false);\n private final String path;\n private final Map matrixParameters;\n\n PathSegmentImpl(String path, boolean decode) {\n this(path, decode, new HashMap ());\n }\n\n PathSegmentImpl(String path, boolean decode, Map matrixParameters) {\n this.path = (decode) ? UriComponent.decode(path, UriComponent.Type.PATH_SEGMENT) : path;\n this.matrixParameters = matrixParameters;\n }\n\n public String getPath() {\n return path;\n }\n\n public Map getMatrixParameters() {\n return matrixParameters;\n }\n }\n\n /**\n * Decode the path component of a URI as path segments.\n *\n * @param u the URI. If the path component is an absolute path component\n * then the leading '/' is ignored and is not considered a delimiator\n * of a path segment.\n * @param decode true if the path segments of the path component\n * should be in decoded form.\n * @return the list of path segments.\n */\n public static List decodePath(URI u, boolean decode) {\n String rawPath = u.getRawPath();\n if (rawPath != null && rawPath.length() > 0 && rawPath.charAt(0) == '/') {\n rawPath = rawPath.substring(1);\n }\n return decodePath(rawPath, decode);\n }\n\n /**\n * Decode the path component of a URI as path segments.\n *

          \n * Any '/' character in the path is considered to be a deliminator\n * between two path segments. Thus if the path is '/' then the path segment\n * list will contain two empty path segments. If the path is \"//\" then\n * the path segment list will contain three empty path segments. If the path\n * is \"/a/\" the path segment list will consist of the following path\n * segments in order: \"\", \"a\" and \"\".\n *\n * @param path the path component in encoded form.\n * @param decode true if the path segments of the path component\n * should be in decoded form.\n * @return the list of path segments.\n */\n public static List decodePath(String path, boolean decode) {\n List segments = new LinkedList<>();\n\n if (path == null) {\n return segments;\n }\n\n int s;\n int e = -1;\n do {\n s = e + 1;\n e = path.indexOf('/', s);\n\n if (e > s) {\n decodePathSegment(segments, path.substring(s, e), decode);\n } else if (e == s) {\n segments.add(PathSegmentImpl.EMPTY_PATH_SEGMENT);\n }\n } while (e != -1);\n if (s < path.length()) {\n decodePathSegment(segments, path.substring(s), decode);\n } else {\n segments.add(PathSegmentImpl.EMPTY_PATH_SEGMENT);\n }\n return segments;\n }\n\n public static void decodePathSegment(List segments, String segment, boolean decode) {\n int colon = segment.indexOf(';');\n if (colon != -1) {\n segments.add(new PathSegmentImpl(\n (colon == 0) ? \"\" : segment.substring(0, colon),\n decode,\n decodeMatrix(segment, decode)));\n } else {\n segments.add(new PathSegmentImpl(\n segment,\n decode));\n }\n }\n\n /**\n * Decode the matrix component of a URI path segment.\n *\n * @param pathSegment the path segment component in encoded form.\n * @param decode true if the matrix parameters of the path segment component\n * should be in decoded form.\n * @return the multivalued map of matrix parameters.\n */\n public static Map decodeMatrix(String pathSegment, boolean decode) {\n Map matrixMap = new HashMap<>();\n\n // Skip over path segment\n int s = pathSegment.indexOf(';') + 1;\n if (s == 0 || s == pathSegment.length()) {\n return matrixMap;\n }\n\n int e;\n do {\n e = pathSegment.indexOf(';', s);\n\n if (e == -1) {\n decodeMatrixParam(matrixMap, pathSegment.substring(s), decode);\n } else if (e > s) {\n decodeMatrixParam(matrixMap, pathSegment.substring(s, e), decode);\n }\n s = e + 1;\n } while (s > 0 && s < pathSegment.length());\n\n return matrixMap;\n }\n\n private static void decodeMatrixParam(Map params,\n String param, boolean decode) {\n int equals = param.indexOf('=');\n if (equals > 0) {\n params.put(\n UriComponent.decode(param.substring(0, equals), UriComponent.Type.MATRIX_PARAM),\n (decode) ? UriComponent.decode(param.substring(equals + 1), UriComponent.Type.MATRIX_PARAM) : param.substring(equals + 1));\n } else if (equals == 0) {\n // no key declared, ignore\n } else if (param.length() > 0) {\n params.put(\n UriComponent.decode(param, UriComponent.Type.MATRIX_PARAM),\n \"\");\n }\n }\n\n private static String decode(String s, int n) {\n final StringBuilder sb = new StringBuilder(n);\n ByteBuffer bb = null;\n\n for (int i = 0; i < n;) {\n final char c = s.charAt(i++);\n if (c != '%') {\n sb.append(c);\n } else {\n bb = decodePercentEncodedOctets(s, i, bb);\n i = decodeOctets(i, bb, sb);\n }\n }\n\n return sb.toString();\n }\n\n private static String decodeQueryParam(String s, int n) {\n final StringBuilder sb = new StringBuilder(n);\n ByteBuffer bb = null;\n\n for (int i = 0; i < n;) {\n final char c = s.charAt(i++);\n if (c != '%') {\n if (c != '+')\n sb.append(c);\n else\n sb.append(' ');\n } else {\n bb = decodePercentEncodedOctets(s, i, bb);\n i = decodeOctets(i, bb, sb);\n }\n }\n\n return sb.toString();\n }\n\n private static String decodeHost(String s, int n) {\n final StringBuilder sb = new StringBuilder(n);\n ByteBuffer bb = null;\n\n boolean betweenBrackets = false;\n for (int i = 0; i < n;) {\n final char c = s.charAt(i++);\n if (c == '[') {\n betweenBrackets = true;\n } else if (betweenBrackets && c == ']') {\n betweenBrackets = false;\n }\n\n if (c != '%' || betweenBrackets) {\n sb.append(c);\n } else {\n bb = decodePercentEncodedOctets(s, i, bb);\n i = decodeOctets(i, bb, sb);\n }\n }\n\n return sb.toString();\n }\n\n /**\n * Decode a contigious sequence of percent encoded octets.\n *

          \n * Assumes the index, i, starts that the first hex digit of the first\n * percent-encoded octet.\n */\n private static ByteBuffer decodePercentEncodedOctets(String s, int i, ByteBuffer bb) {\n if (bb == null)\n bb = ByteBuffer.allocate(1);\n else\n ((Buffer)bb).clear();\n\n while (true) {\n // Decode the hex digits\n bb.put((byte) (decodeHex(s, i++) << 4 | decodeHex(s, i++)));\n\n // Finish if at the end of the string\n if (i == s.length()) {\n break;\n }\n\n // Finish if no more percent-encoded octets follow\n if (s.charAt(i++) != '%') {\n break;\n }\n\n // Check if the byte buffer needs to be increased in size\n if (bb.position() == bb.capacity()) {\n ((Buffer)bb).flip();\n // Create a new byte buffer with the maximum number of possible\n // octets, hence resize should only occur once\n ByteBuffer bb_new = ByteBuffer.allocate(s.length() / 3);\n bb_new.put(bb);\n bb = bb_new;\n }\n }\n\n ((Buffer)bb).flip();\n return bb;\n }\n\n /**\n * Decodes octets to characters using the UTF-8 decoding and appends\n * the characters to a StringBuffer.\n * @return the index to the next unchecked character in the string to decode\n */\n private static int decodeOctets(int i, ByteBuffer bb, StringBuilder sb) {\n // If there is only one octet and is an ASCII character\n if (bb.limit() == 1 && (bb.get(0) & 0xFF) < 0x80) {\n // Octet can be appended directly\n sb.append((char) bb.get(0));\n return i + 2;\n } else {\n // \n CharBuffer cb = UTF_8_CHARSET.decode(bb);\n sb.append(cb);\n return i + bb.limit() * 3 - 1;\n }\n }\n\n private static int decodeHex(String s, int i) {\n final int v = decodeHex(s.charAt(i));\n if (v == -1) // TODO localize\n {\n throw new IllegalArgumentException(\"Malformed percent-encoded octet at index \" + i +\n \", invalid hexadecimal digit '\" + s.charAt(i) + \"'\");\n }\n return v;\n }\n private static final int[] HEX_TABLE = createHexTable();\n\n private static int[] createHexTable() {\n int[] table = new int[0x80];\n Arrays.fill(table, -1);\n\n for (char c = '0'; c <= '9'; c++) {\n table[c] = c - '0';\n }\n for (char c = 'A'; c <= 'F'; c++) {\n table[c] = c - 'A' + 10;\n }\n for (char c = 'a'; c <= 'f'; c++) {\n table[c] = c - 'a' + 10;\n }\n return table;\n }\n\n private static int decodeHex(char c) {\n return (c < 128) ? HEX_TABLE[c] : -1;\n }\n\n private static boolean isHexCharacter(char c) {\n return c < 128 && HEX_TABLE[c] != -1;\n }\n}", "file_name": "UriComponent.java", "human_label": "Encoding the given string by changing '{' and '}' to the specified character for each,return the string after encoding.", "level": "self_contained", "lineno": "272", "name": "encodeTemplateNames", "oracle_context": "{ \"apis\" : \"[indexOf, replace]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "org.atmosphere.util.uri", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767531a6d9265ec017ef1", "all_context": "{ \"class_level\" : \"import org.jgrapht.alg.util.*;\\nimport java.util.function.*;\\nToleranceDoubleComparator TOLERANCE_DOUBLE_COMPARATOR;\\nadd(Point2D a,Point2D b);\\nsubtract(Point2D a,Point2D b);\\nnegate(Point2D a);\\nscalarMultiply(Point2D a,double scalar);\\nscalarMultiply(Point2D a,S scalar,BiFunction mult);\\nequals(Point2D p1,Point2D p2);\\nlength(Point2D v);\\n\", \"repo_level\" : \"\" }", "class_name": "Points", "code": "public static boolean equals(Point2D p1,Point2D p2){\n int xEquals=TOLERANCE_DOUBLE_COMPARATOR.compare(p1.getX(),p2.getX());\n if (xEquals != 0) {\n return false;\n }\n return TOLERANCE_DOUBLE_COMPARATOR.compare(p1.getY(),p2.getY()) == 0;\n}\n", "docstring": "/** \n * Compare two points for equality using tolerance 1e-9.\n * @param p1 the first point\n * @param p2 the second point\n * @return whether the two points are equal or not\n */\n", "end_lineno": "122", "file_content": "/*\n * (C) Copyright 2018-2021, by Dimitrios Michail and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.drawing.model;\n\nimport org.jgrapht.alg.util.*;\n\nimport java.util.function.*;\n\n/**\n * A collection of utilities to assist with point manipulation.\n * \n * @author Dimitrios Michail\n */\npublic abstract class Points\n{\n private static final ToleranceDoubleComparator TOLERANCE_DOUBLE_COMPARATOR =\n new ToleranceDoubleComparator(1e-9);\n\n /**\n * Compute the length of a vector. The length of vector $(x,y)$ is given by $\\sqrt{x^2+y^2}$.\n * \n * @param v the vector\n * @return the length of a vector\n */\n public static double length(Point2D v)\n {\n return Math.sqrt(v.getX() * v.getX() + v.getY() * v.getY());\n }\n\n /**\n * Add 2-dimensional vectors\n * \n * @param a the first vector\n * @param b the second vector\n * @return the vector $a+b$\n */\n public static Point2D add(Point2D a, Point2D b)\n {\n return Point2D.of(a.getX() + b.getX(), a.getY() + b.getY());\n }\n\n /**\n * Subtract 2-dimensional vectors\n * \n * @param a the first vector\n * @param b the second vector\n * @return the vector $a-b$\n */\n public static Point2D subtract(Point2D a, Point2D b)\n {\n return Point2D.of(a.getX() - b.getX(), a.getY() - b.getY());\n }\n\n /**\n * Given a vector $a$ compute $-a$.\n * \n * @param a the vector\n * @return the vector $-a$\n */\n public static Point2D negate(Point2D a)\n {\n return scalarMultiply(a, -1.0);\n }\n\n /**\n * Multiply a vector with a scalar.\n * \n * @param a the vector\n * @param scalar the scalar\n * @return the result of scalar multiplication\n */\n public static Point2D scalarMultiply(Point2D a, double scalar)\n {\n return scalarMultiply(a, scalar, (x, s) -> x * s);\n }\n\n /**\n * Multiply a vector with a scalar.\n * \n * @param a the vector\n * @param scalar the scalar\n * @param mult the multiplication operator\n * @return the result of scalar multiplication\n * \n * @param the scalar type\n */\n public static <\n S> Point2D scalarMultiply(Point2D a, S scalar, BiFunction mult)\n {\n return Point2D.of(mult.apply(a.getX(), scalar), mult.apply(a.getY(), scalar));\n }\n\n /**\n * Compare two points for equality using tolerance 1e-9.\n * \n * @param p1 the first point\n * @param p2 the second point\n * @return whether the two points are equal or not\n */\n public static boolean equals(Point2D p1, Point2D p2)\n {\n int xEquals = TOLERANCE_DOUBLE_COMPARATOR.compare(p1.getX(), p2.getX());\n if (xEquals != 0) {\n return false;\n }\n return TOLERANCE_DOUBLE_COMPARATOR.compare(p1.getY(), p2.getY()) == 0;\n }\n\n}\n", "file_name": "Points.java", "human_label": "Using TOLERANCE_DOUBLE_COMPARATOR to compare two points for equality,return true the point p1 is equal to another point p2,otherwise return false.", "level": "project_runnable", "lineno": "108", "name": "equals", "oracle_context": "{ \"apis\" : \"[compare, getX, getY]\", \"classes\" : \"[]\", \"vars\" : \"[TOLERANCE_DOUBLE_COMPARATOR]\" }", "package": "org.jgrapht.alg.drawing.model", "project": "jgrapht-master" }, { "_id": "6367667c1a6d9265ec0173fb", "all_context": "{ \"class_level\" : \"import org.atmosphere.interceptor.AllowInterceptor;\\nimport org.atmosphere.util.Utils;\\nimport org.atmosphere.websocket.WebSocket;\\nimport org.atmosphere.websocket.WebSocketEventListener;\\nimport org.slf4j.Logger;\\nimport org.slf4j.LoggerFactory;\\nimport javax.servlet.http.HttpSession;\\nimport java.io.IOException;\\nimport java.util.*;\\nimport java.util.concurrent.ConcurrentLinkedQueue;\\nimport java.util.concurrent.CopyOnWriteArrayList;\\nimport java.util.concurrent.TimeUnit;\\nimport java.util.concurrent.atomic.AtomicBoolean;\\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SESSION_CREATE;\\nimport static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID;\\nimport static org.atmosphere.cpr.AtmosphereResource.TRANSPORT.UNDEFINED;\\nimport static org.atmosphere.cpr.Broadcaster.ROOT_MASTER;\\nimport static org.atmosphere.cpr.HeaderConfig.LONG_POLLING_TRANSPORT;\\nimport static org.atmosphere.cpr.HeaderConfig.WEBSOCKET_UPGRADE;\\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_ERROR;\\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_TRANSPORT;\\nimport static org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent.TYPE.CLOSE;\\nLogger logger;\\nString PRE_SUSPEND;\\nString SKIP_BROADCASTER_CREATION;\\nString METEOR;\\nAtmosphereRequest req;\\nAtmosphereResponse response;\\nAction action;\\nList broadcasters;\\nBroadcaster broadcaster;\\nAtmosphereConfig config;\\nAsyncSupport asyncSupport;\\nSerializer serializer;\\nAtomicBoolean isInScope;\\nAtmosphereResourceEventImpl event;\\nAtomicBoolean isResumed;\\nAtomicBoolean isCancelled;\\nAtomicBoolean resumeOnBroadcast;\\nObject writeOnTimeout;\\nboolean disableSuspend;\\nAtomicBoolean disconnected;\\nConcurrentLinkedQueue listeners;\\nAtomicBoolean isSuspendEvent;\\nAtmosphereHandler atmosphereHandler;\\nString uuid;\\nHttpSession session;\\nboolean disableSuspendEvent;\\nTRANSPORT transport;\\nboolean forceBinaryWrite;\\nAtomicBoolean suspended;\\nWebSocket webSocket;\\nAtomicBoolean inClosingPhase;\\nboolean closeOnCancel;\\nAtomicBoolean isPendingClose;\\nAtmosphereResourceImpl();\\nAtmosphereResourceImpl(AtmosphereConfig config,Broadcaster broadcaster,AtmosphereRequest req,AtmosphereResponse response,AsyncSupport asyncSupport,AtmosphereHandler atmosphereHandler);\\nsetUUID(String uuid);\\nregister();\\nconfigureTransport();\\ngetAtmosphereResourceEvent();\\ngetAtmosphereHandler();\\nwriteOnTimeout(Object o);\\nwriteOnTimeout();\\nuuid();\\ntransport();\\ntransport(TRANSPORT transport);\\nresumeOnBroadcast(boolean resumeOnBroadcast);\\nisSuspended();\\nresumeOnBroadcast();\\nresume();\\nsuspend();\\nsuspend(long timeout,TimeUnit timeunit);\\nsuspend(long timeout);\\ngetRequest(boolean enforceScope);\\ngetResponse(boolean enforceScope);\\ngetRequest();\\ngetResponse();\\ngetBroadcaster();\\nbroadcasters();\\ngetBroadcaster(boolean autoCreate);\\nsetBroadcaster(Broadcaster broadcaster);\\naddBroadcaster(Broadcaster broadcaster);\\nremoveBroadcaster(Broadcaster broadcaster);\\nuniqueBroadcaster(Broadcaster newB);\\ngetAtmosphereConfig();\\naction();\\nreset();\\nsetIsInScope(boolean isInScope);\\nisInScope();\\nsetSerializer(Serializer s);\\nisResumed();\\nisCancelled();\\nwrite(String s);\\nwrite(byte[] o);\\ngetSerializer();\\naddEventListener(AtmosphereResourceEventListener e);\\nremoveEventListener(AtmosphereResourceEventListener e);\\nremoveEventListeners();\\nnotifyListeners();\\nnotifyListeners(AtmosphereResourceEvent event);\\nremoveFromAllBroadcasters();\\nonThrowable(Throwable t);\\nonThrowable(AtmosphereResourceEvent e);\\nonHeartbeat(AtmosphereResourceEvent e);\\nonSuspend(AtmosphereResourceEvent e);\\nonPreSuspend(AtmosphereResourceEvent e);\\nonResume(AtmosphereResourceEvent e);\\nonDisconnect(AtmosphereResourceEvent e);\\nonBroadcast(AtmosphereResourceEvent e);\\nonClose(AtmosphereResourceEvent e);\\natmosphereResourceEventListener();\\natmosphereHandler(AtmosphereHandler atmosphereHandler);\\ncancel();\\nunregister();\\n_destroy();\\ntoString();\\ndisableSuspend(boolean disableSuspend);\\nsession(boolean create);\\nclose();\\ndirtyClose();\\nforceBinaryWrite(boolean forceBinaryWrite);\\nforceBinaryWrite();\\nsession();\\nsession(HttpSession session);\\ncloneState(AtmosphereResource r);\\nlisteners();\\ndisableSuspendEvent(boolean disableSuspendEvent);\\ndisableSuspendEvent();\\nwebSocket();\\nwebSocket(WebSocket webSocket);\\nequals(Object o);\\nhashCode();\\ngetAndSetInClosingPhase();\\nisPendingClose();\\ngetAndSetPendingClose();\\ninitialize(AtmosphereConfig config,Broadcaster broadcaster,AtmosphereRequest req,AtmosphereResponse response,AsyncSupport asyncSupport,AtmosphereHandler atmosphereHandler);\\n\", \"repo_level\" : \"public interface AllowInterceptor { }\\npublic interface Utils {static boolean webSocketEnabled(HttpServletRequest request);\\nstatic boolean rawWebSocket(HttpServletRequest request);\\nstatic boolean firefoxWebSocketEnabled(HttpServletRequest request);\\nstatic boolean twoConnectionsTransport(TRANSPORT t);\\nstatic boolean webSocketQueryStringPresentOrNull(HttpServletRequest request);\\nstatic boolean resumableTransport(TRANSPORT t);\\nstatic boolean pollableTransport(TRANSPORT t);\\nstatic boolean pushMessage(TRANSPORT t);\\nstatic boolean atmosphereProtocol(AtmosphereRequest r);\\nstatic boolean webSocketMessage(AtmosphereResource r);\\nstatic boolean properProtocol(HttpServletRequest request);\\nstatic AtmosphereResource websocketResource(AtmosphereResource r);\\nstatic boolean closeMessage(HttpServletRequest request);\\nstatic Object invoke(Object proxiedInstance,Method m,Object o);\\nstatic void inject(AtmosphereResource r);\\nstatic void inject(Object object,Class clazz,AtmosphereResource r);\\nstatic void inject(Object object,Class clazz,AtmosphereConfig config);\\nstatic Set getInheritedPrivateFields(Class type);\\nstatic Set getInheritedPrivateMethod(Class type);\\nstatic boolean requestScopedInjection(AtmosphereConfig config,AtmosphereHandler h);\\nstatic boolean requestScopedInjection(AtmosphereConfig config,Object o);\\nstatic void destroyMeteor(AtmosphereRequest req);\\nstatic String pathInfo(AtmosphereRequest request);\\nstatic boolean isRunningTest();\\nstatic boolean isUnderJDK11AndUp();\\n }\\npublic interface WebSocket {public AtmosphereConfig config();\\nprotected WebSocket webSocketHandler(WebSocketHandler webSocketHandler);\\npublic WebSocket binaryWrite(boolean binaryWrite);\\npublic WebSocketHandler webSocketHandler();\\npublic WebSocket resource(AtmosphereResource r);\\nsynchronized void shiftAttributes();\\npublic Map attributes();\\npublic AtmosphereResource resource();\\npublic long lastWriteTimeStampInMilliseconds();\\nprotected byte[] transform(byte[] b,int offset,int length);\\nprotected byte[] transform(AtmosphereResponse response,byte[] b,int offset,int length);\\npublic WebSocket write(AtmosphereResponse r,String data);\\npublic WebSocket write(AtmosphereResponse r,byte[] data);\\npublic WebSocket write(AtmosphereResponse r,byte[] b,int offset,int length);\\npublic WebSocket broadcast(Object o);\\npublic WebSocket writeError(AtmosphereResponse r,int errorCode,String message);\\npublic WebSocket redirect(AtmosphereResponse r,String location);\\npublic void close(AtmosphereResponse r);\\npublic WebSocket flush(AtmosphereResponse r);\\npublic boolean isOpen();\\npublic WebSocket write(String s);\\npublic WebSocket write(byte[] b,int offset,int length);\\npublic WebSocket write(byte[] b);\\npublic void close();\\npublic void close(int statusCode,String reasonText);\\npublic String uuid();\\nstatic void notSupported(AtmosphereRequest request,AtmosphereResponse response);\\npublic WebSocket sendPing(byte[] payload);\\npublic WebSocket sendPong(byte[] payload);\\npublic WebSocket attachment(Object attachment);\\npublic Object attachment();\\n }\\npublic interface WebSocketEventListener { void onHandshake(WebSocketEvent event);\\n void onMessage(WebSocketEvent event);\\n void onClose(WebSocketEvent event);\\n void onControl(WebSocketEvent event);\\n void onDisconnect(WebSocketEvent event);\\n void onConnect(WebSocketEvent event);\\npublic T message();\\npublic WebSocket webSocket();\\npublic TYPE type();\\npublic String toString();\\n }\\n\" }", "class_name": "AtmosphereResourceImpl", "code": "@Override public AtmosphereResource addEventListener(AtmosphereResourceEventListener e){\n if (listeners.contains(e)) return this;\n listeners.add(e);\n return this;\n}\n", "docstring": "/** \n * Add a {@link AtmosphereResourceEventListener}.\n * @param e an instance of AtmosphereResourceEventListener\n */\n", "end_lineno": "609", "file_content": "/*\n * Copyright 2008-2022 Async-IO.org\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\npackage org.atmosphere.cpr;\n\nimport org.atmosphere.interceptor.AllowInterceptor;\nimport org.atmosphere.util.Utils;\nimport org.atmosphere.websocket.WebSocket;\nimport org.atmosphere.websocket.WebSocketEventListener;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport javax.servlet.http.HttpSession;\nimport java.io.IOException;\nimport java.util.*;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.concurrent.CopyOnWriteArrayList;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\nimport static org.atmosphere.cpr.ApplicationConfig.PROPERTY_SESSION_CREATE;\nimport static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID;\nimport static org.atmosphere.cpr.AtmosphereResource.TRANSPORT.UNDEFINED;\nimport static org.atmosphere.cpr.Broadcaster.ROOT_MASTER;\nimport static org.atmosphere.cpr.HeaderConfig.LONG_POLLING_TRANSPORT;\nimport static org.atmosphere.cpr.HeaderConfig.WEBSOCKET_UPGRADE;\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_ERROR;\nimport static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_TRANSPORT;\nimport static org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent.TYPE.CLOSE;\n\n/**\n * {@link AtmosphereResource} implementation for supporting {@link AtmosphereRequest}\n * and {@link AtmosphereResponse}.\n *\n * @author Jeanfrancois Arcand\n */\npublic class AtmosphereResourceImpl implements AtmosphereResource {\n\n private static final Logger logger = LoggerFactory.getLogger(AtmosphereResourceImpl.class);\n\n public static final String PRE_SUSPEND = AtmosphereResourceImpl.class.getName() + \".preSuspend\";\n public static final String SKIP_BROADCASTER_CREATION = AtmosphereResourceImpl.class.getName() + \".skipBroadcasterCreation\";\n public static final String METEOR = Meteor.class.getName();\n\n private AtmosphereRequest req;\n private AtmosphereResponse response;\n private final Action action = new Action();\n protected final List broadcasters = new CopyOnWriteArrayList<>();\n protected Broadcaster broadcaster;\n private AtmosphereConfig config;\n protected AsyncSupport asyncSupport;\n private Serializer serializer;\n private final AtomicBoolean isInScope = new AtomicBoolean(true);\n private AtmosphereResourceEventImpl event;\n private final AtomicBoolean isResumed = new AtomicBoolean();\n private final AtomicBoolean isCancelled = new AtomicBoolean();\n private final AtomicBoolean resumeOnBroadcast = new AtomicBoolean();\n private Object writeOnTimeout;\n private boolean disableSuspend;\n private final AtomicBoolean disconnected = new AtomicBoolean();\n\n private final ConcurrentLinkedQueue listeners =\n new ConcurrentLinkedQueue<>();\n\n private final AtomicBoolean isSuspendEvent = new AtomicBoolean();\n private AtmosphereHandler atmosphereHandler;\n private String uuid;\n protected HttpSession session;\n private boolean disableSuspendEvent;\n private TRANSPORT transport;\n private boolean forceBinaryWrite;\n private final AtomicBoolean suspended = new AtomicBoolean();\n private WebSocket webSocket;\n private final AtomicBoolean inClosingPhase = new AtomicBoolean();\n private boolean closeOnCancel;\n private final AtomicBoolean isPendingClose = new AtomicBoolean();\n\n public AtmosphereResourceImpl() {\n }\n\n @Deprecated\n public AtmosphereResourceImpl(AtmosphereConfig config, Broadcaster broadcaster,\n AtmosphereRequest req, AtmosphereResponse response,\n AsyncSupport asyncSupport, AtmosphereHandler atmosphereHandler) {\n initialize(config, broadcaster, req, response, asyncSupport, atmosphereHandler);\n }\n\n /**\n * Initialize an {@link AtmosphereResource}.\n *\n * @param config The {@link org.atmosphere.cpr.AtmosphereConfig}\n * @param broadcaster The {@link org.atmosphere.cpr.Broadcaster}.\n * @param req The {@link AtmosphereRequest}\n * @param response The {@link AtmosphereResource}\n * @param asyncSupport The {@link AsyncSupport}\n * @param atmosphereHandler The {@link AtmosphereHandler}\n * @return this\n */\n @Override\n public AtmosphereResource initialize(AtmosphereConfig config, Broadcaster broadcaster,\n AtmosphereRequest req, AtmosphereResponse response,\n AsyncSupport asyncSupport, AtmosphereHandler atmosphereHandler) {\n this.req = req;\n this.response = response;\n this.config = config;\n this.asyncSupport = asyncSupport;\n this.atmosphereHandler = atmosphereHandler;\n this.event = new AtmosphereResourceEventImpl(this);\n\n this.broadcaster = broadcaster;\n uniqueBroadcaster(broadcaster);\n\n String s = (String) req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID);\n if (s == null) {\n s = response.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID);\n if (s == null) {\n String tmp = req.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID);\n s = tmp != null && !tmp.equalsIgnoreCase(\"0\") ? tmp : null;\n }\n }\n setUUID(s == null ? config.uuidProvider().generateUuid() : s);\n\n if (config.isSupportSession()) {\n // Keep a reference to an HttpSession in case the associated request get recycled by the underlying container.\n try {\n session = req.getSession(config.getInitParameter(PROPERTY_SESSION_CREATE, true));\n } catch (NullPointerException ex) {\n // http://java.net/jira/browse/GLASSFISH-18856\n logger.trace(\"http://java.net/jira/browse/GLASSFISH-18856\", ex);\n }\n }\n transport = configureTransport();\n closeOnCancel = config.getInitParameter(ApplicationConfig.CLOSE_STREAM_ON_CANCEL, false);\n return this;\n }\n\n protected void setUUID(String uuid) {\n this.uuid = uuid;\n }\n\n\n protected void register() {\n if (!Utils.pollableTransport(transport()) && !Utils.webSocketMessage(this)) {\n config.resourcesFactory().registerUuidForFindCandidate(this);\n }\n }\n\n private TRANSPORT configureTransport() {\n if (req == null) return UNDEFINED;\n\n String s = req.getHeader(HeaderConfig.X_ATMOSPHERE_TRANSPORT);\n if (s == null) return UNDEFINED;\n\n if (s.equals(UNDEFINED.name()) && Utils.rawWebSocket(req)) {\n return TRANSPORT.WEBSOCKET;\n }\n\n s = s.replace(\"-\", \"_\").toUpperCase();\n if (TRANSPORT.POLLING.name().equals(s)) {\n return TRANSPORT.POLLING;\n } else if (TRANSPORT.LONG_POLLING.name().equals(s)) {\n return TRANSPORT.LONG_POLLING;\n } else if (TRANSPORT.STREAMING.name().equals(s)) {\n return TRANSPORT.STREAMING;\n } else if (TRANSPORT.JSONP.name().equals(s)) {\n return TRANSPORT.JSONP;\n } else if (TRANSPORT.WEBSOCKET.name().equals(s)) {\n return TRANSPORT.WEBSOCKET;\n } else if (TRANSPORT.SSE.name().equals(s)) {\n return TRANSPORT.SSE;\n } else if (TRANSPORT.AJAX.name().equals(s)) {\n return TRANSPORT.AJAX;\n } else if (TRANSPORT.CLOSE.name().equals(s)) {\n return TRANSPORT.CLOSE;\n } else {\n return UNDEFINED;\n }\n }\n\n @Override\n public AtmosphereResourceEventImpl getAtmosphereResourceEvent() {\n return event;\n }\n\n @Override\n public AtmosphereHandler getAtmosphereHandler() {\n return atmosphereHandler;\n }\n\n @Override\n public AtmosphereResource writeOnTimeout(Object o) {\n writeOnTimeout = o;\n return this;\n }\n\n @Override\n public Object writeOnTimeout() {\n return writeOnTimeout;\n }\n\n @Override\n public String uuid() {\n return uuid;\n }\n\n @Override\n public TRANSPORT transport() {\n return transport;\n }\n\n /**\n * Manually set the {@link TRANSPORT}\n *\n * @param transport set the {@link TRANSPORT}\n */\n public AtmosphereResourceImpl transport(TRANSPORT transport) {\n this.transport = transport;\n return this;\n }\n\n @Override\n public AtmosphereResource resumeOnBroadcast(boolean resumeOnBroadcast) {\n this.resumeOnBroadcast.set(resumeOnBroadcast);\n // For legacy reason\n req.setAttribute(ApplicationConfig.RESUME_ON_BROADCAST, resumeOnBroadcast);\n return this;\n }\n\n @Override\n public boolean isSuspended() {\n return suspended.get();\n }\n\n @Override\n public boolean resumeOnBroadcast() {\n boolean rob = resumeOnBroadcast.get();\n if (!rob) {\n try {\n Boolean b = (Boolean) req.getAttribute(ApplicationConfig.RESUME_ON_BROADCAST);\n return b != null && b;\n } catch (ClassCastException ex) {\n // WebSphere is doing something strange here\n return false;\n }\n }\n return rob;\n }\n\n @Override\n public AtmosphereResource resume() {\n\n if (!isSuspended()) {\n logger.trace(\"AtmosphereResource {} not suspended {}, cannot resume it.\", uuid(), action);\n return this;\n }\n\n try {\n if (!isResumed.getAndSet(true) && isInScope.get()) {\n suspended.set(false);\n logger.trace(\"AtmosphereResource {} is resuming\", uuid());\n\n action.type(Action.TYPE.RESUME);\n\n boolean notify = true;\n for (Broadcaster b : broadcasters) {\n // We need it as Jetty doesn't support timeout\n if (!b.isDestroyed() && b instanceof DefaultBroadcaster) {\n ((DefaultBroadcaster) b).broadcastOnResume(this);\n }\n\n if (notify) {\n notify = false;\n notifyListeners();\n }\n\n if (b.getScope() == Broadcaster.SCOPE.REQUEST) {\n logger.debug(\"Broadcaster's scope is set to request, destroying it {}\", b.getID());\n b.destroy();\n }\n }\n removeFromAllBroadcasters();\n\n try {\n req.setAttribute(ApplicationConfig.RESUMED_ON_TIMEOUT, Boolean.FALSE);\n } catch (Exception ex) {\n logger.debug(\"Resume exception: Cannot resume an already resumed/cancelled request\", ex);\n }\n\n if (req.getAttribute(PRE_SUSPEND) == null) {\n asyncSupport.action(this);\n }\n } else {\n logger.trace(\"Already resumed {}\", this);\n return this;\n }\n } catch (Throwable t) {\n logger.trace(\"Wasn't able to resume a connection {}\", this, t);\n } finally {\n unregister();\n Utils.destroyMeteor(req);\n }\n listeners.clear();\n return this;\n }\n\n @Override\n public AtmosphereResource suspend() {\n return suspend(-1);\n }\n\n @Override\n public AtmosphereResource suspend(long timeout, TimeUnit timeunit) {\n long timeoutms = -1;\n if (timeunit != null) {\n timeoutms = TimeUnit.MILLISECONDS.convert(timeout, timeunit);\n }\n\n return suspend(timeoutms);\n }\n\n @Override\n public AtmosphereResource suspend(long timeout) {\n\n if (event.isSuspended() || disableSuspend) return this;\n\n if (config.isSupportSession()\n && req.getSession(false) != null\n && req.getSession().getMaxInactiveInterval() >= 0\n && req.getSession().getMaxInactiveInterval() * 1000L < timeout) {\n throw new IllegalStateException(\"Cannot suspend a \" +\n \"response longer than the session timeout. Increase the value of session-timeout in web.xml\");\n }\n\n if (Utils.resumableTransport(transport())) {\n resumeOnBroadcast.set(true);\n }\n\n onPreSuspend(event);\n\n // Recheck based on preSuspend\n if (event.isSuspended() || disableSuspend) return this;\n\n if (!event.isResumedOnTimeout()) {\n suspended.set(true);\n\n Enumeration connection = req.getHeaders(\"Connection\");\n if (connection == null) {\n connection = req.getHeaders(\"connection\");\n }\n\n if (connection != null && connection.hasMoreElements()) {\n String[] e = connection.nextElement().toString().split(\",\");\n for (String upgrade : e) {\n if (upgrade.trim().equalsIgnoreCase(WEBSOCKET_UPGRADE)) {\n if (!asyncSupport.supportWebSocket()) {\n response.addHeader(X_ATMOSPHERE_ERROR, \"Websocket protocol not supported\");\n } else {\n req.setAttribute(FrameworkConfig.TRANSPORT_IN_USE, HeaderConfig.WEBSOCKET_TRANSPORT);\n }\n }\n }\n }\n\n if (req.getHeader(X_ATMOSPHERE_TRANSPORT) == null || transport().equals(UNDEFINED)) {\n req.setAttribute(FrameworkConfig.TRANSPORT_IN_USE, LONG_POLLING_TRANSPORT);\n }\n\n req.setAttribute(PRE_SUSPEND, \"true\");\n action.type(Action.TYPE.SUSPEND);\n action.timeout(timeout);\n\n // TODO: We can possibly optimize that call by avoiding creating a Broadcaster if we are sure the Broadcaster\n // is unique.\n boolean isJersey = req.getAttribute(FrameworkConfig.CONTAINER_RESPONSE) != null;\n\n boolean skipCreation = req.getAttribute(SKIP_BROADCASTER_CREATION) != null;\n\n Broadcaster broadcaster = getBroadcaster();\n\n // Null means SCOPE=REQUEST set by a Meteor\n if (!skipCreation && (broadcaster == null || broadcaster.getScope() == Broadcaster.SCOPE.REQUEST) && !isJersey) {\n String id = broadcaster != null ? broadcaster.getID() : ROOT_MASTER;\n Class clazz = broadcaster != null ? broadcaster.getClass() : DefaultBroadcaster.class;\n\n broadcaster = config.getBroadcasterFactory().lookup(clazz, id, false);\n if (broadcaster == null || !broadcaster.getAtmosphereResources().isEmpty()) {\n broadcaster = config.getBroadcasterFactory().lookup(clazz, id + \"/\" + UUID.randomUUID(), true);\n }\n }\n\n Objects.requireNonNull(broadcaster).addAtmosphereResource(this);\n if (req.getAttribute(DefaultBroadcaster.CACHED) != null && transport() != null && Utils.resumableTransport(transport())) {\n action.type(Action.TYPE.CONTINUE);\n // Do nothing because we have found cached message which was written already, and the handler resumed.\n logger.debug(\"Cached message found, not suspending {}\", uuid());\n return this;\n }\n req.removeAttribute(PRE_SUSPEND);\n register();\n notifyListeners();\n }\n return this;\n }\n\n public AtmosphereRequest getRequest(boolean enforceScope) {\n if (enforceScope && !isInScope.get()) {\n throw new IllegalStateException(\"Request object no longer\" + \" valid. This object has been cancelled\");\n }\n return req;\n }\n\n public AtmosphereResponse getResponse(boolean enforceScope) {\n if (enforceScope && !isInScope.get()) {\n throw new IllegalStateException(\"Response object no longer valid. This object has been cancelled\");\n }\n return response;\n }\n\n @Override\n public AtmosphereRequest getRequest() {\n return getRequest(true);\n }\n\n @Override\n public AtmosphereResponse getResponse() {\n return getResponse(true);\n }\n\n @Override\n public Broadcaster getBroadcaster() {\n return getBroadcaster(true);\n }\n\n @Override\n public List broadcasters() {\n return Collections.unmodifiableList(broadcasters);\n }\n\n protected Broadcaster getBroadcaster(boolean autoCreate) {\n if (broadcaster == null) {\n throw new IllegalStateException(\"No Broadcaster associated with this AtmosphereResource.\");\n }\n\n String s = config.getInitParameter(ApplicationConfig.RECOVER_DEAD_BROADCASTER);\n if (s != null) {\n autoCreate = Boolean.parseBoolean(s);\n }\n\n if (autoCreate && broadcaster.isDestroyed() && config.getBroadcasterFactory() != null) {\n logger.debug(\"Broadcaster {} has been destroyed and cannot be re-used. Recreating a new one with the same name. You can turn off this\" +\n \" mechanism by adding, in web.xml, {} set to false\", broadcaster.getID(), ApplicationConfig.RECOVER_DEAD_BROADCASTER);\n\n Broadcaster.SCOPE scope = broadcaster.getScope();\n synchronized (this) {\n String id = scope != Broadcaster.SCOPE.REQUEST ? broadcaster.getID() : broadcaster.getID() + \".recovered\"\n + config.uuidProvider().generateUuid();\n\n // Another Thread may have added the Broadcaster.\n broadcaster = config.getBroadcasterFactory().lookup(id, true);\n broadcaster.setScope(scope);\n broadcaster.addAtmosphereResource(this);\n }\n }\n return broadcaster;\n }\n\n @Override\n public AtmosphereResource setBroadcaster(Broadcaster broadcaster) {\n this.broadcaster = broadcaster;\n return uniqueBroadcaster(broadcaster);\n }\n\n @Override\n public AtmosphereResource addBroadcaster(Broadcaster broadcaster) {\n return uniqueBroadcaster(broadcaster);\n }\n\n @Override\n public AtmosphereResource removeBroadcaster(Broadcaster broadcaster) {\n broadcasters.remove(broadcaster);\n return this;\n }\n\n protected AtmosphereResource uniqueBroadcaster(Broadcaster newB) {\n if (newB == null) {\n return this;\n }\n // TODO: performance bottleneck\n for (Broadcaster b: broadcasters) {\n if (b.getID() != null && b.getID().equalsIgnoreCase(newB.getID())) {\n logger.trace(\"Duplicate Broadcaster {}\", newB);\n return this;\n }\n }\n broadcasters.add(newB);\n return this;\n }\n\n\n @Override\n public AtmosphereConfig getAtmosphereConfig() {\n return config;\n }\n\n /**\n * Return the {@link Action} which represent the state of the response, e.g. suspended, resumed or timed out.\n *\n * @return the {@link Action}\n */\n public Action action() {\n return action;\n }\n\n /**\n * Completely reset the instance to its initial state.\n */\n public void reset() {\n isResumed.set(false);\n isCancelled.set(false);\n isPendingClose.set(false);\n isInScope.set(true);\n isSuspendEvent.set(false);\n listeners.clear();\n action.type(Action.TYPE.CREATED);\n }\n\n /**\n * Protect the object from being used after it got cancelled.\n *\n * */\n public void setIsInScope(boolean isInScope) {\n this.isInScope.set(isInScope);\n }\n\n /**\n * Check if the {@link AtmosphereRequest} still is valid.\n *\n * @return true if the {@link AtmosphereRequest} still is valid\n */\n public boolean isInScope() {\n return isInScope.get();\n }\n\n /**\n * Set the {@link Serializer} used to write broadcasted objects.\n *\n */\n @Override\n public AtmosphereResource setSerializer(Serializer s) {\n serializer = s;\n return this;\n }\n\n @Override\n public boolean isResumed() {\n return isResumed.get();\n }\n\n @Override\n public boolean isCancelled() {\n return isCancelled.get();\n }\n\n @Override\n public AtmosphereResource write(String s) {\n response.write(s);\n if (resumeOnBroadcast()) {\n resume();\n }\n return this;\n }\n\n @Override\n public AtmosphereResource write(byte[] o) {\n response.write(o);\n if (resumeOnBroadcast()) {\n resume();\n }\n return this;\n }\n\n @Override\n public Serializer getSerializer() {\n return serializer;\n }\n\n /**\n * Add a {@link AtmosphereResourceEventListener}.\n *\n * @param e an instance of AtmosphereResourceEventListener\n */\n @Override\n public AtmosphereResource addEventListener(AtmosphereResourceEventListener e) {\n if (listeners.contains(e)) return this;\n listeners.add(e);\n return this;\n }\n\n @Override\n public AtmosphereResource removeEventListener(AtmosphereResourceEventListener e) {\n listeners.remove(e);\n return this;\n }\n\n @Override\n public AtmosphereResource removeEventListeners() {\n listeners.clear();\n return this;\n }\n\n @Override\n public AtmosphereResource notifyListeners() {\n notifyListeners(event);\n return this;\n }\n\n @Override\n public AtmosphereResource notifyListeners(AtmosphereResourceEvent event) {\n if (listeners.isEmpty() && config.framework().atmosphereResourceListeners().isEmpty()) {\n logger.trace(\"No listener with {}\", uuid());\n return this;\n }\n logger.trace(\"Invoking listener {} for {}\", listeners, uuid());\n\n try {\n if (HeartbeatAtmosphereResourceEvent.class.isAssignableFrom(event.getClass())) {\n onHeartbeat(event);\n } else if (event.isClosedByApplication()) {\n onClose(event);\n } else if (event.isCancelled() || event.isClosedByClient()) {\n if (!disconnected.getAndSet(true)) {\n onDisconnect(event);\n } else {\n logger.trace(\"Skipping notification, already disconnected {}\", event.getResource() != null ? event.getResource().uuid() : uuid());\n }\n } else if (event.isResuming() || event.isResumedOnTimeout()) {\n onResume(event);\n } else if (!isSuspendEvent.getAndSet(true) && event.isSuspended()) {\n onSuspend(event);\n } else if (event.throwable() != null) {\n onThrowable(event);\n } else {\n onBroadcast(event);\n }\n\n if (action.type() != action.type()) {\n action().type(Action.TYPE.CREATED);\n }\n } catch (Throwable t) {\n ((AtmosphereResourceEventImpl) event).setThrowable(t);\n if (event.isSuspended()) {\n logger.warn(\"Exception during suspend() operation {}\", t.toString());\n logger.debug(\"\", t);\n removeFromAllBroadcasters();\n } else {\n logger.debug(\"Listener error {}\", event, t);\n }\n\n try {\n onThrowable(event);\n } catch (Throwable t2) {\n logger.warn(\"Listener error {}\", event, t2);\n }\n }\n return this;\n }\n\n @Override\n public AtmosphereResource removeFromAllBroadcasters() {\n for (Broadcaster b : broadcasters) {\n try {\n b.removeAtmosphereResource(this);\n } catch (Exception ex) {\n logger.trace(\"\", ex);\n }\n }\n return this;\n }\n\n /**\n * Notify {@link AtmosphereResourceEventListener} thah an unexpected exception occured.\n *\n */\n public void onThrowable(Throwable t) {\n onThrowable(new AtmosphereResourceEventImpl(this, false, false, t));\n }\n\n void onThrowable(AtmosphereResourceEvent e) {\n for (AtmosphereResourceEventListener r : listeners) {\n r.onThrowable(e);\n }\n }\n\n /**\n *

          \n * Notifies to all listeners that a heartbeat has been sent.\n *

          \n *\n * @param e the event\n */\n void onHeartbeat(AtmosphereResourceEvent e) {\n for (AtmosphereResourceEventListener r : listeners) {\n r.onHeartbeat(e);\n }\n }\n\n void onSuspend(AtmosphereResourceEvent e) {\n for (AtmosphereResourceEventListener r : listeners) {\n if (disableSuspendEvent) {\n if (!AllowInterceptor.class.isAssignableFrom(r.getClass())) {\n continue;\n }\n }\n r.onSuspend(e);\n }\n if (e.getResource() != null) {\n config.framework().notifySuspended(e.getResource().uuid());\n }\n }\n\n void onPreSuspend(AtmosphereResourceEvent e) {\n for (AtmosphereResourceEventListener r : listeners) {\n if (disableSuspendEvent) {\n if (!AllowInterceptor.class.isAssignableFrom(r.getClass())) {\n continue;\n }\n }\n r.onPreSuspend(e);\n }\n }\n\n void onResume(AtmosphereResourceEvent e) {\n for (AtmosphereResourceEventListener r : listeners) {\n r.onResume(e);\n }\n }\n\n void onDisconnect(AtmosphereResourceEvent e) {\n for (AtmosphereResourceEventListener r : listeners) {\n r.onDisconnect(e);\n if (transport.equals(TRANSPORT.WEBSOCKET) && WebSocketEventListener.class.isAssignableFrom(r.getClass())) {\n ((WebSocketEventListener) r).onDisconnect(new WebSocketEventListener.WebSocketEvent<>(1005, CLOSE, webSocket));\n }\n }\n\n if (e.getResource() != null) {\n config.framework().notifyDestroyed(e.getResource().uuid());\n }\n }\n\n void onBroadcast(AtmosphereResourceEvent e) {\n for (AtmosphereResourceEventListener r : listeners) {\n r.onBroadcast(e);\n }\n }\n\n void onClose(AtmosphereResourceEvent e) {\n for (AtmosphereResourceEventListener r : listeners) {\n r.onClose(e);\n if (transport.equals(TRANSPORT.WEBSOCKET) && WebSocketEventListener.class.isAssignableFrom(r.getClass())) {\n ((WebSocketEventListener) r).onClose(new WebSocketEventListener.WebSocketEvent<>(1005, CLOSE, webSocket));\n }\n }\n }\n\n public ConcurrentLinkedQueue atmosphereResourceEventListener() {\n return listeners;\n }\n\n public AtmosphereResourceImpl atmosphereHandler(AtmosphereHandler atmosphereHandler) {\n this.atmosphereHandler = atmosphereHandler;\n return this;\n }\n\n public void cancel() throws IOException {\n try {\n if (!isCancelled.getAndSet(true)) {\n suspended.set(false);\n logger.trace(\"Cancelling {}\", uuid());\n\n if (config.getBroadcasterFactory() != null) {\n removeFromAllBroadcasters();\n if (transport.equals(TRANSPORT.WEBSOCKET)) {\n String parentUUID = (String) req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID);\n AtmosphereResource p = config.resourcesFactory().find(parentUUID);\n if (p != null) {\n p.removeFromAllBroadcasters();\n }\n }\n }\n\n asyncSupport.complete(this);\n\n try {\n Object o = req.getAttribute(AtmosphereResourceImpl.METEOR);\n if (o != null && Meteor.class.isAssignableFrom(o.getClass())) {\n ((Meteor) o).destroy();\n }\n } catch (Exception ex) {\n logger.trace(\"Meteor exception\", ex);\n }\n\n SessionTimeoutSupport.restoreTimeout(req);\n action.type(Action.TYPE.CANCELLED);\n if (asyncSupport != null) asyncSupport.action(this);\n // We must close the underlying WebSocket as well.\n if (AtmosphereResponseImpl.class.isAssignableFrom(response.getClass())) {\n if (closeOnCancel) {\n response.close();\n }\n response.destroy();\n }\n\n if (AtmosphereRequestImpl.class.isAssignableFrom(req.getClass())) {\n if (closeOnCancel) {\n req.destroy();\n }\n }\n event.destroy();\n }\n } finally {\n unregister();\n }\n }\n\n private void unregister() {\n config.resourcesFactory().remove(uuid());\n }\n\n public void _destroy() {\n try {\n if (!isCancelled.get()) {\n removeFromAllBroadcasters();\n }\n broadcasters.clear();\n\n unregister();\n removeEventListeners();\n } catch (Throwable t) {\n logger.trace(\"destroyResource\", t);\n } finally {\n unregister();\n webSocket = null;\n }\n }\n\n @Override\n public String toString() {\n try {\n return \"AtmosphereResource{\" +\n \"\\n\\t uuid=\" + uuid() +\n \",\\n\\t transport=\" + transport() +\n \",\\n\\t isInScope=\" + isInScope +\n \",\\n\\t isResumed=\" + isResumed() +\n \",\\n\\t isCancelled=\" + isCancelled() +\n \",\\n\\t isSuspended=\" + isSuspended() +\n \",\\n\\t broadcasters=\" + getBroadcaster().getID() +\n \",\\n\\t isClosedByClient=\" + (event != null && event.isClosedByClient()) +\n \",\\n\\t isClosedByApplication=\" + (event != null && event.isClosedByApplication()) +\n \",\\n\\t action=\" + action +\n '}';\n } catch (NullPointerException ex) {\n // Prevent logger\n return \"AtmosphereResourceImpl{\" + uuid() + \"}\";\n }\n }\n\n public AtmosphereResourceImpl disableSuspend(boolean disableSuspend) {\n this.disableSuspend = disableSuspend;\n return this;\n }\n\n @Override\n public HttpSession session(boolean create) {\n if (config.isSupportSession() && session == null) {\n // http://java.net/jira/browse/GLASSFISH-18856\n session = req.getSession(create);\n }\n return session;\n }\n\n @Override\n public void close() throws IOException {\n event.setCloseByApplication(true);\n notifyListeners();\n cancel();\n if (webSocket != null && webSocket.isOpen()) {\n webSocket.close();\n }\n }\n\n public void dirtyClose() {\n try {\n event.setCancelled(true);\n notifyListeners();\n cancel();\n if (webSocket != null) {\n webSocket.close();\n }\n } catch (IOException ex) {\n logger.trace(\"\", ex);\n }\n }\n\n @Override\n public AtmosphereResource forceBinaryWrite(boolean forceBinaryWrite) {\n this.forceBinaryWrite = forceBinaryWrite;\n return this;\n }\n\n @Override\n public boolean forceBinaryWrite() {\n return forceBinaryWrite;\n }\n\n @Override\n public HttpSession session() {\n return session(true);\n }\n\n public AtmosphereResourceImpl session(HttpSession session) {\n this.session = session;\n return this;\n }\n\n public AtmosphereResourceImpl cloneState(AtmosphereResource r) {\n for (AtmosphereResourceEventListener l : ((AtmosphereResourceImpl) r).atmosphereResourceEventListener()) {\n addEventListener(l);\n }\n ((AtmosphereResourceImpl) r).session(r.session());\n boolean isFirst = true;\n for (Broadcaster b : broadcasters) {\n if (isFirst) {\n isFirst = false;\n setBroadcaster(b);\n } else {\n addBroadcaster(b);\n }\n }\n atmosphereHandler(r.getAtmosphereHandler());\n return this;\n }\n\n public ConcurrentLinkedQueue listeners() {\n return listeners;\n }\n\n /**\n * Disable invocation of {@link AtmosphereResourceEventListener#onSuspend(AtmosphereResourceEvent)} and\n * {@link AtmosphereResourceEventListener#onPreSuspend(AtmosphereResourceEvent)}. You normally disable those events\n * after the first onSuspend has been called so all transports behave the same way.\n *
          \n * {@link AtmosphereResourceEventListener} marked with {@link org.atmosphere.interceptor.AllowInterceptor} will not\n * be affected by this property.\n *\n * @param disableSuspendEvent\n * @return this\n */\n public AtmosphereResourceImpl disableSuspendEvent(boolean disableSuspendEvent) {\n this.disableSuspendEvent = disableSuspendEvent;\n return this;\n }\n\n /**\n * Return true if {@link AtmosphereResourceEventListener#onSuspend(AtmosphereResourceEvent)} and\n * {@link AtmosphereResourceEventListener#onPreSuspend(AtmosphereResourceEvent)} events are disabled.\n *\n * @return true if disabled\n */\n public boolean disableSuspendEvent() {\n return disableSuspendEvent;\n }\n\n public WebSocket webSocket() {\n return webSocket;\n }\n\n public AtmosphereResourceImpl webSocket(WebSocket webSocket) {\n this.webSocket = webSocket;\n return this;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n AtmosphereResourceImpl that = (AtmosphereResourceImpl) o;\n\n return uuid() != null ? uuid().equals(that.uuid()) : that.uuid() == null;\n }\n\n @Override\n public int hashCode() {\n return uuid() != null ? uuid().hashCode() : 0;\n }\n\n public boolean getAndSetInClosingPhase() {\n return inClosingPhase.getAndSet(true);\n }\n\n /**\n * @return\n */\n public boolean isPendingClose () {\n return isPendingClose.get();\n }\n \n public boolean getAndSetPendingClose() {\n return isPendingClose.getAndSet(true);\n }\n}\n", "file_name": "AtmosphereResourceImpl.java", "human_label": "Adding an instance of AtmosphereResourceEventListener e into a list and return the AtmosphereResource object which call the function.", "level": "project_runnable", "lineno": "599", "name": "addEventListener", "oracle_context": "{ \"apis\" : \"[contains, add, listeners]\", \"classes\" : \"[]\", \"vars\" : \"[listeners]\" }", "package": "org.atmosphere.cpr", "project": "atmosphere-atmosphere-2.7.x" }, { "_id": "636767691a6d9265ec0181ac", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static String applyRelativePath(String path,String relativePath){\n int separatorIndex=path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath=path.substring(0,separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath+=FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n}\n", "docstring": "/** \n * Apply the given relative path to the given path, assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply(relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n", "end_lineno": "592", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *
          \n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
          \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
          \n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
          \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

          The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

          This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

          The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

          The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

          Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

          Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

          The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

          The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

          A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

          A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Combine the substring before FOLDER_SEPARATOR of the given path with the given relative path to construct a new full file path,and return the full file path.", "level": "class_runnable", "lineno": "572", "name": "applyRelativePath", "oracle_context": "{ \"apis\" : \"[lastIndexOf, substring, startsWith]\", \"classes\" : \"[String]\", \"vars\" : \"[FOLDER_SEPARATOR]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636767021a6d9265ec0178bc", "all_context": "{ \"class_level\" : \"import net.hasor.core.Singleton;\\nimport net.hasor.dataql.UdfSourceAssembly;\\nimport net.hasor.utils.StringUtils;\\nimport java.util.Arrays;\\nimport java.util.List;\\nimport java.util.regex.Matcher;\\nimport java.util.regex.Pattern;\\nPattern linePattern;\\nPattern humpPattern;\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWith(String str,String suffix);\\nendsWithIgnoreCase(String str,String suffix);\\n_startsWith(String str,String prefix,boolean ignoreCase);\\n_endsWith(String str,String suffix,boolean ignoreCase);\\nlineToHump(String str);\\nhumpToLine(String str);\\nfirstCharToUpperCase(String value);\\nfirstCharToLowerCase(String value);\\ntoUpperCase(String value);\\ntoLowerCase(String value);\\nindexOf(String str,String searchStr);\\nindexOfWithStart(String str,String searchStr,int startPos);\\nindexOfIgnoreCase(String str,String searchStr);\\nindexOfIgnoreCaseWithStart(String str,String searchStr,int startPos);\\nlastIndexOf(String str,String searchStr);\\nlastIndexOfWithStart(String str,String searchChar,int startPos);\\nlastIndexOfIgnoreCase(String str,String searchStr);\\nlastIndexOfIgnoreCaseWithStart(String str,String searchStr,int startPos);\\ncontains(String str,String searchStr);\\ncontainsIgnoreCase(String str,String searchStr);\\ncontainsAny(String str,List searchStrArray);\\ncontainsAnyIgnoreCase(String str,List searchStrArray);\\ntrim(String str);\\nsub(String str,int start,int end);\\nleft(String str,int len);\\nright(String str,int len);\\nalignRight(String str,String padChar,int len);\\nalignLeft(String str,String padChar,int len);\\nalignCenter(String str,String padChar,int len);\\ncompareString(String str1,String str2);\\ncompareStringIgnoreCase(String str1,String str2);\\nsplit(String str,String separatorChars);\\njoin(List array,String separator);\\nisEmpty(String str);\\nequalsIgnoreCase(String str1,String str2);\\nstartsWith(String str,String prefix);\\n\", \"repo_level\" : \"public interface UdfSourceAssembly {default Supplier getSupplier(Class targetType,Finder finder);\\ndefault Predicate getPredicate(Class targetType);\\npublic Object[] allParams();\\ndefault Supplier> getUdfResource(Finder finder);\\npublic Class annotationType();\\npublic String value();\\npublic Object call(Hints readOnly,Object values);\\npublic Object call(Hints readOnly,Object values);\\n }\\npublic interface StringUtils {static boolean isEmpty(String str);\\nstatic boolean isNotEmpty(String str);\\nstatic boolean isBlank(String str);\\nstatic boolean isNotBlank(String str);\\nstatic String trim(String str);\\nstatic String trimToNull(String str);\\nstatic String trimToEmpty(String str);\\nstatic String strip(String str);\\nstatic String stripToNull(String str);\\nstatic String stripToEmpty(String str);\\nstatic String strip(String str,String stripChars);\\nstatic String stripStart(String str,String stripChars);\\nstatic String stripEnd(String str,String stripChars);\\nstatic String[] stripAll(String[] strs);\\nstatic String[] stripAll(String[] strs,String stripChars);\\nstatic boolean equals(String str1,String str2);\\nstatic boolean equalsIgnoreCase(String str1,String str2);\\nstatic int indexOf(String str,char searchChar);\\nstatic int indexOf(String str,char searchChar,int startPos);\\nstatic int indexOf(String str,String searchStr);\\nstatic int ordinalIndexOf(String str,String searchStr,int ordinal);\\nstatic int indexOf(String str,String searchStr,int startPos);\\nstatic int indexOfIgnoreCase(String str,String searchStr);\\nstatic int indexOfIgnoreCase(String str,String searchStr,int startPos);\\nstatic int lastIndexOf(String str,char searchChar);\\nstatic int lastIndexOf(String str,char searchChar,int startPos);\\nstatic int lastIndexOf(String str,String searchStr);\\nstatic int lastOrdinalIndexOf(String str,String searchStr,int ordinal);\\nstatic int lastIndexOf(String str,String searchStr,int startPos);\\nstatic int lastIndexOfIgnoreCase(String str,String searchStr);\\nstatic int lastIndexOfIgnoreCase(String str,String searchStr,int startPos);\\nstatic boolean contains(String str,char searchChar);\\nstatic boolean contains(String str,String searchStr);\\nstatic boolean containsIgnoreCase(String str,String searchStr);\\nstatic int indexOfAny(String str,char[] searchChars);\\nstatic int indexOfAny(String str,String searchChars);\\nstatic boolean containsAny(String str,char[] searchChars);\\nstatic boolean containsAny(String str,String searchChars);\\nstatic int indexOfAnyBut(String str,char[] searchChars);\\nstatic int indexOfAnyBut(String str,String searchChars);\\nstatic boolean containsOnly(String str,char[] valid);\\nstatic boolean containsOnly(String str,String validChars);\\nstatic boolean containsNone(String str,char[] searchChars);\\nstatic boolean containsNone(String str,String invalidChars);\\nstatic int indexOfAny(String str,String[] searchStrs);\\nstatic int lastIndexOfAny(String str,String[] searchStrs);\\nstatic String substring(String str,int start);\\nstatic String substring(String str,int start,int end);\\nstatic String left(String str,int len);\\nstatic String right(String str,int len);\\nstatic String mid(String str,int pos,int len);\\nstatic String substringBefore(String str,String separator);\\nstatic String substringAfter(String str,String separator);\\nstatic String substringBeforeLast(String str,String separator);\\nstatic String substringAfterLast(String str,String separator);\\nstatic String substringBetween(String str,String tag);\\nstatic String substringBetween(String str,String open,String close);\\nstatic String[] substringsBetween(String str,String open,String close);\\nstatic String[] splitKeep(String str,char separatorChar);\\nstatic String[] splitKeep(String str,String separatorStr);\\nstatic String[] split(String str);\\nstatic String[] split(String str,char separatorChar);\\nstatic String[] split(String str,String separatorChars);\\nstatic String[] split(String str,String separatorChars,int max);\\nstatic String[] splitByWholeSeparator(String str,String separator);\\nstatic String[] splitByWholeSeparator(String str,String separator,int max);\\nstatic String[] splitByWholeSeparatorPreserveAllTokens(String str,String separator);\\nstatic String[] splitByWholeSeparatorPreserveAllTokens(String str,String separator,int max);\\nstatic String[] splitPreserveAllTokens(String str);\\nstatic String[] splitPreserveAllTokens(String str,char separatorChar);\\nstatic String[] splitPreserveAllTokens(String str,String separatorChars);\\nstatic String[] splitPreserveAllTokens(String str,String separatorChars,int max);\\nstatic String[] splitByCharacterType(String str);\\nstatic String[] splitByCharacterTypeCamelCase(String str);\\nstatic String join(Object[] array);\\nstatic String join(Object[] array,char separator);\\nstatic String join(Object[] array,char separator,int startIndex,int endIndex);\\nstatic String join(Object[] array,String separator);\\nstatic String join(Object[] array,String separator,int startIndex,int endIndex);\\nstatic String deleteWhitespace(String str);\\nstatic String removeStart(String str,String remove);\\nstatic String removeStartIgnoreCase(String str,String remove);\\nstatic String removeEnd(String str,String remove);\\nstatic String removeEndIgnoreCase(String str,String remove);\\nstatic String remove(String str,String remove);\\nstatic String remove(String str,char remove);\\nstatic String replaceOnce(String text,String searchString,String replacement);\\nstatic String replace(String text,String searchString,String replacement);\\nstatic String replace(String text,String searchString,String replacement,int max);\\nstatic String replaceEach(String text,String[] searchList,String[] replacementList);\\nstatic String replaceEachRepeatedly(String text,String[] searchList,String[] replacementList);\\nstatic String replaceChars(String str,char searchChar,char replaceChar);\\nstatic String replaceChars(String str,String searchChars,String replaceChars);\\nstatic String overlay(String str,String overlay,int start,int end);\\nstatic String chomp(String str);\\nstatic String chomp(String str,String separator);\\nstatic String chop(String str);\\nstatic String repeat(char character,int repeat);\\nstatic String repeat(String str,int repeat);\\nstatic String repeat(String str,String separator,int repeat);\\nstatic String rightPad(String str,int size);\\nstatic String rightPad(String str,int size,char padChar);\\nstatic String rightPad(String str,int size,String padStr);\\nstatic String leftPad(String str,int size);\\nstatic String leftPad(String str,int size,char padChar);\\nstatic String leftPad(String str,int size,String padStr);\\nstatic int length(String str);\\nstatic String center(String str,int size);\\nstatic String center(String str,int size,char padChar);\\nstatic String center(String str,int size,String padStr);\\nstatic String upperCase(String str);\\nstatic String upperCase(String str,Locale locale);\\nstatic String lowerCase(String str);\\nstatic String lowerCase(String str,Locale locale);\\nstatic String capitalize(String str);\\nstatic String uncapitalize(String str);\\nstatic String swapCase(String str);\\nstatic int countMatches(String str,String sub);\\nstatic boolean isAlpha(String str);\\nstatic boolean isAlphaSpace(String str);\\nstatic boolean isAlphanumeric(String str);\\nstatic boolean isAlphanumericSpace(String str);\\nstatic boolean isAsciiPrintable(String str);\\nstatic boolean isNumeric(String str);\\nstatic boolean isNumericSpace(String str);\\nstatic boolean isWhitespace(String str);\\nstatic boolean isAllLowerCase(String str);\\nstatic boolean isAllUpperCase(String str);\\nstatic String defaultString(String str);\\nstatic String defaultString(String str,String defaultStr);\\nstatic String defaultIfBlank(String str,String defaultStr);\\nstatic String defaultIfEmpty(String str,String defaultStr);\\nstatic String reverse(String str);\\nstatic String reverseDelimited(String str,char separatorChar);\\nstatic String abbreviate(String str,int maxWidth);\\nstatic String abbreviate(String str,int offset,int maxWidth);\\nstatic String abbreviateMiddle(String str,String middle,int length);\\nstatic String difference(String str1,String str2);\\nstatic int indexOfDifference(String str1,String str2);\\nstatic int indexOfDifference(String[] strs);\\nstatic String getCommonPrefix(String[] strs);\\nstatic int getLevenshteinDistance(String s,String t);\\nstatic boolean startsWith(String str,String prefix);\\nstatic boolean startsWithIgnoreCase(String str,String prefix);\\nstatic boolean startsWithAny(String string,String[] searchStrings);\\nstatic boolean endsWith(String str,String suffix);\\nstatic boolean endsWithIgnoreCase(String str,String suffix);\\nstatic String normalizeSpace(String str);\\nstatic boolean endsWithAny(String string,String[] searchStrings);\\nstatic String firstCharToUpperCase(String value);\\nstatic String firstCharToLowerCase(String value);\\nstatic boolean equalsBlankIgnoreCase(String str1,String str2);\\nstatic String quote(String input);\\nstatic void quote(Appendable buffer,String input);\\nstatic String toString(Object object);\\n }\\n\" }", "class_name": "StringUdfSource", "code": "public static int indexOf(String str,String searchStr){\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr);\n}\n", "docstring": "/** \n * Finds the first index within a String, handling null. This method uses {@link String#indexOf(String)}. \n */\n", "end_lineno": "140", "file_content": "/*\n * Copyright 2008-2009 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.dataql.fx.basic;\nimport net.hasor.core.Singleton;\nimport net.hasor.dataql.UdfSourceAssembly;\nimport net.hasor.utils.StringUtils;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * 字符串函数 import 'net.hasor.dataql.fx.basic.StringUdfSource' as string;\n * @version : 2019-12-12\n */\n@Singleton\npublic class StringUdfSource implements UdfSourceAssembly {\n // startsWith/endsWith\n //-----------------------------------------------------------------------\n\n /** Check if a String starts with a specified prefix. */\n public static boolean startsWith(String str, String prefix) {\n return _startsWith(str, prefix, false);\n }\n\n /** Case insensitive check if a String starts with a specified prefix. */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n return _startsWith(str, prefix, true);\n }\n\n /** Case insensitive check if a String ends with a specified suffix. */\n public static boolean endsWith(String str, String suffix) {\n return _endsWith(str, suffix, false);\n }\n\n /** Case insensitive check if a String ends with a specified suffix. */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n return _endsWith(str, suffix, true);\n }\n\n private static boolean _startsWith(String str, String prefix, boolean ignoreCase) {\n if (str == null || prefix == null) {\n return str == null && prefix == null;\n }\n if (prefix.length() > str.length()) {\n return false;\n }\n return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length());\n }\n\n private static boolean _endsWith(String str, String suffix, boolean ignoreCase) {\n if (str == null || suffix == null) {\n return str == null && suffix == null;\n }\n if (suffix.length() > str.length()) {\n return false;\n }\n int strOffset = str.length() - suffix.length();\n return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length());\n }\n\n // Hump\n //-----------------------------------------------------------------------\n private static final Pattern linePattern = Pattern.compile(\"_(\\\\w)\");\n private static final Pattern humpPattern = Pattern.compile(\"[A-Z]\");\n\n /** 下划线转驼峰 */\n public static String lineToHump(String str) {\n if (str == null) {\n return null;\n }\n str = str.toLowerCase();\n Matcher matcher = linePattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, matcher.group(1).toUpperCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n\n /** 驼峰转下划线 */\n public static String humpToLine(String str) {\n if (str == null) {\n return null;\n }\n Matcher matcher = humpPattern.matcher(str);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n matcher.appendReplacement(sb, \"_\" + matcher.group(0).toLowerCase());\n }\n matcher.appendTail(sb);\n return sb.toString();\n }\n // UpperCase/LowerCase\n //-----------------------------------------------------------------------\n\n /** 转换首字母大写 */\n public static String firstCharToUpperCase(String value) {\n return StringUtils.firstCharToUpperCase(value);\n }\n\n /** 转换首字母小写 */\n public static String firstCharToLowerCase(String value) {\n return StringUtils.firstCharToLowerCase(value);\n }\n\n /** 转换大写 */\n public static String toUpperCase(String value) {\n return StringUtils.upperCase(value);\n }\n\n /** 转换小写 */\n public static String toLowerCase(String value) {\n return StringUtils.lowerCase(value);\n }\n // IndexOf/lastIndexOf\n //-----------------------------------------------------------------------\n\n /** Finds the first index within a String, handling null. This method uses {@link String#indexOf(String)}. */\n public static int indexOf(String str, String searchStr) {\n if (str == null || searchStr == null) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr);\n }\n\n /** Finds the first index within a String from a start position, handling null. This method uses {@link String#indexOf(String, int)}. */\n public static int indexOfWithStart(String str, String searchStr, int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.indexOf(searchStr, startPos);\n }\n\n /** Case in-sensitive find of the first index within a String. */\n public static int indexOfIgnoreCase(String str, String searchStr) {\n return StringUtils.indexOfIgnoreCase(str, searchStr, 0);\n }\n\n /** Case in-sensitive find of the first index within a String from the specified position. */\n public static int indexOfIgnoreCaseWithStart(String str, String searchStr, int startPos) {\n return StringUtils.indexOfIgnoreCase(str, searchStr, startPos);\n }\n\n /** Finds the last index within a String, handling null. This method uses {@link String#lastIndexOf(String)}. */\n public static int lastIndexOf(String str, String searchStr) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchStr);\n }\n\n /** Finds the last index within a String from a start position, handling null. This method uses {@link String#lastIndexOf(String, int)}. */\n public static int lastIndexOfWithStart(String str, String searchChar, int startPos) {\n if (StringUtils.isEmpty(str)) {\n return StringUtils.INDEX_NOT_FOUND;\n }\n return str.lastIndexOf(searchChar, startPos);\n }\n\n /** Case in-sensitive find of the last index within a String from the specified position. */\n public static int lastIndexOfIgnoreCase(String str, String searchStr) {\n return StringUtils.lastIndexOfIgnoreCase(str, searchStr, 0);\n }\n\n /** Case in-sensitive find of the last index within a String from the specified position. */\n public static int lastIndexOfIgnoreCaseWithStart(String str, String searchStr, int startPos) {\n return StringUtils.lastIndexOfIgnoreCase(str, searchStr, startPos);\n }\n // Contains\n //-----------------------------------------------------------------------\n\n /** Checks if String contains a search String, handling null. This method uses {@link String#indexOf(String)}. */\n public static boolean contains(String str, String searchStr) {\n return StringUtils.contains(str, searchStr);\n }\n\n /** Checks if String contains a search String irrespective of case, handling null. Case-insensitivity is defined as by {@link String#equalsIgnoreCase(String)}. */\n public static boolean containsIgnoreCase(String str, String searchStr) {\n return StringUtils.containsIgnoreCase(str, searchStr);\n }\n\n /** Checks if the String contains any character in the given set of string. */\n public static boolean containsAny(String str, List searchStrArray) {\n if (StringUtils.isEmpty(str) || searchStrArray == null || searchStrArray.isEmpty()) {\n return false;\n }\n for (String item : searchStrArray) {\n if (contains(str, item)) {\n return true;\n }\n }\n return false;\n }\n\n /** Case in-sensitive Checks if the String contains any character in the given set of string. */\n public static boolean containsAnyIgnoreCase(String str, List searchStrArray) {\n if (StringUtils.isEmpty(str) || searchStrArray == null || searchStrArray.isEmpty()) {\n return false;\n }\n for (String item : searchStrArray) {\n if (containsIgnoreCase(str, item)) {\n return true;\n }\n }\n return false;\n }\n // trim/Sub/left/right\n //-----------------------------------------------------------------------\n\n /** 截断两边空格,如果为空返回为空。 */\n public static String trim(final String str) {\n return str == null ? null : str.trim();\n }\n\n /** Gets a substring from the specified String avoiding exceptions. */\n public static String sub(String str, int start, int end) {\n return StringUtils.substring(str, start, end);\n }\n\n /** Gets the leftmost len characters of a String. */\n public static String left(String str, int len) {\n return StringUtils.left(str, len);\n }\n\n /** Gets the rightmost len characters of a String. */\n public static String right(String str, int len) {\n return StringUtils.right(str, len);\n }\n // align/pading\n //-----------------------------------------------------------------------\n\n /** 字符串在指定长度下进行右对齐,空出来的字符使用padChar补齐。如果传入多个字符将会取第一个字符。 */\n public static String alignRight(String str, String padChar, int len) {\n if (str != null) {\n if (str.length() > len) {\n return str;\n }\n }\n char pad = padChar.length() == 0 ? ' ' : padChar.charAt(0);\n return StringUtils.rightPad(str, len, pad);\n }\n\n /** 字符串在指定长度下进行左对齐,空出来的字符使用padChar补齐。如果传入多个字符将会取第一个字符。 */\n public static String alignLeft(String str, String padChar, int len) {\n if (str != null) {\n if (str.length() > len) {\n return str;\n }\n }\n char pad = padChar.length() == 0 ? ' ' : padChar.charAt(0);\n return StringUtils.leftPad(str, len, pad);\n }\n\n /** 字符串在指定长度下进行剧中对齐,空出来的字符使用padChar补齐。如果传入多个字符将会取第一个字符。 */\n public static String alignCenter(String str, String padChar, int len) {\n if (str != null) {\n if (str.length() > len) {\n return str;\n }\n }\n char pad = padChar.length() == 0 ? ' ' : padChar.charAt(0);\n return StringUtils.center(str, len, pad);\n }\n // compare\n //-----------------------------------------------------------------------\n\n /**\n * Compares two strings lexicographically.\n * The comparison is based on the Unicode value of each character in\n * the strings. The character sequence represented by this\n * {@code String} object is compared lexicographically to the\n * character sequence represented by the argument string. The result is\n * a negative integer if this {@code String} object\n * lexicographically precedes the argument string. The result is a\n * positive integer if this {@code String} object lexicographically\n * follows the argument string. The result is zero if the strings\n * are equal; {@code compareTo} returns {@code 0} exactly when\n * the {@link #equals(Object)} method would return {@code true}.\n *

          \n * This is the definition of lexicographic ordering. If two strings are\n * different, then either they have different characters at some index\n * that is a valid index for both strings, or their lengths are different,\n * or both. If they have different characters at one or more index\n * positions, let k be the smallest such index; then the string\n * whose character at position k has the smaller value, as\n * determined by using the < operator, lexicographically precedes the\n * other string. In this case, {@code compareTo} returns the\n * difference of the two character values at position {@code k} in\n * the two string -- that is, the value:\n *

          \n     * this.charAt(k)-anotherString.charAt(k)\n     * 
          \n * If there is no index position at which they differ, then the shorter\n * string lexicographically precedes the longer string. In this case,\n * {@code compareTo} returns the difference of the lengths of the\n * strings -- that is, the value:\n *
          \n     * this.length()-anotherString.length()\n     * 
          \n *\n * @param str1 the {@code String} to be compared.\n * @param str2 the {@code String} to be compared.\n * @return the value {@code 0} if the argument string is equal to\n * this string; a value less than {@code 0} if this string\n * is lexicographically less than the string argument; and a\n * value greater than {@code 0} if this string is\n * lexicographically greater than the string argument.\n */\n public static int compareString(String str1, String str2) {\n str1 = str1 == null ? \"\" : str1;\n str2 = str2 == null ? \"\" : str2;\n return str1.compareTo(str2);\n }\n\n /**\n * Compares two strings lexicographically, ignoring case\n * differences. This method returns an integer whose sign is that of\n * calling {@code compareTo} with normalized versions of the strings\n * where case differences have been eliminated by calling\n * {@code Character.toLowerCase(Character.toUpperCase(character))} on\n * each character.\n *

          \n * Note that this method does not take locale into account,\n * and will result in an unsatisfactory ordering for certain locales.\n * The java.text package provides collators to allow\n * locale-sensitive ordering.\n *\n * @param str1 the {@code String} to be compared.\n * @param str2 the {@code String} to be compared.\n * @return a negative integer, zero, or a positive integer as the\n * specified String is greater than, equal to, or less\n * than this String, ignoring case considerations.\n * @see java.text.Collator#compare(String, String)\n * @since 1.2\n */\n public static int compareStringIgnoreCase(String str1, String str2) {\n str1 = str1 == null ? \"\" : str1;\n str2 = str2 == null ? \"\" : str2;\n return str1.compareToIgnoreCase(str2);\n }\n // other\n //-----------------------------------------------------------------------\n\n /**\n *

          Splits the provided text into an array, separators specified.\n * This is an alternative to using StringTokenizer.

          \n *\n *

          The separator is not included in the returned String array.\n * Adjacent separators are treated as one separator.\n * For more control over the split use the StrTokenizer class.

          \n *\n *

          A null input String returns null.\n * A null separatorChars splits on whitespace.

          \n *\n *
          \n     * StringUtils.split(null, *)         = null\n     * StringUtils.split(\"\", *)           = []\n     * StringUtils.split(\"abc def\", null) = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc def\", \" \")  = [\"abc\", \"def\"]\n     * StringUtils.split(\"abc  def\", \" \") = [\"abc\", \"def\"]\n     * StringUtils.split(\"ab:cd:ef\", \":\") = [\"ab\", \"cd\", \"ef\"]\n     * 
          \n *\n * @param str the String to parse, may be null\n * @param separatorChars the characters used as the delimiters, null splits on whitespace\n * @return an array of parsed Strings, null if null String input\n */\n public static List split(String str, String separatorChars) {\n return Arrays.asList(StringUtils.split(str, separatorChars));\n }\n\n /** Joins the elements of the provided array into a single String containing the provided list of elements. */\n public static String join(List array, String separator) {\n if (array == null) {\n return null;\n }\n return StringUtils.join(array.toArray(), separator);\n }\n\n /** Checks if a String is empty (\"\") or null.*/\n public static boolean isEmpty(String str) {\n return str == null || str.length() == 0;\n }\n\n /** 忽略大小写比较相等 */\n public static boolean equalsIgnoreCase(String str1, String str2) {\n return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);\n }\n}\n", "file_name": "StringUdfSource.java", "human_label": "Return the first index of the searchStr in the given string.", "level": "project_runnable", "lineno": "134", "name": "indexOf", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[StringUtils]\", \"vars\" : \"[INDEX_NOT_FOUND]\" }", "package": "net.hasor.dataql.fx.basic", "project": "hasor-master" }, { "_id": "636766fc1a6d9265ec0177ef", "all_context": "{ \"class_level\" : \"import net.hasor.utils.ArrayUtils;\\nimport net.hasor.utils.ClassUtils;\\nimport java.lang.reflect.AccessibleObject;\\nimport java.lang.reflect.Field;\\nimport java.lang.reflect.Modifier;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nboolean appendStatics;\\nboolean appendTransients;\\nString[] excludeFieldNames;\\nClass upToClass;\\ntoString(Object object,ToStringStyle style);\\ntoString(Object object,ToStringStyle style,boolean outputTransients);\\ntoString(Object object,ToStringStyle style,boolean outputTransients,boolean outputStatics);\\ntoString(Object object,ToStringStyle style,boolean outputTransients,boolean outputStatics,Class reflectUpToClass);\\ntoStringExclude(Object object,String excludeFieldName);\\ntoStringExclude(Object object,Collection excludeFieldNames);\\ntoNoNullStringArray(Collection collection);\\ntoNoNullStringArray(Object[] array);\\ntoStringExclude(Object object,String[] excludeFieldNames);\\nReflectionToStringBuilder(Object object);\\nReflectionToStringBuilder(Object object,ToStringStyle style);\\nReflectionToStringBuilder(Object object,ToStringStyle style,StringBuffer buffer);\\nReflectionToStringBuilder(Object object,ToStringStyle style,StringBuffer buffer,Class reflectUpToClass,boolean outputTransients,boolean outputStatics);\\naccept(Field field);\\nappendFieldsIn(Class clazz);\\ngetExcludeFieldNames();\\ngetUpToClass();\\ngetValue(Field field);\\nisAppendStatics();\\nisAppendTransients();\\nreflectionAppendArray(Object array);\\nsetAppendStatics(boolean appendStatics);\\nsetAppendTransients(boolean appendTransients);\\nsetExcludeFieldNames(String[] excludeFieldNamesParam);\\nsetUpToClass(Class clazz);\\ntoString();\\ntoString(Object object);\\n\", \"repo_level\" : \"public interface ArrayUtils {static Map toMap(Object[] array);\\nstatic Object[] clone(Object[] array);\\nstatic long[] clone(long[] array);\\nstatic int[] clone(int[] array);\\nstatic short[] clone(short[] array);\\nstatic char[] clone(char[] array);\\nstatic byte[] clone(byte[] array);\\nstatic double[] clone(double[] array);\\nstatic float[] clone(float[] array);\\nstatic boolean[] clone(boolean[] array);\\nstatic String[] clone(String[] array);\\nstatic Object[] nullToEmpty(Object[] array);\\nstatic String[] nullToEmpty(String[] array);\\nstatic long[] nullToEmpty(long[] array);\\nstatic int[] nullToEmpty(int[] array);\\nstatic short[] nullToEmpty(short[] array);\\nstatic char[] nullToEmpty(char[] array);\\nstatic byte[] nullToEmpty(byte[] array);\\nstatic double[] nullToEmpty(double[] array);\\nstatic float[] nullToEmpty(float[] array);\\nstatic boolean[] nullToEmpty(boolean[] array);\\nstatic Long[] nullToEmpty(Long[] array);\\nstatic Integer[] nullToEmpty(Integer[] array);\\nstatic Short[] nullToEmpty(Short[] array);\\nstatic Character[] nullToEmpty(Character[] array);\\nstatic Byte[] nullToEmpty(Byte[] array);\\nstatic Double[] nullToEmpty(Double[] array);\\nstatic Float[] nullToEmpty(Float[] array);\\nstatic Boolean[] nullToEmpty(Boolean[] array);\\nstatic Object[] subarray(Object[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic long[] subarray(long[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic int[] subarray(int[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic short[] subarray(short[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic char[] subarray(char[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic byte[] subarray(byte[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic double[] subarray(double[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic float[] subarray(float[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic boolean[] subarray(boolean[] array,int startIndexInclusive,int endIndexExclusive);\\nstatic boolean isSameLength(Object[] array1,Object[] array2);\\nstatic boolean isSameLength(long[] array1,long[] array2);\\nstatic boolean isSameLength(int[] array1,int[] array2);\\nstatic boolean isSameLength(short[] array1,short[] array2);\\nstatic boolean isSameLength(char[] array1,char[] array2);\\nstatic boolean isSameLength(byte[] array1,byte[] array2);\\nstatic boolean isSameLength(double[] array1,double[] array2);\\nstatic boolean isSameLength(float[] array1,float[] array2);\\nstatic boolean isSameLength(boolean[] array1,boolean[] array2);\\nstatic int getLength(Object array);\\nstatic boolean isSameType(Object array1,Object array2);\\nstatic void reverse(Object[] array);\\nstatic void reverse(long[] array);\\nstatic void reverse(int[] array);\\nstatic void reverse(short[] array);\\nstatic void reverse(char[] array);\\nstatic void reverse(byte[] array);\\nstatic void reverse(double[] array);\\nstatic void reverse(float[] array);\\nstatic void reverse(boolean[] array);\\nstatic int indexOf(Object[] array,Object objectToFind);\\nstatic int indexOf(Object[] array,Object objectToFind,int startIndex);\\nstatic int lastIndexOf(Object[] array,Object objectToFind);\\nstatic int lastIndexOf(Object[] array,Object objectToFind,int startIndex);\\nstatic boolean contains(Object[] array,Object objectToFind);\\nstatic int indexOf(long[] array,long valueToFind);\\nstatic int indexOf(long[] array,long valueToFind,int startIndex);\\nstatic int lastIndexOf(long[] array,long valueToFind);\\nstatic int lastIndexOf(long[] array,long valueToFind,int startIndex);\\nstatic boolean contains(long[] array,long valueToFind);\\nstatic int indexOf(int[] array,int valueToFind);\\nstatic int indexOf(int[] array,int valueToFind,int startIndex);\\nstatic int lastIndexOf(int[] array,int valueToFind);\\nstatic int lastIndexOf(int[] array,int valueToFind,int startIndex);\\nstatic boolean contains(int[] array,int valueToFind);\\nstatic int indexOf(short[] array,short valueToFind);\\nstatic int indexOf(short[] array,short valueToFind,int startIndex);\\nstatic int lastIndexOf(short[] array,short valueToFind);\\nstatic int lastIndexOf(short[] array,short valueToFind,int startIndex);\\nstatic boolean contains(short[] array,short valueToFind);\\nstatic int indexOf(char[] array,char valueToFind);\\nstatic int indexOf(char[] array,char valueToFind,int startIndex);\\nstatic int lastIndexOf(char[] array,char valueToFind);\\nstatic int lastIndexOf(char[] array,char valueToFind,int startIndex);\\nstatic boolean contains(char[] array,char valueToFind);\\nstatic int indexOf(byte[] array,byte valueToFind);\\nstatic int indexOf(byte[] array,byte valueToFind,int startIndex);\\nstatic int lastIndexOf(byte[] array,byte valueToFind);\\nstatic int lastIndexOf(byte[] array,byte valueToFind,int startIndex);\\nstatic boolean contains(byte[] array,byte valueToFind);\\nstatic int indexOf(double[] array,double valueToFind);\\nstatic int indexOf(double[] array,double valueToFind,double tolerance);\\nstatic int indexOf(double[] array,double valueToFind,int startIndex);\\nstatic int indexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nstatic int lastIndexOf(double[] array,double valueToFind);\\nstatic int lastIndexOf(double[] array,double valueToFind,double tolerance);\\nstatic int lastIndexOf(double[] array,double valueToFind,int startIndex);\\nstatic int lastIndexOf(double[] array,double valueToFind,int startIndex,double tolerance);\\nstatic boolean contains(double[] array,double valueToFind);\\nstatic boolean contains(double[] array,double valueToFind,double tolerance);\\nstatic int indexOf(float[] array,float valueToFind);\\nstatic int indexOf(float[] array,float valueToFind,int startIndex);\\nstatic int lastIndexOf(float[] array,float valueToFind);\\nstatic int lastIndexOf(float[] array,float valueToFind,int startIndex);\\nstatic boolean contains(float[] array,float valueToFind);\\nstatic int indexOf(boolean[] array,boolean valueToFind);\\nstatic int indexOf(boolean[] array,boolean valueToFind,int startIndex);\\nstatic int lastIndexOf(boolean[] array,boolean valueToFind);\\nstatic int lastIndexOf(boolean[] array,boolean valueToFind,int startIndex);\\nstatic boolean contains(boolean[] array,boolean valueToFind);\\nstatic char[] toPrimitive(Character[] array);\\nstatic char[] toPrimitive(Character[] array,char valueForNull);\\nstatic Character[] toObject(char[] array);\\nstatic long[] toPrimitive(Long[] array);\\nstatic long[] toPrimitive(Long[] array,long valueForNull);\\nstatic Long[] toObject(long[] array);\\nstatic int[] toPrimitive(Integer[] array);\\nstatic int[] toPrimitive(Integer[] array,int valueForNull);\\nstatic Integer[] toObject(int[] array);\\nstatic short[] toPrimitive(Short[] array);\\nstatic short[] toPrimitive(Short[] array,short valueForNull);\\nstatic Short[] toObject(short[] array);\\nstatic byte[] toPrimitive(Byte[] array);\\nstatic byte[] toPrimitive(Byte[] array,byte valueForNull);\\nstatic Byte[] toObject(byte[] array);\\nstatic double[] toPrimitive(Double[] array);\\nstatic double[] toPrimitive(Double[] array,double valueForNull);\\nstatic Double[] toObject(double[] array);\\nstatic float[] toPrimitive(Float[] array);\\nstatic float[] toPrimitive(Float[] array,float valueForNull);\\nstatic Float[] toObject(float[] array);\\nstatic boolean[] toPrimitive(Boolean[] array);\\nstatic boolean[] toPrimitive(Boolean[] array,boolean valueForNull);\\nstatic Boolean[] toObject(boolean[] array);\\nstatic boolean isEmpty(Object[] array);\\nstatic boolean isEmpty(long[] array);\\nstatic boolean isEmpty(int[] array);\\nstatic boolean isEmpty(short[] array);\\nstatic boolean isEmpty(char[] array);\\nstatic boolean isEmpty(byte[] array);\\nstatic boolean isEmpty(double[] array);\\nstatic boolean isEmpty(float[] array);\\nstatic boolean isEmpty(boolean[] array);\\nstatic boolean isNotEmpty(Object[] array);\\nstatic boolean isNotEmpty(long[] array);\\nstatic boolean isNotEmpty(int[] array);\\nstatic boolean isNotEmpty(short[] array);\\nstatic boolean isNotEmpty(char[] array);\\nstatic boolean isNotEmpty(byte[] array);\\nstatic boolean isNotEmpty(double[] array);\\nstatic boolean isNotEmpty(float[] array);\\nstatic boolean isNotEmpty(boolean[] array);\\nstatic Object[] addAll(Object[] array1,Object[] array2);\\nstatic boolean[] addAll(boolean[] array1,boolean[] array2);\\nstatic char[] addAll(char[] array1,char[] array2);\\nstatic byte[] addAll(byte[] array1,byte[] array2);\\nstatic short[] addAll(short[] array1,short[] array2);\\nstatic int[] addAll(int[] array1,int[] array2);\\nstatic long[] addAll(long[] array1,long[] array2);\\nstatic float[] addAll(float[] array1,float[] array2);\\nstatic double[] addAll(double[] array1,double[] array2);\\nstatic String[] addAll(String[] array1,String[] array2);\\nstatic T[] add(T[] array,T element);\\nstatic boolean[] add(boolean[] array,boolean element);\\nstatic byte[] add(byte[] array,byte element);\\nstatic char[] add(char[] array,char element);\\nstatic double[] add(double[] array,double element);\\nstatic float[] add(float[] array,float element);\\nstatic int[] add(int[] array,int element);\\nstatic long[] add(long[] array,long element);\\nstatic short[] add(short[] array,short element);\\nstatic Object[] add(Object[] array,int index,Object element);\\nstatic boolean[] add(boolean[] array,int index,boolean element);\\nstatic char[] add(char[] array,int index,char element);\\nstatic byte[] add(byte[] array,int index,byte element);\\nstatic short[] add(short[] array,int index,short element);\\nstatic int[] add(int[] array,int index,int element);\\nstatic long[] add(long[] array,int index,long element);\\nstatic float[] add(float[] array,int index,float element);\\nstatic double[] add(double[] array,int index,double element);\\nstatic Object[] remove(Object[] array,int index);\\nstatic Object[] removeElement(Object[] array,Object element);\\nstatic boolean[] remove(boolean[] array,int index);\\nstatic boolean[] removeElement(boolean[] array,boolean element);\\nstatic byte[] remove(byte[] array,int index);\\nstatic byte[] removeElement(byte[] array,byte element);\\nstatic char[] remove(char[] array,int index);\\nstatic char[] removeElement(char[] array,char element);\\nstatic double[] remove(double[] array,int index);\\nstatic double[] removeElement(double[] array,double element);\\nstatic float[] remove(float[] array,int index);\\nstatic float[] removeElement(float[] array,float element);\\nstatic int[] remove(int[] array,int index);\\nstatic int[] removeElement(int[] array,int element);\\nstatic long[] remove(long[] array,int index);\\nstatic long[] removeElement(long[] array,long element);\\nstatic short[] remove(short[] array,int index);\\nstatic short[] removeElement(short[] array,short element);\\nstatic Object[] clearNull(Object[] arr);\\n }\\npublic interface ClassUtils {static String getShortClassName(Object object,String valueIfNull);\\nstatic String getShortClassName(Class cls);\\nstatic String getShortClassName(String className);\\nstatic String getPackageName(Object object,String valueIfNull);\\nstatic String getPackageName(Class cls);\\nstatic String getPackageName(String className);\\nstatic List> getAllSuperclasses(Class cls);\\nstatic List> getAllInterfaces(Class cls);\\nstatic List> convertClassNamesToClasses(List classNames);\\nstatic List convertClassesToClassNames(List classes);\\nstatic boolean isAssignable(Class[] classArray,Class[] toClassArray);\\nstatic boolean isAssignable(Class[] classArray,Class[] toClassArray,boolean autoboxing);\\nstatic boolean isAssignable(Class cls,Class toClass);\\nstatic boolean isAssignable(Class cls,Class toClass,boolean autoboxing);\\nstatic Class primitiveToWrapper(Class cls);\\nstatic Class[] primitivesToWrappers(Class[] classes);\\nstatic Class wrapperToPrimitive(Class cls);\\nstatic Class[] wrappersToPrimitives(Class[] classes);\\nstatic boolean isInnerClass(Class cls);\\nstatic Class getClass(ClassLoader classLoader,String className,boolean initialize);\\nstatic Class getClass(ClassLoader classLoader,String className);\\nstatic Class getClass(String className);\\nstatic Class getClass(String className,boolean initialize);\\nstatic Method getPublicMethod(Class cls,String methodName,Class parameterTypes);\\nstatic Class[] toClass(Object[] array);\\nstatic String getShortCanonicalName(Object object,String valueIfNull);\\nstatic String getShortCanonicalName(Class cls);\\nstatic String getShortCanonicalName(String canonicalName);\\nstatic String getPackageCanonicalName(Object object,String valueIfNull);\\nstatic String getPackageCanonicalName(Class cls);\\nstatic String getPackageCanonicalName(String canonicalName);\\nstatic ClassLoader getClassLoader(ClassLoader classLoader);\\nstatic boolean isLangClass(Class target);\\nstatic String getDescName(Class type);\\nstatic String getDescNameWithOutModifiers(Method method);\\nstatic String getDescName(Method method);\\nstatic Class getSuperClassGenricType(Class clazz,int index);\\nstatic T newInstance(Class clazz);\\n }\\n\" }", "class_name": "ReflectionToStringBuilder", "code": "static String[] toNoNullStringArray(Object[] array){\n ArrayList list=new ArrayList(array.length);\n for (int i=0; i < array.length; i++) {\n Object e=array[i];\n if (e != null) {\n list.add(e.toString());\n }\n }\n return (String[])list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);\n}\n", "docstring": "/** \n * Returns a new array of Strings without null elements. Internal method used to normalize exclude lists (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException}if an array element is null.\n * @param array The array to check\n * @return The given array or a new array without null.\n */\n", "end_lineno": "346", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.builder;\nimport net.hasor.utils.ArrayUtils;\nimport net.hasor.utils.ClassUtils;\n\nimport java.lang.reflect.AccessibleObject;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\n\n/**\n *

          \n * Assists in implementing {@link Object#toString()} methods using reflection.\n *

          \n *\n *

          \n * This class uses reflection to determine the fields to append. Because these fields are usually private, the class\n * uses {@link java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[], boolean)} to\n * change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are\n * set up correctly.\n *

          \n *\n *

          \n * A typical invocation for this method would look like:\n *

          \n *\n *
          \n * public String toString() {\n *   return ReflectionToStringBuilder.toString(this);\n * }
          \n *\n *\n *\n *

          \n * You can also use the builder to debug 3rd party objects:\n *

          \n *\n *
          \n * System.out.println(\"An object: \" + ReflectionToStringBuilder.toString(anObject));
          \n *\n *\n *\n *

          \n * A subclass can control field output by overriding the methods:\n *

            \n *
          • {@link #accept(java.lang.reflect.Field)}
          • \n *
          • {@link #getValue(java.lang.reflect.Field)}
          • \n *
          \n *

          \n *

          \n * For example, this method does not include the password field in the returned\n * String:\n *

          \n *\n *
          \n * public String toString() {\n *     return (new ReflectionToStringBuilder(this) {\n *         protected boolean accept(Field f) {\n *             return super.accept(f) && !f.getName().equals(\"password\");\n *         }\n *     }).toString();\n * }
          \n *\n *\n *\n *

          \n * The exact format of the toString is determined by the {@link ToStringStyle} passed into the\n * constructor.\n *

          \n *\n * @author Apache Software Foundation\n * @author Gary Gregory\n * @author Pete Gieser\n * @since 2.0\n * @version $Id: ReflectionToStringBuilder.java 905636 2010-02-02 14:03:32Z niallp $\n */\npublic class ReflectionToStringBuilder extends ToStringBuilder {\n /**\n *

          \n * Builds a toString value using the default ToStringStyle through reflection.\n *

          \n *\n *

          \n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

          \n *\n *

          \n * Transient members will be not be included, as they are likely derived. Static fields will not be included.\n * Superclass fields will be appended.\n *

          \n *\n * @param object\n * the Object to be output\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object is null\n */\n public static String toString(Object object) {\n return toString(object, null, false, false, null);\n }\n\n /**\n *

          \n * Builds a toString value through reflection.\n *

          \n *\n *

          \n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

          \n *\n *

          \n * Transient members will be not be included, as they are likely derived. Static fields will not be included.\n * Superclass fields will be appended.\n *

          \n *\n *

          \n * If the style is null, the default ToStringStyle is used.\n *

          \n *\n * @param object\n * the Object to be output\n * @param style\n * the style of the toString to create, may be null\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object or ToStringStyle is null\n */\n public static String toString(Object object, ToStringStyle style) {\n return toString(object, style, false, false, null);\n }\n\n /**\n *

          \n * Builds a toString value through reflection.\n *

          \n *\n *

          \n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

          \n *\n *

          \n * If the outputTransients is true, transient members will be output, otherwise they\n * are ignored, as they are likely derived fields, and not part of the value of the Object.\n *

          \n *\n *

          \n * Static fields will not be included. Superclass fields will be appended.\n *

          \n *\n *

          \n * If the style is null, the default ToStringStyle is used.\n *

          \n *\n * @param object\n * the Object to be output\n * @param style\n * the style of the toString to create, may be null\n * @param outputTransients\n * whether to include transient fields\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object is null\n */\n public static String toString(Object object, ToStringStyle style, boolean outputTransients) {\n return toString(object, style, outputTransients, false, null);\n }\n\n /**\n *

          \n * Builds a toString value through reflection.\n *

          \n *\n *

          \n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

          \n *\n *

          \n * If the outputTransients is true, transient fields will be output, otherwise they\n * are ignored, as they are likely derived fields, and not part of the value of the Object.\n *

          \n *\n *

          \n * If the outputStatics is true, static fields will be output, otherwise they are\n * ignored.\n *

          \n *\n *

          \n * Static fields will not be included. Superclass fields will be appended.\n *

          \n *\n *

          \n * If the style is null, the default ToStringStyle is used.\n *

          \n *\n * @param object\n * the Object to be output\n * @param style\n * the style of the toString to create, may be null\n * @param outputTransients\n * whether to include transient fields\n * @param outputStatics\n * whether to include transient fields\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object is null\n * @since 2.1\n */\n public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics) {\n return toString(object, style, outputTransients, outputStatics, null);\n }\n\n /**\n *

          \n * Builds a toString value through reflection.\n *

          \n *\n *

          \n * It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will\n * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is\n * also not as efficient as testing explicitly.\n *

          \n *\n *

          \n * If the outputTransients is true, transient fields will be output, otherwise they\n * are ignored, as they are likely derived fields, and not part of the value of the Object.\n *

          \n *\n *

          \n * If the outputStatics is true, static fields will be output, otherwise they are\n * ignored.\n *

          \n *\n *

          \n * Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as\n * java.lang.Object.\n *

          \n *\n *

          \n * If the style is null, the default ToStringStyle is used.\n *

          \n *\n * @param object\n * the Object to be output\n * @param style\n * the style of the toString to create, may be null\n * @param outputTransients\n * whether to include transient fields\n * @param outputStatics\n * whether to include static fields\n * @param reflectUpToClass\n * the superclass to reflect up to (inclusive), may be null\n * @return the String result\n * @throws IllegalArgumentException\n * if the Object is null\n * @since 2.1\n */\n public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics, Class reflectUpToClass) {\n return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics).toString();\n }\n\n /**\n * Builds a String for a toString method excluding the given field name.\n *\n * @param object\n * The object to \"toString\".\n * @param excludeFieldName\n * The field name to exclude\n * @return The toString value.\n */\n public static String toStringExclude(Object object, final String excludeFieldName) {\n return toStringExclude(object, new String[] { excludeFieldName });\n }\n\n /**\n * Builds a String for a toString method excluding the given field names.\n *\n * @param object\n * The object to \"toString\".\n * @param excludeFieldNames\n * The field names to exclude. Null excludes nothing.\n * @return The toString value.\n */\n public static String toStringExclude(Object object, Collection /*String*/ excludeFieldNames) {\n return toStringExclude(object, toNoNullStringArray(excludeFieldNames));\n }\n\n /**\n * Converts the given Collection into an array of Strings. The returned array does not contain null\n * entries. Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} if an array element \n * is null.\n *\n * @param collection\n * The collection to convert\n * @return A new array of Strings.\n */\n static String[] toNoNullStringArray(Collection collection) {\n if (collection == null) {\n return ArrayUtils.EMPTY_STRING_ARRAY;\n }\n return toNoNullStringArray(collection.toArray());\n }\n\n /**\n * Returns a new array of Strings without null elements. Internal method used to normalize exclude lists\n * (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException}\n * if an array element is null.\n *\n * @param array\n * The array to check\n * @return The given array or a new array without null.\n */\n static String[] toNoNullStringArray(Object[] array) {\n ArrayList list = new ArrayList(array.length);\n for (int i = 0; i < array.length; i++) {\n Object e = array[i];\n if (e != null) {\n list.add(e.toString());\n }\n }\n return (String[]) list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);\n }\n\n /**\n * Builds a String for a toString method excluding the given field names.\n *\n * @param object\n * The object to \"toString\".\n * @param excludeFieldNames\n * The field names to exclude\n * @return The toString value.\n */\n public static String toStringExclude(Object object, String[] excludeFieldNames) {\n return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString();\n }\n\n /**\n * Whether or not to append static fields.\n */\n private boolean appendStatics = false;\n /**\n * Whether or not to append transient fields.\n */\n private boolean appendTransients = false;\n /**\n * Which field names to exclude from output. Intended for fields like \"password\".\n */\n private String[] excludeFieldNames;\n /**\n * The last super class to stop appending fields for.\n */\n private Class upToClass = null;\n\n /**\n *

          \n * Constructor.\n *

          \n *\n *

          \n * This constructor outputs using the default style set with setDefaultStyle.\n *

          \n *\n * @param object\n * the Object to build a toString for, must not be null\n * @throws IllegalArgumentException\n * if the Object passed in is null\n */\n public ReflectionToStringBuilder(Object object) {\n super(object);\n }\n\n /**\n *

          \n * Constructor.\n *

          \n *\n *

          \n * If the style is null, the default style is used.\n *

          \n *\n * @param object\n * the Object to build a toString for, must not be null\n * @param style\n * the style of the toString to create, may be null\n * @throws IllegalArgumentException\n * if the Object passed in is null\n */\n public ReflectionToStringBuilder(Object object, ToStringStyle style) {\n super(object, style);\n }\n\n /**\n *

          \n * Constructor.\n *

          \n *\n *

          \n * If the style is null, the default style is used.\n *

          \n *\n *

          \n * If the buffer is null, a new one is created.\n *

          \n *\n * @param object\n * the Object to build a toString for\n * @param style\n * the style of the toString to create, may be null\n * @param buffer\n * the StringBuffer to populate, may be null\n * @throws IllegalArgumentException\n * if the Object passed in is null\n */\n public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) {\n super(object, style, buffer);\n }\n\n /**\n * Constructor.\n *\n * @param object\n * the Object to build a toString for\n * @param style\n * the style of the toString to create, may be null\n * @param buffer\n * the StringBuffer to populate, may be null\n * @param reflectUpToClass\n * the superclass to reflect up to (inclusive), may be null\n * @param outputTransients\n * whether to include transient fields\n * @param outputStatics\n * whether to include static fields\n * @since 2.1\n */\n public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer, Class reflectUpToClass, boolean outputTransients, boolean outputStatics) {\n super(object, style, buffer);\n this.setUpToClass(reflectUpToClass);\n this.setAppendTransients(outputTransients);\n this.setAppendStatics(outputStatics);\n }\n\n /**\n * Returns whether or not to append the given Field.\n *
            \n *
          • Transient fields are appended only if {@link #isAppendTransients()} returns true.\n *
          • Static fields are appended only if {@link #isAppendStatics()} returns true.\n *
          • Inner class fields are not appened.
          • \n *
          \n *\n * @param field The Field to test.\n * @return Whether or not to append the given Field.\n */\n protected boolean accept(Field field) {\n if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {\n // Reject field from inner class.\n return false;\n }\n if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) {\n // Reject transient fields.\n return false;\n }\n if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) {\n // Reject static fields.\n return false;\n }\n if (this.getExcludeFieldNames() != null && Arrays.binarySearch(this.getExcludeFieldNames(), field.getName()) >= 0) {\n // Reject fields from the getExcludeFieldNames list.\n return false;\n }\n return true;\n }\n\n /**\n *

          \n * Appends the fields and values defined by the given object of the given Class.\n *

          \n *\n *

          \n * If a cycle is detected as an object is "toString()'ed", such an object is rendered as if\n * Object.toString() had been called and not implemented by the object.\n *

          \n *\n * @param clazz The class of object parameter\n */\n protected void appendFieldsIn(Class clazz) {\n if (clazz.isArray()) {\n this.reflectionAppendArray(this.getObject());\n return;\n }\n Field[] fields = clazz.getDeclaredFields();\n AccessibleObject.setAccessible(fields, true);\n for (int i = 0; i < fields.length; i++) {\n Field field = fields[i];\n String fieldName = field.getName();\n if (this.accept(field)) {\n try {\n // Warning: Field.get(Object) creates wrappers objects\n // for primitive types.\n Object fieldValue = this.getValue(field);\n this.append(fieldName, fieldValue);\n } catch (IllegalAccessException ex) {\n //this can't happen. Would get a Security exception\n // instead\n //throw a runtime exception in case the impossible\n // happens.\n throw new InternalError(\"Unexpected IllegalAccessException: \" + ex.getMessage());\n }\n }\n }\n }\n\n /**\n * @return Returns the excludeFieldNames.\n */\n public String[] getExcludeFieldNames() {\n return this.excludeFieldNames;\n }\n\n /**\n *

          \n * Gets the last super class to stop appending fields for.\n *

          \n *\n * @return The last super class to stop appending fields for.\n */\n public Class getUpToClass() {\n return this.upToClass;\n }\n\n /**\n *

          \n * Calls java.lang.reflect.Field.get(Object).\n *

          \n *\n * @param field The Field to query.\n * @return The Object from the given Field.\n *\n * @throws IllegalArgumentException see {@link java.lang.reflect.Field#get(Object)}\n * @throws IllegalAccessException see {@link java.lang.reflect.Field#get(Object)}\n * @see java.lang.reflect.Field#get(Object)\n */\n protected Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException {\n return field.get(this.getObject());\n }\n\n /**\n *

          \n * Gets whether or not to append static fields.\n *

          \n *\n * @return Whether or not to append static fields.\n * @since 2.1\n */\n public boolean isAppendStatics() {\n return this.appendStatics;\n }\n\n /**\n *

          \n * Gets whether or not to append transient fields.\n *

          \n *\n * @return Whether or not to append transient fields.\n */\n public boolean isAppendTransients() {\n return this.appendTransients;\n }\n\n /**\n *

          \n * Append to the toString an Object array.\n *

          \n *\n * @param array\n * the array to add to the toString\n * @return this\n */\n public ToStringBuilder reflectionAppendArray(Object array) {\n this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array);\n return this;\n }\n\n /**\n *

          \n * Sets whether or not to append static fields.\n *

          \n *\n * @param appendStatics\n * Whether or not to append static fields.\n * @since 2.1\n */\n public void setAppendStatics(boolean appendStatics) {\n this.appendStatics = appendStatics;\n }\n\n /**\n *

          \n * Sets whether or not to append transient fields.\n *

          \n *\n * @param appendTransients Whether or not to append transient fields.\n */\n public void setAppendTransients(boolean appendTransients) {\n this.appendTransients = appendTransients;\n }\n\n /**\n * Sets the field names to exclude.\n *\n * @param excludeFieldNamesParam\n * The excludeFieldNames to excluding from toString or null.\n * @return this\n */\n public ReflectionToStringBuilder setExcludeFieldNames(String[] excludeFieldNamesParam) {\n if (excludeFieldNamesParam == null) {\n this.excludeFieldNames = null;\n } else {\n this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam);\n Arrays.sort(this.excludeFieldNames);\n }\n return this;\n }\n\n /**\n *

          \n * Sets the last super class to stop appending fields for.\n *

          \n *\n * @param clazz\n * The last super class to stop appending fields for.\n */\n public void setUpToClass(Class clazz) {\n if (clazz != null) {\n Object object = getObject();\n if (object != null && clazz.isInstance(object) == false) {\n throw new IllegalArgumentException(\"Specified class is not a superclass of the object\");\n }\n }\n this.upToClass = clazz;\n }\n\n /**\n *

          \n * Gets the String built by this builder.\n *

          \n *\n * @return the built string\n */\n public String toString() {\n if (this.getObject() == null) {\n return this.getStyle().getNullText();\n }\n Class clazz = this.getObject().getClass();\n this.appendFieldsIn(clazz);\n while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) {\n clazz = clazz.getSuperclass();\n this.appendFieldsIn(clazz);\n }\n return super.toString();\n }\n}\n", "file_name": "ReflectionToStringBuilder.java", "human_label": "Return a new array of strings converted from the elements which are not null of the given array,if the size of the array is zero,it will throw an exception.", "level": "project_runnable", "lineno": "328", "name": "toNoNullStringArray", "oracle_context": "{ \"apis\" : \"[add, toString, toArray]\", \"classes\" : \"[ArrayList, Object, ArrayUtils]\", \"vars\" : \"[length, EMPTY_STRING_ARRAY]\" }", "package": "net.hasor.utils.builder", "project": "hasor-master" }, { "_id": "636767061a6d9265ec01794a", "all_context": "{ \"class_level\" : \"import java.io.File;\\nimport java.util.Collection;\\nchar EXTENSION_SEPARATOR;\\nString EXTENSION_SEPARATOR_STR;\\nchar UNIX_SEPARATOR;\\nchar WINDOWS_SEPARATOR;\\nchar SYSTEM_SEPARATOR;\\nchar OTHER_SEPARATOR;\\nFilenameUtils();\\nisSeparator(char ch);\\nnormalize(String filename);\\nnormalize(String filename,boolean unixSeparator);\\nnormalizeNoEndSeparator(String filename);\\nnormalizeNoEndSeparator(String filename,boolean unixSeparator);\\ndoNormalize(String filename,char separator,boolean keepSeparator);\\nconcat(String basePath,String fullFilenameToAdd);\\nseparatorsToUnix(String path);\\nseparatorsToWindows(String path);\\nseparatorsToSystem(String path);\\ngetPrefixLength(String filename);\\nindexOfLastSeparator(String filename);\\nindexOfExtension(String filename);\\ngetPrefix(String filename);\\ngetPath(String filename);\\ngetPathNoEndSeparator(String filename);\\ndoGetPath(String filename,int separatorAdd);\\ngetFullPath(String filename);\\ngetFullPathNoEndSeparator(String filename);\\ndoGetFullPath(String filename,boolean includeSeparator);\\ngetName(String filename);\\ngetBaseName(String filename);\\ngetExtension(String filename);\\nremoveExtension(String filename);\\nisExtension(String filename,String extension);\\nisExtension(String filename,String[] extensions);\\nisExtension(String filename,Collection extensions);\\nisSystemWindows();\\n\", \"repo_level\" : \"\" }", "class_name": "FilenameUtils", "code": "public static int indexOfExtension(String filename){\n if (filename == null) {\n return -1;\n }\n int extensionPos=filename.lastIndexOf(EXTENSION_SEPARATOR);\n int lastSeparator=indexOfLastSeparator(filename);\n return lastSeparator > extensionPos ? -1 : extensionPos;\n}\n", "docstring": "/** \n * Returns the index of the last extension separator character, which is a dot.

          This method also checks that there is no directory separator after the last dot. To do this it uses {@link #indexOfLastSeparator(String)} which willhandle a file in either Unix or Windows format.

          The output will be the same irrespective of the machine that the code is running on.\n * @param filename the filename to find the last path separator in, null returns -1\n * @return the index of the last separator character, or -1 if thereis no such character\n */\n", "end_lineno": "657", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils.io;\nimport java.io.File;\nimport java.util.Collection;\n\n/**\n * General filename and filepath manipulation utilities.\n *

          \n * When dealing with filenames you can hit problems when moving from a Windows\n * based development machine to a Unix based production machine.\n * This class aims to help avoid those problems.\n *

          \n * NOTE: You may be able to avoid using this class entirely simply by\n * using JDK {@link File File} objects and the two argument constructor\n * {@link File#File(File, String) File(File,String)}.\n *

          \n * Most methods on this class are designed to work the same on both Unix and Windows.\n * Those that don't include 'System', 'Unix' or 'Windows' in their name.\n *

          \n * Most methods recognise both separators (forward and back), and both\n * sets of prefixes. See the javadoc of each method for details.\n *

          \n * This class defines six components within a filename\n * (example C:\\dev\\project\\file.txt):\n *

            \n *
          • the prefix - C:\\
          • \n *
          • the path - dev\\project\\
          • \n *
          • the full path - C:\\dev\\project\\
          • \n *
          • the name - file.txt
          • \n *
          • the base name - file
          • \n *
          • the extension - txt
          • \n *
          \n * Note that this class works best if directory filenames end with a separator.\n * If you omit the last separator, it is impossible to determine if the filename\n * corresponds to a file or a directory. As a result, we have chosen to say\n * it corresponds to a file.\n *

          \n * This class only supports Unix and Windows style names.\n * Prefixes are matched as follows:\n *

          \n * Windows:\n * a\\b\\c.txt           --> \"\"          --> relative\n * \\a\\b\\c.txt          --> \"\\\"         --> current drive absolute\n * C:a\\b\\c.txt         --> \"C:\"        --> drive relative\n * C:\\a\\b\\c.txt        --> \"C:\\\"       --> absolute\n * \\\\server\\a\\b\\c.txt  --> \"\\\\server\\\" --> UNC\n *\n * Unix:\n * a/b/c.txt           --> \"\"          --> relative\n * /a/b/c.txt          --> \"/\"         --> absolute\n * ~/a/b/c.txt         --> \"~/\"        --> current user\n * ~                   --> \"~/\"        --> current user (slash added)\n * ~user/a/b/c.txt     --> \"~user/\"    --> named user\n * ~user               --> \"~user/\"    --> named user (slash added)\n * 
          \n * Both prefix styles are matched always, irrespective of the machine that you are\n * currently running on.\n *

          \n * Origin of code: Excalibur, Alexandria, Tomcat, Commons-Utils.\n *\n * @version $Id: FilenameUtils.java 1307462 2012-03-30 15:13:11Z ggregory $\n * @since 1.1\n */\npublic class FilenameUtils {\n /**\n * The extension separator character.\n * @since 1.4\n */\n public static final char EXTENSION_SEPARATOR = '.';\n /**\n * The extension separator String.\n * @since 1.4\n */\n public static final String EXTENSION_SEPARATOR_STR = Character.toString(EXTENSION_SEPARATOR);\n /**\n * The Unix separator character.\n */\n private static final char UNIX_SEPARATOR = '/';\n /**\n * The Windows separator character.\n */\n private static final char WINDOWS_SEPARATOR = '\\\\';\n /**\n * The system separator character.\n */\n private static final char SYSTEM_SEPARATOR = File.separatorChar;\n /**\n * The separator character that is the opposite of the system separator.\n */\n private static final char OTHER_SEPARATOR;\n\n static {\n if (isSystemWindows()) {\n OTHER_SEPARATOR = UNIX_SEPARATOR;\n } else {\n OTHER_SEPARATOR = WINDOWS_SEPARATOR;\n }\n }\n\n /**\n * Instances should NOT be constructed in standard programming.\n */\n public FilenameUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n * Determines if Windows file system is in use.\n *\n * @return true if the system is Windows\n */\n static boolean isSystemWindows() {\n return SYSTEM_SEPARATOR == WINDOWS_SEPARATOR;\n }\n //-----------------------------------------------------------------------\n\n /**\n * Checks if the character is a separator.\n *\n * @param ch the character to check\n * @return true if it is a separator character\n */\n private static boolean isSeparator(char ch) {\n return ch == UNIX_SEPARATOR || ch == WINDOWS_SEPARATOR;\n }\n //-----------------------------------------------------------------------\n\n /**\n * Normalizes a path, removing double and single dot path steps.\n *

          \n * This method normalizes a path to a standard format.\n * The input may contain separators in either Unix or Windows format.\n * The output will contain separators in the format of the system.\n *

          \n * A trailing slash will be retained.\n * A double slash will be merged to a single slash (but UNC names are handled).\n * A single dot path segment will be removed.\n * A double dot will cause that path segment and the one before to be removed.\n * If the double dot has no parent path segment to work with, {@code null}\n * is returned.\n *

          \n * The output will be the same on both Unix and Windows except\n * for the separator character.\n *

          \n     * /foo//               -->   /foo/\n     * /foo/./              -->   /foo/\n     * /foo/../bar          -->   /bar\n     * /foo/../bar/         -->   /bar/\n     * /foo/../bar/../baz   -->   /baz\n     * //foo//./bar         -->   /foo/bar\n     * /../                 -->   null\n     * ../foo               -->   null\n     * foo/bar/..           -->   foo/\n     * foo/../../bar        -->   null\n     * foo/../bar           -->   bar\n     * //server/foo/../bar  -->   //server/bar\n     * //server/../bar      -->   null\n     * C:\\foo\\..\\bar        -->   C:\\bar\n     * C:\\..\\bar            -->   null\n     * ~/foo/../bar/        -->   ~/bar/\n     * ~/../bar             -->   null\n     * 
          \n * (Note the file separator returned will be correct for Windows/Unix)\n *\n * @param filename the filename to normalize, null returns null\n * @return the normalized filename, or null if invalid\n */\n public static String normalize(String filename) {\n return doNormalize(filename, SYSTEM_SEPARATOR, true);\n }\n\n /**\n * Normalizes a path, removing double and single dot path steps.\n *

          \n * This method normalizes a path to a standard format.\n * The input may contain separators in either Unix or Windows format.\n * The output will contain separators in the format specified.\n *

          \n * A trailing slash will be retained.\n * A double slash will be merged to a single slash (but UNC names are handled).\n * A single dot path segment will be removed.\n * A double dot will cause that path segment and the one before to be removed.\n * If the double dot has no parent path segment to work with, {@code null}\n * is returned.\n *

          \n * The output will be the same on both Unix and Windows except\n * for the separator character.\n *

          \n     * /foo//               -->   /foo/\n     * /foo/./              -->   /foo/\n     * /foo/../bar          -->   /bar\n     * /foo/../bar/         -->   /bar/\n     * /foo/../bar/../baz   -->   /baz\n     * //foo//./bar         -->   /foo/bar\n     * /../                 -->   null\n     * ../foo               -->   null\n     * foo/bar/..           -->   foo/\n     * foo/../../bar        -->   null\n     * foo/../bar           -->   bar\n     * //server/foo/../bar  -->   //server/bar\n     * //server/../bar      -->   null\n     * C:\\foo\\..\\bar        -->   C:\\bar\n     * C:\\..\\bar            -->   null\n     * ~/foo/../bar/        -->   ~/bar/\n     * ~/../bar             -->   null\n     * 
          \n * The output will be the same on both Unix and Windows including\n * the separator character.\n *\n * @param filename the filename to normalize, null returns null\n * @param unixSeparator {@code true} if a unix separator should\n * be used or {@code false} if a windows separator should be used.\n * @return the normalized filename, or null if invalid\n * @since 2.0\n */\n public static String normalize(String filename, boolean unixSeparator) {\n char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR;\n return doNormalize(filename, separator, true);\n }\n //-----------------------------------------------------------------------\n\n /**\n * Normalizes a path, removing double and single dot path steps,\n * and removing any final directory separator.\n *

          \n * This method normalizes a path to a standard format.\n * The input may contain separators in either Unix or Windows format.\n * The output will contain separators in the format of the system.\n *

          \n * A trailing slash will be removed.\n * A double slash will be merged to a single slash (but UNC names are handled).\n * A single dot path segment will be removed.\n * A double dot will cause that path segment and the one before to be removed.\n * If the double dot has no parent path segment to work with, {@code null}\n * is returned.\n *

          \n * The output will be the same on both Unix and Windows except\n * for the separator character.\n *

          \n     * /foo//               -->   /foo\n     * /foo/./              -->   /foo\n     * /foo/../bar          -->   /bar\n     * /foo/../bar/         -->   /bar\n     * /foo/../bar/../baz   -->   /baz\n     * //foo//./bar         -->   /foo/bar\n     * /../                 -->   null\n     * ../foo               -->   null\n     * foo/bar/..           -->   foo\n     * foo/../../bar        -->   null\n     * foo/../bar           -->   bar\n     * //server/foo/../bar  -->   //server/bar\n     * //server/../bar      -->   null\n     * C:\\foo\\..\\bar        -->   C:\\bar\n     * C:\\..\\bar            -->   null\n     * ~/foo/../bar/        -->   ~/bar\n     * ~/../bar             -->   null\n     * 
          \n * (Note the file separator returned will be correct for Windows/Unix)\n *\n * @param filename the filename to normalize, null returns null\n * @return the normalized filename, or null if invalid\n */\n public static String normalizeNoEndSeparator(String filename) {\n return doNormalize(filename, SYSTEM_SEPARATOR, false);\n }\n\n /**\n * Normalizes a path, removing double and single dot path steps,\n * and removing any final directory separator.\n *

          \n * This method normalizes a path to a standard format.\n * The input may contain separators in either Unix or Windows format.\n * The output will contain separators in the format specified.\n *

          \n * A trailing slash will be removed.\n * A double slash will be merged to a single slash (but UNC names are handled).\n * A single dot path segment will be removed.\n * A double dot will cause that path segment and the one before to be removed.\n * If the double dot has no parent path segment to work with, {@code null}\n * is returned.\n *

          \n * The output will be the same on both Unix and Windows including\n * the separator character.\n *

          \n     * /foo//               -->   /foo\n     * /foo/./              -->   /foo\n     * /foo/../bar          -->   /bar\n     * /foo/../bar/         -->   /bar\n     * /foo/../bar/../baz   -->   /baz\n     * //foo//./bar         -->   /foo/bar\n     * /../                 -->   null\n     * ../foo               -->   null\n     * foo/bar/..           -->   foo\n     * foo/../../bar        -->   null\n     * foo/../bar           -->   bar\n     * //server/foo/../bar  -->   //server/bar\n     * //server/../bar      -->   null\n     * C:\\foo\\..\\bar        -->   C:\\bar\n     * C:\\..\\bar            -->   null\n     * ~/foo/../bar/        -->   ~/bar\n     * ~/../bar             -->   null\n     * 
          \n *\n * @param filename the filename to normalize, null returns null\n * @param unixSeparator {@code true} if a unix separator should\n * be used or {@code false} if a windows separtor should be used.\n * @return the normalized filename, or null if invalid\n * @since 2.0\n */\n public static String normalizeNoEndSeparator(String filename, boolean unixSeparator) {\n char separator = unixSeparator ? UNIX_SEPARATOR : WINDOWS_SEPARATOR;\n return doNormalize(filename, separator, false);\n }\n\n /**\n * Internal method to perform the normalization.\n *\n * @param filename the filename\n * @param separator The separator character to use\n * @param keepSeparator true to keep the final separator\n * @return the normalized filename\n */\n private static String doNormalize(String filename, char separator, boolean keepSeparator) {\n if (filename == null) {\n return null;\n }\n int size = filename.length();\n if (size == 0) {\n return filename;\n }\n int prefix = getPrefixLength(filename);\n if (prefix < 0) {\n return null;\n }\n char[] array = new char[size + 2]; // +1 for possible extra slash, +2 for arraycopy\n filename.getChars(0, filename.length(), array, 0);\n // fix separators throughout\n char otherSeparator = separator == SYSTEM_SEPARATOR ? OTHER_SEPARATOR : SYSTEM_SEPARATOR;\n for (int i = 0; i < array.length; i++) {\n if (array[i] == otherSeparator) {\n array[i] = separator;\n }\n }\n // add extra separator on the end to simplify code below\n boolean lastIsDirectory = true;\n if (array[size - 1] != separator) {\n array[size++] = separator;\n lastIsDirectory = false;\n }\n // adjoining slashes\n for (int i = prefix + 1; i < size; i++) {\n if (array[i] == separator && array[i - 1] == separator) {\n System.arraycopy(array, i, array, i - 1, size - i);\n size--;\n i--;\n }\n }\n // dot slash\n for (int i = prefix + 1; i < size; i++) {\n if (array[i] == separator && array[i - 1] == '.' && (i == prefix + 1 || array[i - 2] == separator)) {\n if (i == size - 1) {\n lastIsDirectory = true;\n }\n System.arraycopy(array, i + 1, array, i - 1, size - i);\n size -= 2;\n i--;\n }\n }\n // double dot slash\n outer:\n for (int i = prefix + 2; i < size; i++) {\n if (array[i] == separator && array[i - 1] == '.' && array[i - 2] == '.' && (i == prefix + 2 || array[i - 3] == separator)) {\n if (i == prefix + 2) {\n return null;\n }\n if (i == size - 1) {\n lastIsDirectory = true;\n }\n int j;\n for (j = i - 4; j >= prefix; j--) {\n if (array[j] == separator) {\n // remove b/../ from a/b/../c\n System.arraycopy(array, i + 1, array, j + 1, size - i);\n size -= i - j;\n i = j + 1;\n continue outer;\n }\n }\n // remove a/../ from a/../c\n System.arraycopy(array, i + 1, array, prefix, size - i);\n size -= i + 1 - prefix;\n i = prefix + 1;\n }\n }\n if (size <= 0) { // should never be less than 0\n return \"\";\n }\n if (size <= prefix) { // should never be less than prefix\n return new String(array, 0, size);\n }\n if (lastIsDirectory && keepSeparator) {\n return new String(array, 0, size); // keep trailing separator\n }\n return new String(array, 0, size - 1); // lose trailing separator\n }\n //-----------------------------------------------------------------------\n\n /**\n * Concatenates a filename to a base path using normal command line style rules.\n *

          \n * The effect is equivalent to resultant directory after changing\n * directory to the first argument, followed by changing directory to\n * the second argument.\n *

          \n * The first argument is the base path, the second is the path to concatenate.\n * The returned path is always normalized via {@link #normalize(String)},\n * thus .. is handled.\n *

          \n * If pathToAdd is absolute (has an absolute prefix), then\n * it will be normalized and returned.\n * Otherwise, the paths will be joined, normalized and returned.\n *

          \n * The output will be the same on both Unix and Windows except\n * for the separator character.\n *

          \n     * /foo/ + bar          -->   /foo/bar\n     * /foo + bar           -->   /foo/bar\n     * /foo + /bar          -->   /bar\n     * /foo + C:/bar        -->   C:/bar\n     * /foo + C:bar         -->   C:bar (*)\n     * /foo/a/ + ../bar     -->   foo/bar\n     * /foo/ + ../../bar    -->   null\n     * /foo/ + /bar         -->   /bar\n     * /foo/.. + /bar       -->   /bar\n     * /foo + bar/c.txt     -->   /foo/bar/c.txt\n     * /foo/c.txt + bar     -->   /foo/c.txt/bar (!)\n     * 
          \n * (*) Note that the Windows relative drive prefix is unreliable when\n * used with this method.\n * (!) Note that the first parameter must be a path. If it ends with a name, then\n * the name will be built into the concatenated path. If this might be a problem,\n * use {@link #getFullPath(String)} on the base path argument.\n *\n * @param basePath the base path to attach to, always treated as a path\n * @param fullFilenameToAdd the filename (or path) to attach to the base\n * @return the concatenated path, or null if invalid\n */\n public static String concat(String basePath, String fullFilenameToAdd) {\n int prefix = getPrefixLength(fullFilenameToAdd);\n if (prefix < 0) {\n return null;\n }\n if (prefix > 0) {\n return normalize(fullFilenameToAdd);\n }\n if (basePath == null) {\n return null;\n }\n int len = basePath.length();\n if (len == 0) {\n return normalize(fullFilenameToAdd);\n }\n char ch = basePath.charAt(len - 1);\n if (isSeparator(ch)) {\n return normalize(basePath + fullFilenameToAdd);\n } else {\n return normalize(basePath + '/' + fullFilenameToAdd);\n }\n }\n //-----------------------------------------------------------------------\n\n /**\n * Converts all separators to the Unix separator of forward slash.\n *\n * @param path the path to be changed, null ignored\n * @return the updated path\n */\n public static String separatorsToUnix(String path) {\n if (path == null || path.indexOf(WINDOWS_SEPARATOR) == -1) {\n return path;\n }\n return path.replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR);\n }\n\n /**\n * Converts all separators to the Windows separator of backslash.\n *\n * @param path the path to be changed, null ignored\n * @return the updated path\n */\n public static String separatorsToWindows(String path) {\n if (path == null || path.indexOf(UNIX_SEPARATOR) == -1) {\n return path;\n }\n return path.replace(UNIX_SEPARATOR, WINDOWS_SEPARATOR);\n }\n\n /**\n * Converts all separators to the system separator.\n *\n * @param path the path to be changed, null ignored\n * @return the updated path\n */\n public static String separatorsToSystem(String path) {\n if (path == null) {\n return null;\n }\n if (isSystemWindows()) {\n return separatorsToWindows(path);\n } else {\n return separatorsToUnix(path);\n }\n }\n //-----------------------------------------------------------------------\n\n /**\n * Returns the length of the filename prefix, such as C:/ or ~/.\n *

          \n * This method will handle a file in either Unix or Windows format.\n *

          \n * The prefix length includes the first slash in the full filename\n * if applicable. Thus, it is possible that the length returned is greater\n * than the length of the input string.\n *

          \n     * Windows:\n     * a\\b\\c.txt           --> \"\"          --> relative\n     * \\a\\b\\c.txt          --> \"\\\"         --> current drive absolute\n     * C:a\\b\\c.txt         --> \"C:\"        --> drive relative\n     * C:\\a\\b\\c.txt        --> \"C:\\\"       --> absolute\n     * \\\\server\\a\\b\\c.txt  --> \"\\\\server\\\" --> UNC\n     *\n     * Unix:\n     * a/b/c.txt           --> \"\"          --> relative\n     * /a/b/c.txt          --> \"/\"         --> absolute\n     * ~/a/b/c.txt         --> \"~/\"        --> current user\n     * ~                   --> \"~/\"        --> current user (slash added)\n     * ~user/a/b/c.txt     --> \"~user/\"    --> named user\n     * ~user               --> \"~user/\"    --> named user (slash added)\n     * 
          \n *

          \n * The output will be the same irrespective of the machine that the code is running on.\n * ie. both Unix and Windows prefixes are matched regardless.\n *\n * @param filename the filename to find the prefix in, null returns -1\n * @return the length of the prefix, -1 if invalid or null\n */\n public static int getPrefixLength(String filename) {\n if (filename == null) {\n return -1;\n }\n int len = filename.length();\n if (len == 0) {\n return 0;\n }\n char ch0 = filename.charAt(0);\n if (ch0 == ':') {\n return -1;\n }\n if (len == 1) {\n if (ch0 == '~') {\n return 2; // return a length greater than the input\n }\n return isSeparator(ch0) ? 1 : 0;\n } else {\n if (ch0 == '~') {\n int posUnix = filename.indexOf(UNIX_SEPARATOR, 1);\n int posWin = filename.indexOf(WINDOWS_SEPARATOR, 1);\n if (posUnix == -1 && posWin == -1) {\n return len + 1; // return a length greater than the input\n }\n posUnix = posUnix == -1 ? posWin : posUnix;\n posWin = posWin == -1 ? posUnix : posWin;\n return Math.min(posUnix, posWin) + 1;\n }\n char ch1 = filename.charAt(1);\n if (ch1 == ':') {\n ch0 = Character.toUpperCase(ch0);\n if (ch0 >= 'A' && ch0 <= 'Z') {\n if (len == 2 || isSeparator(filename.charAt(2)) == false) {\n return 2;\n }\n return 3;\n }\n return -1;\n } else if (isSeparator(ch0) && isSeparator(ch1)) {\n int posUnix = filename.indexOf(UNIX_SEPARATOR, 2);\n int posWin = filename.indexOf(WINDOWS_SEPARATOR, 2);\n if (posUnix == -1 && posWin == -1 || posUnix == 2 || posWin == 2) {\n return -1;\n }\n posUnix = posUnix == -1 ? posWin : posUnix;\n posWin = posWin == -1 ? posUnix : posWin;\n return Math.min(posUnix, posWin) + 1;\n } else {\n return isSeparator(ch0) ? 1 : 0;\n }\n }\n }\n\n /**\n * Returns the index of the last directory separator character.\n *

          \n * This method will handle a file in either Unix or Windows format.\n * The position of the last forward or backslash is returned.\n *

          \n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to find the last path separator in, null returns -1\n * @return the index of the last separator character, or -1 if there\n * is no such character\n */\n public static int indexOfLastSeparator(String filename) {\n if (filename == null) {\n return -1;\n }\n int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR);\n int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR);\n return Math.max(lastUnixPos, lastWindowsPos);\n }\n\n /**\n * Returns the index of the last extension separator character, which is a dot.\n *

          \n * This method also checks that there is no directory separator after the last dot.\n * To do this it uses {@link #indexOfLastSeparator(String)} which will\n * handle a file in either Unix or Windows format.\n *

          \n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to find the last path separator in, null returns -1\n * @return the index of the last separator character, or -1 if there\n * is no such character\n */\n public static int indexOfExtension(String filename) {\n if (filename == null) {\n return -1;\n }\n int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);\n int lastSeparator = indexOfLastSeparator(filename);\n return lastSeparator > extensionPos ? -1 : extensionPos;\n }\n //-----------------------------------------------------------------------\n\n /**\n * Gets the prefix from a full filename, such as C:/\n * or ~/.\n *

          \n * This method will handle a file in either Unix or Windows format.\n * The prefix includes the first slash in the full filename where applicable.\n *

          \n     * Windows:\n     * a\\b\\c.txt           --> \"\"          --> relative\n     * \\a\\b\\c.txt          --> \"\\\"         --> current drive absolute\n     * C:a\\b\\c.txt         --> \"C:\"        --> drive relative\n     * C:\\a\\b\\c.txt        --> \"C:\\\"       --> absolute\n     * \\\\server\\a\\b\\c.txt  --> \"\\\\server\\\" --> UNC\n     *\n     * Unix:\n     * a/b/c.txt           --> \"\"          --> relative\n     * /a/b/c.txt          --> \"/\"         --> absolute\n     * ~/a/b/c.txt         --> \"~/\"        --> current user\n     * ~                   --> \"~/\"        --> current user (slash added)\n     * ~user/a/b/c.txt     --> \"~user/\"    --> named user\n     * ~user               --> \"~user/\"    --> named user (slash added)\n     * 
          \n *

          \n * The output will be the same irrespective of the machine that the code is running on.\n * ie. both Unix and Windows prefixes are matched regardless.\n *\n * @param filename the filename to query, null returns null\n * @return the prefix of the file, null if invalid\n */\n public static String getPrefix(String filename) {\n if (filename == null) {\n return null;\n }\n int len = getPrefixLength(filename);\n if (len < 0) {\n return null;\n }\n if (len > filename.length()) {\n return filename + UNIX_SEPARATOR; // we know this only happens for unix\n }\n return filename.substring(0, len);\n }\n\n /**\n * Gets the path from a full filename, which excludes the prefix.\n *

          \n * This method will handle a file in either Unix or Windows format.\n * The method is entirely text based, and returns the text before and\n * including the last forward or backslash.\n *

          \n     * C:\\a\\b\\c.txt --> a\\b\\\n     * ~/a/b/c.txt  --> a/b/\n     * a.txt        --> \"\"\n     * a/b/c        --> a/b/\n     * a/b/c/       --> a/b/c/\n     * 
          \n *

          \n * The output will be the same irrespective of the machine that the code is running on.\n *

          \n * This method drops the prefix from the result.\n * See {@link #getFullPath(String)} for the method that retains the prefix.\n *\n * @param filename the filename to query, null returns null\n * @return the path of the file, an empty string if none exists, null if invalid\n */\n public static String getPath(String filename) {\n return doGetPath(filename, 1);\n }\n\n /**\n * Gets the path from a full filename, which excludes the prefix, and\n * also excluding the final directory separator.\n *

          \n * This method will handle a file in either Unix or Windows format.\n * The method is entirely text based, and returns the text before the\n * last forward or backslash.\n *

          \n     * C:\\a\\b\\c.txt --> a\\b\n     * ~/a/b/c.txt  --> a/b\n     * a.txt        --> \"\"\n     * a/b/c        --> a/b\n     * a/b/c/       --> a/b/c\n     * 
          \n *

          \n * The output will be the same irrespective of the machine that the code is running on.\n *

          \n * This method drops the prefix from the result.\n * See {@link #getFullPathNoEndSeparator(String)} for the method that retains the prefix.\n *\n * @param filename the filename to query, null returns null\n * @return the path of the file, an empty string if none exists, null if invalid\n */\n public static String getPathNoEndSeparator(String filename) {\n return doGetPath(filename, 0);\n }\n\n /**\n * Does the work of getting the path.\n *\n * @param filename the filename\n * @param separatorAdd 0 to omit the end separator, 1 to return it\n * @return the path\n */\n private static String doGetPath(String filename, int separatorAdd) {\n if (filename == null) {\n return null;\n }\n int prefix = getPrefixLength(filename);\n if (prefix < 0) {\n return null;\n }\n int index = indexOfLastSeparator(filename);\n int endIndex = index + separatorAdd;\n if (prefix >= filename.length() || index < 0 || prefix >= endIndex) {\n return \"\";\n }\n return filename.substring(prefix, endIndex);\n }\n\n /**\n * Gets the full path from a full filename, which is the prefix + path.\n *

          \n * This method will handle a file in either Unix or Windows format.\n * The method is entirely text based, and returns the text before and\n * including the last forward or backslash.\n *

          \n     * C:\\a\\b\\c.txt --> C:\\a\\b\\\n     * ~/a/b/c.txt  --> ~/a/b/\n     * a.txt        --> \"\"\n     * a/b/c        --> a/b/\n     * a/b/c/       --> a/b/c/\n     * C:           --> C:\n     * C:\\          --> C:\\\n     * ~            --> ~/\n     * ~/           --> ~/\n     * ~user        --> ~user/\n     * ~user/       --> ~user/\n     * 
          \n *

          \n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to query, null returns null\n * @return the path of the file, an empty string if none exists, null if invalid\n */\n public static String getFullPath(String filename) {\n return doGetFullPath(filename, true);\n }\n\n /**\n * Gets the full path from a full filename, which is the prefix + path,\n * and also excluding the final directory separator.\n *

          \n * This method will handle a file in either Unix or Windows format.\n * The method is entirely text based, and returns the text before the\n * last forward or backslash.\n *

          \n     * C:\\a\\b\\c.txt --> C:\\a\\b\n     * ~/a/b/c.txt  --> ~/a/b\n     * a.txt        --> \"\"\n     * a/b/c        --> a/b\n     * a/b/c/       --> a/b/c\n     * C:           --> C:\n     * C:\\          --> C:\\\n     * ~            --> ~\n     * ~/           --> ~\n     * ~user        --> ~user\n     * ~user/       --> ~user\n     * 
          \n *

          \n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to query, null returns null\n * @return the path of the file, an empty string if none exists, null if invalid\n */\n public static String getFullPathNoEndSeparator(String filename) {\n return doGetFullPath(filename, false);\n }\n\n /**\n * Does the work of getting the path.\n *\n * @param filename the filename\n * @param includeSeparator true to include the end separator\n * @return the path\n */\n private static String doGetFullPath(String filename, boolean includeSeparator) {\n if (filename == null) {\n return null;\n }\n int prefix = getPrefixLength(filename);\n if (prefix < 0) {\n return null;\n }\n if (prefix >= filename.length()) {\n if (includeSeparator) {\n return getPrefix(filename); // add end slash if necessary\n } else {\n return filename;\n }\n }\n int index = indexOfLastSeparator(filename);\n if (index < 0) {\n return filename.substring(0, prefix);\n }\n int end = index + (includeSeparator ? 1 : 0);\n if (end == 0) {\n end++;\n }\n return filename.substring(0, end);\n }\n\n /**\n * Gets the name minus the path from a full filename.\n *

          \n * This method will handle a file in either Unix or Windows format.\n * The text after the last forward or backslash is returned.\n *

          \n     * a/b/c.txt --> c.txt\n     * a.txt     --> a.txt\n     * a/b/c     --> c\n     * a/b/c/    --> \"\"\n     * 
          \n *

          \n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to query, null returns null\n * @return the name of the file without the path, or an empty string if none exists\n */\n public static String getName(String filename) {\n if (filename == null) {\n return null;\n }\n int index = indexOfLastSeparator(filename);\n return filename.substring(index + 1);\n }\n\n /**\n * Gets the base name, minus the full path and extension, from a full filename.\n *

          \n * This method will handle a file in either Unix or Windows format.\n * The text after the last forward or backslash and before the last dot is returned.\n *

          \n     * a/b/c.txt --> c\n     * a.txt     --> a\n     * a/b/c     --> c\n     * a/b/c/    --> \"\"\n     * 
          \n *

          \n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to query, null returns null\n * @return the name of the file without the path, or an empty string if none exists\n */\n public static String getBaseName(String filename) {\n return removeExtension(getName(filename));\n }\n\n /**\n * Gets the extension of a filename.\n *

          \n * This method returns the textual part of the filename after the last dot.\n * There must be no directory separator after the dot.\n *

          \n     * foo.txt      --> \"txt\"\n     * a/b/c.jpg    --> \"jpg\"\n     * a/b.txt/c    --> \"\"\n     * a/b/c        --> \"\"\n     * 
          \n *

          \n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to retrieve the extension of.\n * @return the extension of the file or an empty string if none exists or {@code null}\n * if the filename is {@code null}.\n */\n public static String getExtension(String filename) {\n if (filename == null) {\n return null;\n }\n int index = indexOfExtension(filename);\n if (index == -1) {\n return \"\";\n } else {\n return filename.substring(index + 1);\n }\n }\n //-----------------------------------------------------------------------\n\n /**\n * Removes the extension from a filename.\n *

          \n * This method returns the textual part of the filename before the last dot.\n * There must be no directory separator after the dot.\n *

          \n     * foo.txt    --> foo\n     * a\\b\\c.jpg  --> a\\b\\c\n     * a\\b\\c      --> a\\b\\c\n     * a.b\\c      --> a.b\\c\n     * 
          \n *

          \n * The output will be the same irrespective of the machine that the code is running on.\n *\n * @param filename the filename to query, null returns null\n * @return the filename minus the extension\n */\n public static String removeExtension(String filename) {\n if (filename == null) {\n return null;\n }\n int index = indexOfExtension(filename);\n if (index == -1) {\n return filename;\n } else {\n return filename.substring(0, index);\n }\n }\n //-----------------------------------------------------------------------\n\n /**\n * Checks whether the extension of the filename is that specified.\n *

          \n * This method obtains the extension as the textual part of the filename\n * after the last dot. There must be no directory separator after the dot.\n * The extension check is case-sensitive on all platforms.\n *\n * @param filename the filename to query, null returns false\n * @param extension the extension to check for, null or empty checks for no extension\n * @return true if the filename has the specified extension\n */\n public static boolean isExtension(String filename, String extension) {\n if (filename == null) {\n return false;\n }\n if (extension == null || extension.length() == 0) {\n return indexOfExtension(filename) == -1;\n }\n String fileExt = getExtension(filename);\n return fileExt.equals(extension);\n }\n\n /**\n * Checks whether the extension of the filename is one of those specified.\n *

          \n * This method obtains the extension as the textual part of the filename\n * after the last dot. There must be no directory separator after the dot.\n * The extension check is case-sensitive on all platforms.\n *\n * @param filename the filename to query, null returns false\n * @param extensions the extensions to check for, null checks for no extension\n * @return true if the filename is one of the extensions\n */\n public static boolean isExtension(String filename, String[] extensions) {\n if (filename == null) {\n return false;\n }\n if (extensions == null || extensions.length == 0) {\n return indexOfExtension(filename) == -1;\n }\n String fileExt = getExtension(filename);\n for (String extension : extensions) {\n if (fileExt.equals(extension)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Checks whether the extension of the filename is one of those specified.\n *

          \n * This method obtains the extension as the textual part of the filename\n * after the last dot. There must be no directory separator after the dot.\n * The extension check is case-sensitive on all platforms.\n *\n * @param filename the filename to query, null returns false\n * @param extensions the extensions to check for, null checks for no extension\n * @return true if the filename is one of the extensions\n */\n public static boolean isExtension(String filename, Collection extensions) {\n if (filename == null) {\n return false;\n }\n if (extensions == null || extensions.isEmpty()) {\n return indexOfExtension(filename) == -1;\n }\n String fileExt = getExtension(filename);\n for (String extension : extensions) {\n if (fileExt.equals(extension)) {\n return true;\n }\n }\n return false;\n }\n}", "file_name": "FilenameUtils.java", "human_label": "Return the last index of the extension separator in the given filename,it will return -1 if the filename doesn't have the separator or there is a directory separator after it.", "level": "class_runnable", "lineno": "637", "name": "indexOfExtension", "oracle_context": "{ \"apis\" : \"[lastIndexOf, indexOfLastSeparator]\", \"classes\" : \"[]\", \"vars\" : \"[EXTENSION_SEPARATOR]\" }", "package": "net.hasor.utils.io", "project": "hasor-master" }, { "_id": "636767dd1a6d9265ec0186de", "all_context": "{ \"class_level\" : \"import lombok.EqualsAndHashCode;\\nimport lombok.Getter;\\nimport lombok.Setter;\\nimport org.apache.skywalking.oap.server.core.analysis.TimeBucket;\\nimport org.apache.skywalking.oap.server.core.remote.data.StreamData;\\nimport org.apache.skywalking.oap.server.core.storage.ShardingAlgorithm;\\nimport org.apache.skywalking.oap.server.core.storage.StorageData;\\nimport org.apache.skywalking.oap.server.core.storage.annotation.Column;\\nimport org.apache.skywalking.oap.server.core.storage.annotation.SQLDatabase;\\nimport static org.apache.skywalking.oap.server.core.analysis.metrics.Metrics.ENTITY_ID;\\nimport static org.apache.skywalking.oap.server.core.analysis.metrics.Metrics.ID;\\nString TIME_BUCKET;\\nString ENTITY_ID;\\nString ID;\\nlong timeBucket;\\nlong lastUpdateTimestamp;\\nString id;\\ncalculate();\\ntoHour();\\ntoDay();\\nsetLastUpdateTimestamp(long timestamp);\\nisExpired(long timestamp,long expiredThreshold);\\ntoTimeBucketInHour();\\ntoTimeBucketInDay();\\ngetDurationInMinute();\\nisMinuteBucket();\\nisHourBucket();\\nisDayBucket();\\nid();\\nid0();\\ncombine(Metrics metrics);\\n\", \"repo_level\" : \"public interface TimeBucket {static long getRecordTimeBucket(long time);\\nstatic long getMinuteTimeBucket(long time);\\nstatic long getTimestamp(long timeBucket);\\nstatic boolean isSecondBucket(long timeBucket);\\nstatic boolean isMinuteBucket(long timeBucket);\\nstatic boolean isHourBucket(long timeBucket);\\nstatic boolean isDayBucket(long timeBucket);\\nstatic long getTimestamp(long timeBucket,DownSampling downsampling);\\nstatic long getTimeBucket(long timestamp,DownSampling downsampling);\\n }\\npublic interface StreamData {abstract int remoteHashCode();\\n }\\npublic interface StorageData { String id();\\n }\\n\" }", "class_name": "Metrics", "code": "public boolean isExpired(long timestamp,long expiredThreshold){\n return timestamp - lastUpdateTimestamp > expiredThreshold;\n}\n", "docstring": "/** \n * @param timestamp of current time\n * @param expiredThreshold represents the duration between last update time and the time point removing from cache.\n * @return true means this metrics should be removed from cache.\n */\n", "end_lineno": "106", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.core.analysis.metrics;\n\nimport lombok.EqualsAndHashCode;\nimport lombok.Getter;\nimport lombok.Setter;\nimport org.apache.skywalking.oap.server.core.analysis.TimeBucket;\nimport org.apache.skywalking.oap.server.core.remote.data.StreamData;\nimport org.apache.skywalking.oap.server.core.storage.ShardingAlgorithm;\nimport org.apache.skywalking.oap.server.core.storage.StorageData;\nimport org.apache.skywalking.oap.server.core.storage.annotation.Column;\nimport org.apache.skywalking.oap.server.core.storage.annotation.SQLDatabase;\n\nimport static org.apache.skywalking.oap.server.core.analysis.metrics.Metrics.ENTITY_ID;\nimport static org.apache.skywalking.oap.server.core.analysis.metrics.Metrics.ID;\n\n/**\n * Metrics represents the statistic data, which analysis by OAL script or hard code. It has the lifecycle controlled by\n * TTL(time to live).\n */\n@EqualsAndHashCode(of = {\n \"timeBucket\"\n})\n@SQLDatabase.Sharding(shardingAlgorithm = ShardingAlgorithm.TIME_RELATIVE_ID_SHARDING_ALGORITHM, tableShardingColumn = ID, dataSourceShardingColumn = ENTITY_ID)\npublic abstract class Metrics extends StreamData implements StorageData {\n\n public static final String TIME_BUCKET = \"time_bucket\";\n public static final String ENTITY_ID = \"entity_id\";\n public static final String ID = \"id\";\n\n /**\n * Time attribute\n */\n @Getter\n @Setter\n @Column(columnName = TIME_BUCKET)\n private long timeBucket;\n\n /**\n * Time in the cache, only work when MetricsPersistentWorker#enableDatabaseSession == true.\n */\n @Getter\n private long lastUpdateTimestamp = 0L;\n\n /**\n * Merge the given metrics instance, these two must be the same metrics type.\n *\n * @param metrics to be merged\n * @return {@code true} if the combined metrics should be continuously processed. {@code false} means it should be\n * abandoned, and the implementation needs to keep the data unaltered in this case.\n */\n public abstract boolean combine(Metrics metrics);\n\n /**\n * Calculate the metrics final value when required.\n */\n public abstract void calculate();\n\n /**\n * Downsampling the metrics to hour precision.\n *\n * @return the metrics in hour precision in the clone mode.\n */\n public abstract Metrics toHour();\n\n /**\n * Downsampling the metrics to day precision.\n *\n * @return the metrics in day precision in the clone mode.\n */\n public abstract Metrics toDay();\n\n /**\n * Set the last update timestamp\n *\n * @param timestamp last update timestamp\n */\n public void setLastUpdateTimestamp(long timestamp) {\n lastUpdateTimestamp = timestamp;\n }\n\n /**\n * @param timestamp of current time\n * @param expiredThreshold represents the duration between last update time and the time point removing from cache.\n * @return true means this metrics should be removed from cache.\n */\n public boolean isExpired(long timestamp, long expiredThreshold) {\n return timestamp - lastUpdateTimestamp > expiredThreshold;\n }\n\n public long toTimeBucketInHour() {\n if (isMinuteBucket()) {\n return timeBucket / 100;\n } else {\n throw new IllegalStateException(\"Current time bucket is not in minute dimensionality\");\n }\n }\n\n public long toTimeBucketInDay() {\n if (isMinuteBucket()) {\n return timeBucket / 10000;\n } else if (isHourBucket()) {\n return timeBucket / 100;\n } else {\n throw new IllegalStateException(\"Current time bucket is not in minute dimensionality\");\n }\n }\n\n /**\n * Always get the duration for this time bucket in minute.\n */\n protected long getDurationInMinute() {\n if (isMinuteBucket()) {\n return 1;\n } else if (isHourBucket()) {\n return 60;\n } else if (isDayBucket()) {\n return 24 * 60;\n }\n throw new IllegalStateException(\"Time bucket (\" + timeBucket + \") can't be recognized.\");\n }\n\n private boolean isMinuteBucket() {\n return TimeBucket.isMinuteBucket(timeBucket);\n }\n\n private boolean isHourBucket() {\n return TimeBucket.isHourBucket(timeBucket);\n }\n\n private boolean isDayBucket() {\n return TimeBucket.isDayBucket(timeBucket);\n }\n\n private volatile String id;\n\n @Override\n public String id() {\n if (id == null) {\n id = id0();\n }\n return id;\n }\n\n protected abstract String id0();\n}\n", "file_name": "Metrics.java", "human_label": "Return true if the timestamp minus the lastUpdateTimestamp is greater than expiredThreshold,otherwise return false.", "level": "class_runnable", "lineno": "99", "name": "isExpired", "oracle_context": "{ \"apis\" : \"[]\", \"classes\" : \"[]\", \"vars\" : \"[lastUpdateTimestamp]\" }", "package": "org.apache.skywalking.oap.server.core.analysis.metrics", "project": "skywalking-master" }, { "_id": "6367675d1a6d9265ec018082", "all_context": "{ \"class_level\" : \"import org.jgrapht.*;\\nimport org.jgrapht.alg.interfaces.*;\\nimport org.jgrapht.alg.util.*;\\nimport org.jgrapht.graph.*;\\nimport org.jgrapht.util.*;\\nimport java.lang.reflect.*;\\nimport java.util.*;\\nimport java.util.function.*;\\nboolean DEBUG;\\nboolean PRINT_CASES;\\nGraph graph;\\nint n;\\nEmbedding embedding;\\nGraph kuratowskiSubdivision;\\nList nodes;\\nList dfsTreeRoots;\\nList componentRoots;\\nList stack;\\nNode failedV;\\nboolean tested;\\nboolean planar;\\nNode current;\\nEdge prevEdge;\\nboolean backtrack;\\nV current;\\nV parent;\\nE parentEdge;\\nNode parent;\\nNode parentNext;\\nNode child;\\nNode childPrev;\\nint vIn;\\nint vOut;\\nNode prev;\\nE graphEdge;\\nNode source;\\nNode target;\\nint sign;\\nboolean embedded;\\nboolean shortCircuit;\\nV graphVertex;\\nboolean rootVertex;\\nint dfsIndex;\\nint height;\\nint lowpoint;\\nint leastAncestor;\\nint visited;\\nint backEdgeFlag;\\nint boundaryHeight;\\nboolean marked;\\nEdge parentEdge;\\nEdge edgeToEmbed;\\nNode initialComponentRoot;\\nNode[] outerFaceNeighbors;\\nDoublyLinkedList separatedDfsChildList;\\nDoublyLinkedList pertinentRoots;\\nList treeEdges;\\nList downEdges;\\nList backEdges;\\nDoublyLinkedList.ListNode listNode;\\nDoublyLinkedList embedded;\\nBoyerMyrvoldPlanarityInspector(Graph graph);\\norientDfs(Map vertexMap,V startGraphVertex,int currentDfsIndex);\\norient();\\nsortVertices();\\nlazyTestPlanarity();\\nmergeBiconnectedComponent();\\nembedBackEdge(Node root,int entryDir,Edge edge,Node childPrev);\\nembedShortCircuit(Node componentRoot,int entryDir,OuterFaceCirculator circulator);\\nwalkDown(Node componentRoot);\\nwalkUp(Node start,Node end,Edge edge);\\nlazyComputeEmbedding();\\nprintBiconnectedComponent(Node node);\\nprintState();\\nselectOnOuterFace(Predicate predicate,Node start,Node stop,int dir);\\ngetActiveSuccessorOnOuterFace(Node start,Node v,int dir);\\ngetExternallyActiveSuccessorOnOuterFace(Node start,Node stop,Node v,int dir);\\ngetComponentRoot(Node node);\\naddPathEdges(Set edges,Edge startEdge,Node stop);\\naddPathEdges(Set edges,Node start,Node stop);\\nsearchEdge(Node current,int heightMax);\\nsearchEdge(Node current,int heightMax,Edge forbiddenEdge);\\nsearchEdge(Node current,Predicate isNeeded);\\nsearchSubtreeDfs(Node start,Predicate isNeeded);\\nhighest(Node a,Node b);\\nlowest(Node a,Node b);\\nsetBoundaryDepth(Node componentRoot,Node w,int dir,int delta);\\nclearVisited();\\nfindPathDfs(Node start,Edge startPrev,Predicate canGo,Predicate isFinish,List edges);\\nfindHighestObstructingPath(Node componentRoot,Node w);\\nfinish(Set subdivision);\\naddBoundaryEdges(Set edges,Node componentRoot);\\nkuratowskiCleanUp();\\ncleanUpDfs(Node dfsTreeRoot);\\nfixBoundaryOrder(Node componentRoot);\\nremoveUp(Node start,Node end,int dir,Set edges);\\ngetNextOnPath(Node w,Edge backEdge);\\nfindPathToV(List path,Node v);\\nfirstStrictlyHigher(Node a,Node b,Node c);\\ncheckComponentForFailedEdge(Node componentRoot,Node v);\\nfindFailedEdge(Node v);\\nlazyExtractKuratowskiSubdivision();\\nisPlanar();\\ngetEmbedding();\\ngetKuratowskiSubdivision();\\nSearchInfo(Node current,Edge prevEdge,boolean backtrack);\\nOrientDfsStackInfo(V current,V parent,E parentEdge,boolean backtrack);\\nMergeInfo(Node parent,Node parentNext,Node child,Node childPrev,int vIn,int vOut);\\nisInverted();\\ntoString();\\nOuterFaceCirculator(Node current,Node prev);\\nhasNext();\\nnext();\\nedgeToNext();\\ngetCurrent();\\ngetPrev();\\ntoExistingNode(Node node);\\nEdge(Node source,Node target);\\nEdge(E graphEdge,Node source);\\nEdge(E graphEdge,Node source,Node target);\\nisIncidentTo(Node node);\\ngetOpposite(Node node);\\nNode(V graphVertex,int dfsIndex,int height,Node initialComponentRoot,Edge parentEdge);\\nNode(int dfsIndex,Edge parentEdge);\\nNode(V graphVertex,int dfsIndex,Edge parentEdge,boolean rootVertex);\\nisVisitedWrtTo(Node node);\\nisPertinentWrtTo(Node node);\\nhasBackEdgeWrtTo(Node node);\\nisExternallyActiveWrtTo(Node node);\\nisRootVertex();\\nisInternallyActiveWrtTo(Node node);\\nisInactiveWrtTo(Node node);\\nisActiveWrtTo(Node node);\\niterator(int direction);\\nremoveShortCircuitEdges();\\ngetParent();\\ncheckIsAdjacent(Node node);\\nswapNeighbors();\\nsubstitute(Node node,Node newNeighbor);\\nsubstituteAnother(Node node,Node newNeighbor);\\nhasRootNeighbor();\\nnextOnOuterFace(Node prev);\\nembedBackEdge(Edge edge,Node prev);\\nmergeChildEdges(DoublyLinkedList edges,int vIn,int vOut,Node parentNext,Edge parentEdge);\\ntoString(boolean full);\\ncreateNewNode(Map vertexMap,V graphVertex,E edge,Node parent,int dfsIndex);\\n\", \"repo_level\" : \"\" }", "class_name": "BoyerMyrvoldPlanarityInspector$OuterFaceCirculator", "code": "Edge edgeToNext(){\n Edge edge=prev.embedded.getFirst();\n Node target=toExistingNode(current);\n Node source=toExistingNode(prev);\n if (edge.getOpposite(source) == target) {\n return edge;\n }\n else {\n return prev.embedded.getLast();\n }\n}\n", "docstring": "/** \n * Returns an edge connecting previously returned node with node, which will be returned next. If either of the mentioned nodes is virtual, the edge will be incident to its real counterpart.\n * @return an edge from the current node to the next node\n */\n", "end_lineno": "1744", "file_content": "/*\n * (C) Copyright 2018-2021, by Timofey Chudakov and Contributors.\n *\n * JGraphT : a free Java graph-theory library\n *\n * See the CONTRIBUTORS.md file distributed with this work for additional\n * information regarding copyright ownership.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License 2.0 which is available at\n * http://www.eclipse.org/legal/epl-2.0, or the\n * GNU Lesser General Public License v2.1 or later\n * which is available at\n * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html.\n *\n * SPDX-License-Identifier: EPL-2.0 OR LGPL-2.1-or-later\n */\npackage org.jgrapht.alg.planar;\n\nimport org.jgrapht.*;\nimport org.jgrapht.alg.interfaces.*;\nimport org.jgrapht.alg.util.*;\nimport org.jgrapht.graph.*;\nimport org.jgrapht.util.*;\n\nimport java.lang.reflect.*;\nimport java.util.*;\nimport java.util.function.*;\n\n/**\n * An implementation of the Boyer-Myrvold planarity testing algorithm. This class determines whether\n * an input graph is planar or not. If the graph is planar, the algorithm provides a\n * combinatorial\n * embedding of the graph, which is represented as a clockwise ordering of the edges of the\n * graph. Otherwise, the algorithm provides a\n * Kuratowski\n * subgraph as a certificate. Both embedding of the graph and Kuratowski subdivision are\n * computed lazily, meaning that the call to the {@link BoyerMyrvoldPlanarityInspector#isPlanar()}\n * does spend time only on the planarity testing. All of the operations of this algorithm (testing,\n * embedding and Kuratowski subgraph extraction) run in linear time.\n *

          \n * A planar graph is a graph, which can be\n * drawn in two-dimensional space without any of its edges crossing. According to the\n * Kuratowski theorem, a graph is\n * planar if and only if it doesn't contain a subdivision of the $K_{3,3}$ or $K_{5}$ graphs.\n *

          \n * The Boyer-Myrvold planarity testing algorithm was originally described in: Boyer, John amp;\n * Myrvold, Wendy. (2004). On the Cutting Edge: Simplified O(n) Planarity by Edge Addition. J. Graph\n * Algorithms Appl.. 8. 241-273. 10.7155/jgaa.00091. . We refer to this paper for the complete\n * description of the Boyer-Myrvold algorithm\n *\n * @param the graph vertex type\n * @param the graph edge type\n * @author Timofey Chudakov\n */\npublic class BoyerMyrvoldPlanarityInspector\n implements\n PlanarityTestingAlgorithm\n{\n /**\n * Whether to print debug messages\n */\n private static final boolean DEBUG = false;\n /**\n * Whether to print Kuratowski case distinction messages\n */\n private static final boolean PRINT_CASES = false;\n /**\n * The graph we're testing planarity of\n */\n private Graph graph;\n /**\n * The number of vertices in the {@code graph}\n */\n private int n;\n /**\n * The resulting combinatorial embedding. This value is computed only after the first call to\n * the {@link BoyerMyrvoldPlanarityInspector#getEmbedding()}\n */\n private Embedding embedding;\n /**\n * The subgraph of the {@code graph}, which is a Kuratowski subdivision. This subgraph certifies\n * the nonplanarity of the graph.\n */\n private Graph kuratowskiSubdivision;\n /**\n * List of the vertices of the {@code graph} in their internal representation. After the\n * orientation of the {@code graph} and edge sorting, nodes in this list are sorted according to\n * their dfs indexes\n */\n private List nodes;\n /**\n * List of the dfs tree roots of the {@code graph}. This list has length more than 1 if the\n * input {@code graph} isn't connected\n */\n private List dfsTreeRoots;\n /**\n * List of the virtual biconnected component roots. Initially, a virtual biconnected component\n * root is created for every node in the {@code graph}, except for the dfs roots. These\n * component roots don't belong to the {@code graph}. At each step of the algorithm, every\n * biconnected component has its own unique component root.\n */\n private List componentRoots;\n /**\n * The stack containing merge information for every consecutive pair of biconnected components\n * on the path to the back edge source. After all the biconnected components are merged, this\n * stack is cleared\n */\n private List stack;\n /**\n * The node $v$, which has an unembedded back edge incident to it.\n */\n private Node failedV;\n /**\n * Whether the planarity of the {@code graph} has been tested already\n */\n private boolean tested;\n /**\n * Whether the graph is planar or not. Is valid, if {@code tested} is {@code true}\n */\n private boolean planar;\n\n /**\n * Creates new instance of the planarity testing algorithm for the {@code graph}. The input\n * graph can't be null.\n *\n * @param graph the graph to test the planarity of\n */\n public BoyerMyrvoldPlanarityInspector(Graph graph)\n {\n this.graph = Objects.requireNonNull(graph, \"Graph can't be null\");\n this.n = graph.vertexSet().size();\n this.nodes = new ArrayList<>(n);\n this.dfsTreeRoots = new ArrayList<>();\n this.componentRoots = new ArrayList<>(n);\n this.stack = new ArrayList<>();\n }\n\n /**\n * Creates a new node by converting the {@code graphVertex} to the internal node representation.\n *\n * @param vertexMap the map from vertices of the {@code graph} to their internal representation\n * @param graphVertex the vertex of the {@code graph} we're processing\n * @param edge the parent edge of the {@code graphVertex}, is {@code null} for dfs tree roots\n * @param parent the parent node of the {@code graphVertex}\n * @param dfsIndex the dfs index of the {@code graphVertex}\n * @return the newly created node\n */\n private Node createNewNode(\n Map vertexMap, V graphVertex, E edge, Node parent, int dfsIndex)\n {\n Node child;\n if (parent == null) {\n child = new Node(graphVertex, dfsIndex, 0, null, null);\n child.outerFaceNeighbors[0] = child.outerFaceNeighbors[1] = child;\n dfsTreeRoots.add(child);\n } else {\n Edge treeEdge = new Edge(edge, parent);\n Node componentRoot = new Node(parent.dfsIndex, treeEdge);\n child = new Node(graphVertex, dfsIndex, parent.height + 1, componentRoot, treeEdge);\n treeEdge.target = child;\n\n componentRoots.add(componentRoot);\n\n parent.treeEdges.add(treeEdge);\n\n child.outerFaceNeighbors[0] = child.outerFaceNeighbors[1] = componentRoot;\n componentRoot.outerFaceNeighbors[0] = componentRoot.outerFaceNeighbors[1] = child;\n }\n nodes.add(child);\n vertexMap.put(graphVertex, child);\n return child;\n }\n\n /**\n * Orients the input graph according to its dfs traversal by creating a dfs tree. Computes the\n * least ancestors and lowpoints of the nodes\n *\n * @param vertexMap the map from {@code graph} vertices to their internal representatives\n * @param startGraphVertex the node to start the traversal from (this is a dfs tree root).\n * @param currentDfsIndex the dfs index of the {@code startGraphVertex}\n * @return the {@code currentDfsIndex} + number of nodes in the traversed subtree\n */\n private int orientDfs(Map vertexMap, V startGraphVertex, int currentDfsIndex)\n {\n List stack = new ArrayList<>();\n stack.add(new OrientDfsStackInfo(startGraphVertex, null, null, false));\n while (!stack.isEmpty()) {\n OrientDfsStackInfo info = stack.remove(stack.size() - 1);\n\n if (info.backtrack) {\n Node current = vertexMap.get(info.current);\n current.leastAncestor = current.lowpoint = current.dfsIndex;\n for (Edge backEdge : current.backEdges) {\n current.leastAncestor =\n Math.min(current.leastAncestor, backEdge.target.dfsIndex);\n }\n for (Edge treeEdge : current.treeEdges) {\n current.lowpoint = Math.min(current.lowpoint, treeEdge.target.lowpoint);\n }\n current.lowpoint = Math.min(current.lowpoint, current.leastAncestor);\n } else {\n if (vertexMap.containsKey(info.current)) {\n // other dfs branch has reached this vertex earlier\n continue;\n }\n stack.add(new OrientDfsStackInfo(info.current, info.parent, info.parentEdge, true));\n Node current = createNewNode(\n vertexMap, info.current, info.parentEdge, vertexMap.get(info.parent),\n currentDfsIndex);\n ++currentDfsIndex;\n for (E e : graph.edgesOf(info.current)) {\n V opposite = Graphs.getOppositeVertex(graph, e, info.current);\n if (vertexMap.containsKey(opposite)) {\n // back edge or parent edge\n Node oppositeNode = vertexMap.get(opposite);\n if (opposite.equals(info.parent)) {\n continue;\n }\n Edge backEdge = new Edge(e, current, oppositeNode);\n oppositeNode.downEdges.add(backEdge);\n current.backEdges.add(backEdge);\n } else {\n // possible tree edge\n stack.add(new OrientDfsStackInfo(opposite, current.graphVertex, e, false));\n }\n }\n }\n }\n return currentDfsIndex;\n }\n\n /**\n * Iteratively start an orienting dfs from every {@code graph} vertex that hasn't been visited\n * yet. After orienting the graph, sorts the nodes by their lowpoints and adds them to the\n * {@code separatedDfsChildList}\n */\n private void orient()\n {\n Map visited = new HashMap<>();\n int currentDfsIndex = 0;\n for (V vertex : graph.vertexSet()) {\n if (!visited.containsKey(vertex)) {\n currentDfsIndex = orientDfs(visited, vertex, currentDfsIndex);\n }\n }\n sortVertices();\n }\n\n /**\n * Performs sorting of the vertices by their lowpoints and adding them to the\n * {@code separatedDfsChildList}\n */\n private void sortVertices()\n {\n List> sorted = new ArrayList<>(Collections.nCopies(n, null));\n for (Node node : nodes) {\n int lowpoint = node.lowpoint;\n if (sorted.get(lowpoint) == null) {\n sorted.set(lowpoint, new ArrayList<>());\n }\n sorted.get(lowpoint).add(node);\n }\n int i = 0;\n for (List list : sorted) {\n if (i >= n) {\n break;\n }\n if (list != null) {\n for (Node node : list) {\n nodes.set(i++, node);\n if (node.parentEdge != null) {\n node.listNode =\n node.parentEdge.source.separatedDfsChildList.addElementLast(node);\n }\n }\n }\n }\n }\n\n /**\n * Lazily tests the planarity of the graph. The implementation below is close to the code\n * presented in the original paper\n *\n * @return true if the graph is planar, false otherwise\n */\n private boolean lazyTestPlanarity()\n {\n if (!tested) {\n tested = true;\n\n orient();\n if (DEBUG) {\n printState();\n System.out.println(\"Start testing planarity\");\n }\n for (int currentNode = n - 1; currentNode >= 0; currentNode--) {\n Node current = nodes.get(currentNode);\n if (DEBUG) {\n System.out.printf(\"Current vertex is %s\\n\", current.toString(false));\n }\n for (Edge downEdge : current.downEdges) {\n walkUp(downEdge.source, current, downEdge);\n }\n for (Edge treeEdge : current.treeEdges) {\n walkDown(treeEdge.target.initialComponentRoot);\n }\n\n for (Edge downEdge : current.downEdges) {\n if (!downEdge.embedded) {\n failedV = current;\n return planar = false;\n }\n }\n }\n planar = true;\n }\n return planar;\n }\n\n /**\n * Merges the last two biconnected components using the info stored on top of the stack. The key\n * goal of this method is to merge the outer faces of the two components and to merge the\n * embedded edges of the child component root with the embedded edges of the component parent\n * node.\n */\n private void mergeBiconnectedComponent()\n {\n MergeInfo info = stack.get(stack.size() - 1);\n stack.remove(stack.size() - 1);\n if (DEBUG) {\n System.out.printf(\"\\nMerging biconnected component, info: %s\\n\", info.toString());\n }\n Node virtualRoot = info.child;\n if (info.isInverted()) {\n virtualRoot.swapNeighbors();\n }\n Node root = info.parent;\n Node virtualRootChild = virtualRoot.parentEdge.target;\n\n root.pertinentRoots.removeNode(virtualRoot.listNode);\n root.separatedDfsChildList.removeNode(virtualRootChild.listNode);\n\n root\n .mergeChildEdges(\n virtualRoot.embedded, info.vIn, info.vOut, info.parentNext, virtualRoot.parentEdge);\n\n root.substituteAnother(info.parentNext, info.childPrev);\n info.childPrev.substitute(virtualRoot, root);\n virtualRoot.outerFaceNeighbors[0] = virtualRoot.outerFaceNeighbors[1] = null;\n }\n\n /**\n * Embeds the back edge {@code edge} into the list of embedded edges of the source and the\n * virtual target of the edge such that the {@code childPrev} belongs to the new inner face.\n * This method also takes care of modifying the boundary of the outer face accordingly\n *\n * @param root the component root\n * @param entryDir the component entry direction\n * @param edge the edge to embed\n * @param childPrev the neighbor of the source of the edge that should belong to the inner face\n * @return a circulator starting from the edge's source\n */\n private OuterFaceCirculator embedBackEdge(Node root, int entryDir, Edge edge, Node childPrev)\n {\n if (DEBUG) {\n System.out.printf(\"Embedding back edge %s\\n\", edge.toString());\n }\n assert !edge.embedded;\n if (entryDir == 0) {\n root.embedded.addLast(edge);\n } else {\n root.embedded.addFirst(edge);\n }\n Node child = edge.source;\n child.embedBackEdge(edge, childPrev);\n child.edgeToEmbed = null;\n child.backEdgeFlag = n;\n edge.embedded = true;\n\n child.substitute(childPrev, root);\n root.outerFaceNeighbors[entryDir] = child;\n Node next = child.nextOnOuterFace(root);\n return new OuterFaceCirculator(next, child);\n }\n\n /**\n * Embeds a short-circuit edge from the {@code componentRoot} to the current node of the\n * {@code circulator}. Changes the outer face accordingly\n *\n * @param componentRoot the component root\n * @param entryDir the direction used to enter the component\n * @param circulator a circulator to the source of the new edge\n */\n private void embedShortCircuit(Node componentRoot, int entryDir, OuterFaceCirculator circulator)\n {\n Node current = circulator.getCurrent(), prev = circulator.getPrev();\n Edge shortCircuit = new Edge(current, componentRoot.getParent());\n if (entryDir == 0) {\n componentRoot.embedded.addLast(shortCircuit);\n componentRoot.outerFaceNeighbors[0] = current;\n } else {\n componentRoot.embedded.addFirst(shortCircuit);\n componentRoot.outerFaceNeighbors[1] = current;\n }\n current.embedBackEdge(shortCircuit, prev);\n current.substitute(prev, componentRoot);\n if (DEBUG) {\n System.out.printf(\"Embedding short circuit edge: %s\\n\", shortCircuit.toString());\n printState();\n }\n }\n\n /**\n * The walkdown procedure from the original paper. Either embeds all of the back edges in the\n * subtree rooted at the child of the {@code componentRoot} or identifies the back edges which\n * can be used to extract a Kuratowski subdivision. Iteratively traverses the tree of the\n * biconnected component and descends only to the pertinent components. This procedure is also\n * responsible for embedding short-circuit edges to make the algorithm run in linear time in the\n * worst case.\n *\n * @param componentRoot the root of the component to start the walkdown from\n */\n private void walkDown(Node componentRoot)\n {\n if (DEBUG) {\n System.out.printf(\"\\nStart walk down on node %s\\n\", componentRoot.toString(true));\n }\n for (int componentEntryDir = 0; componentEntryDir < 2 && stack.isEmpty();\n componentEntryDir++)\n {\n if (DEBUG) {\n System.out.println(\"\\nNew traversal direction = \" + componentEntryDir);\n }\n int currentComponentEntryDir = componentEntryDir;\n OuterFaceCirculator circulator = componentRoot.iterator(currentComponentEntryDir);\n for (Node current = circulator.next(); current != componentRoot;) {\n if (DEBUG) {\n System.out.printf(\"Current = %s\\n\", current.toString());\n }\n if (current.hasBackEdgeWrtTo(componentRoot)) {\n Node childPrev = circulator.getPrev();\n while (!stack.isEmpty()) {\n mergeBiconnectedComponent();\n if (DEBUG) {\n printState();\n }\n }\n circulator = embedBackEdge(\n componentRoot, componentEntryDir, current.edgeToEmbed, childPrev);\n if (DEBUG) {\n printState();\n printBiconnectedComponent(current);\n }\n }\n if (!current.pertinentRoots.isEmpty()) {\n int parentComponentEntryDir = currentComponentEntryDir;\n Node root = current.pertinentRoots.getFirst();\n\n if (DEBUG) {\n System.out.printf(\"Descending to the root = %s\\n\", root.toString());\n }\n OuterFaceCirculator ccwCirculator =\n getActiveSuccessorOnOuterFace(root, componentRoot, 0);\n Node ccwActiveNode = ccwCirculator.getCurrent();\n OuterFaceCirculator cwCirculator =\n getActiveSuccessorOnOuterFace(root, componentRoot, 1);\n Node cwActiveNode = cwCirculator.getCurrent();\n\n if (ccwActiveNode.isInternallyActiveWrtTo(componentRoot)) {\n currentComponentEntryDir = 0;\n } else if (cwActiveNode.isInternallyActiveWrtTo(componentRoot)) {\n currentComponentEntryDir = 1;\n } else if (ccwActiveNode.isPertinentWrtTo(componentRoot)) {\n currentComponentEntryDir = 0;\n } else {\n currentComponentEntryDir = 1;\n }\n\n if (currentComponentEntryDir == 0) {\n stack\n .add(\n new MergeInfo(\n current, circulator.next(), root, root.outerFaceNeighbors[1],\n parentComponentEntryDir, currentComponentEntryDir));\n current = ccwActiveNode;\n circulator = ccwCirculator;\n\n if (!cwActiveNode.hasRootNeighbor()) {\n embedShortCircuit(root, 1, cwCirculator);\n }\n } else {\n stack\n .add(\n new MergeInfo(\n current, circulator.next(), root, root.outerFaceNeighbors[0],\n parentComponentEntryDir, currentComponentEntryDir));\n current = cwActiveNode;\n circulator = cwCirculator;\n\n if (!ccwActiveNode.hasRootNeighbor()) {\n embedShortCircuit(root, 0, ccwCirculator);\n }\n }\n\n } else if (current.isInactiveWrtTo(componentRoot)) {\n current = circulator.next();\n } else {\n // current vertex is externally active\n if (DEBUG) {\n System.out.println(\"Current vertex is externally active, stop\\n\");\n }\n if (!current.hasRootNeighbor() && stack.isEmpty()) {\n embedShortCircuit(componentRoot, componentEntryDir, circulator);\n }\n break;\n }\n }\n }\n }\n\n /**\n * The walkup procedure from the original paper. Identifies the pertinent subgraph of the graph\n * by going up the dfs tree from the {@code start} node to the {@code end} node using the edge\n * {@code edge}\n *\n * @param start the node to start the walkup from\n * @param end the node currently processed by the main loop of the algorithm\n * @param edge a back edge to embed\n */\n private void walkUp(Node start, Node end, Edge edge)\n {\n if (DEBUG) {\n System.out.printf(\"\\nStart walk up on edge = %s\\n\", edge.toString());\n }\n int visited = end.dfsIndex;\n\n start.backEdgeFlag = visited;\n start.edgeToEmbed = edge;\n\n Node x = start.outerFaceNeighbors[0], y = start.outerFaceNeighbors[1], xPrev = start,\n yPrev = start;\n start.visited = visited;\n while (x != end && !x.isVisitedWrtTo(end) && !y.isVisitedWrtTo(end)) {\n if (DEBUG) {\n System.out.printf(\"Current x = %s\\nCurrent y = %s\\n\", x.toString(), y.toString());\n }\n x.visited = y.visited = visited;\n\n Node root = null;\n if (x.isRootVertex()) {\n root = x;\n } else if (y.isRootVertex()) {\n root = y;\n }\n if (root != null) {\n if (DEBUG) {\n System.out.printf(\"Found root = %s\\n\", root.toString());\n }\n Node rootChild = root.parentEdge.target;\n Node newStart = root.parentEdge.source;\n if (newStart != end) {\n if (rootChild.lowpoint < end.dfsIndex) {\n // the component in externally active\n root.listNode = newStart.pertinentRoots.addElementLast(root);\n } else {\n // the component is internally active\n root.listNode = newStart.pertinentRoots.addElementFirst(root);\n }\n } else {\n break;\n }\n newStart.visited = visited;\n xPrev = yPrev = newStart;\n x = newStart.outerFaceNeighbors[0];\n y = newStart.outerFaceNeighbors[1];\n\n } else {\n Node t = x;\n x = x.nextOnOuterFace(xPrev);\n xPrev = t;\n\n t = y;\n y = y.nextOnOuterFace(yPrev);\n yPrev = t;\n }\n }\n }\n\n /**\n * Lazily computes a combinatorial embedding of the {@code graph} by removing all the\n * short-circuit edges and properly orienting the edges around the nodes.\n *\n * @return a combinatorial embedding of the {@code graph}\n */\n private Embedding lazyComputeEmbedding()\n {\n lazyTestPlanarity();\n if (!planar) {\n throw new IllegalArgumentException(\n \"Input graph is not planar, can't compute graph embedding\");\n }\n if (embedding == null) {\n for (Node dfsTreeRoot : dfsTreeRoots) {\n cleanUpDfs(dfsTreeRoot);\n }\n Map> embeddingMap = new HashMap<>();\n for (Node node : nodes) {\n for (Node child : node.separatedDfsChildList) {\n Node virtualRoot = child.initialComponentRoot;\n node.embedded.append(virtualRoot.embedded);\n }\n List embeddedEdges = new ArrayList<>(node.embedded.size());\n for (Edge edge : node.embedded) {\n embeddedEdges.add(edge.graphEdge);\n }\n embeddingMap.put(node.graphVertex, embeddedEdges);\n }\n embedding = new EmbeddingImpl<>(graph, embeddingMap);\n }\n return embedding;\n }\n\n /**\n * Method for debug purposes, prints the boundary the {@code node} belongs to\n *\n * @param node a node on the outer face\n */\n private void printBiconnectedComponent(Node node)\n {\n StringBuilder builder = new StringBuilder(node.toString(false));\n OuterFaceCirculator circulator = node.iterator(0);\n Node current = circulator.next();\n Node stop = current;\n do {\n builder.append(\" -> \").append(current.toString(false));\n current = circulator.next();\n } while (current != stop);\n System.out.println(\"Biconnected component after merge: \" + builder.toString());\n }\n\n /**\n * Method for debug purposes, prints the state of the algorithm\n */\n private void printState()\n {\n System.out.println(\"\\nPrinting state:\");\n System.out.println(\"Dfs roots: \" + dfsTreeRoots);\n System.out.println(\"Nodes:\");\n for (Node node : nodes) {\n System.out.println(node.toString(true));\n }\n System.out.println(\"Virtual nodes:\");\n for (Node node : componentRoots) {\n System.out.println(node.toString(true));\n }\n List inverted = new ArrayList<>();\n for (Node node : nodes) {\n for (Edge edge : node.treeEdges) {\n if (edge.sign < 0) {\n inverted.add(edge);\n }\n }\n }\n System.out.println(\"Inverted edges = \" + inverted);\n }\n\n /**\n * Either finds and returns a circulator to the node on the boundary of the component, which\n * satisfies the {@code predicate} or returns a circulator to the {@code stop} node.\n *\n * @param predicate the condition the desired node should satisfy\n * @param start the node to start the search from\n * @param stop the node to end the search with\n * @param dir the direction to start the traversal in\n * @return a circulator to the node satisfying the {@code predicate} or to the {@code stop} node\n */\n private OuterFaceCirculator selectOnOuterFace(\n Predicate predicate, Node start, Node stop, int dir)\n {\n OuterFaceCirculator circulator = start.iterator(dir);\n Node current = circulator.next();\n while (current != stop && !predicate.test(current)) {\n current = circulator.next();\n }\n return circulator;\n }\n\n /**\n * Returns an active node on the outer face in the direction {@code dir} starting from the\n * {@code start} node\n *\n * @param start the node to start the search from\n * @param v an ancestor of the {@code start}\n * @param dir the direction of the search\n * @return a circulator to the found node\n */\n private OuterFaceCirculator getActiveSuccessorOnOuterFace(Node start, Node v, int dir)\n {\n return selectOnOuterFace(n -> n.isActiveWrtTo(v), start, start, dir);\n }\n\n /**\n * Returns acirculator to the externally active node on the outer face between the {@code start}\n * and {@code end} nodes in the direction {@code dir}.\n *\n * @param start the node to start the search from\n * @param stop the node to end the search with\n * @param v an ancestor of the {@code start} and the {@code end}\n * @param dir the direction of the search\n * @return a circulator to the found node\n */\n private OuterFaceCirculator getExternallyActiveSuccessorOnOuterFace(\n Node start, Node stop, Node v, int dir)\n {\n return selectOnOuterFace(n -> n.isExternallyActiveWrtTo(v), start, stop, dir);\n }\n\n /**\n * Returns a component root of component the {@code node} is contained in.\n *\n * @param node a node in the partially embedded graph\n * @return a component root of the component the {@code node} belongs to\n */\n private Node getComponentRoot(Node node)\n {\n return selectOnOuterFace(Node::isRootVertex, node, node, 0).getCurrent();\n }\n\n /**\n * Adds the edges on the path from the {@code startEdge} up to the node {@code stop} to the set\n * {@code edges}\n *\n * @param edges the set to add the path edges to\n * @param startEdge the edge to start from\n * @param stop the last node on the path\n */\n private void addPathEdges(Set edges, Edge startEdge, Node stop)\n {\n edges.add(startEdge);\n Node current = startEdge.source;\n while (current != stop) {\n edges.add(current.parentEdge);\n current = current.getParent();\n }\n }\n\n /**\n * Adds the edges between the {@code start} and the {@code end} to the set {@code edges}\n *\n * @param edges the set to add the path edges to to\n * @param start the node to start from\n * @param stop the node to end with\n */\n private void addPathEdges(Set edges, Node start, Node stop)\n {\n if (start != stop) {\n addPathEdges(edges, start.parentEdge, stop);\n }\n }\n\n /**\n * Searches a back edge which target has a height smaller than {@code heightMax}\n *\n * @param current the node to start from\n * @param heightMax an upper bound on the height of the desired back edge\n * @return the desired back edge or null, if no such edge exist\n */\n private Edge searchEdge(Node current, int heightMax)\n {\n return searchEdge(current, heightMax, null);\n }\n\n /**\n * Searches a back edge which target has a height smaller than {@code heightMax}\n *\n * @param current the node to start from\n * @param heightMax an upper bound on the height of the desired back edge\n * @param forbiddenEdge an edge the desired edge should not be equal to\n * @return the desired back edge or null, if no such edge exist\n */\n private Edge searchEdge(Node current, int heightMax, Edge forbiddenEdge)\n {\n Predicate isNeeded = e -> {\n if (forbiddenEdge == e) {\n return false;\n }\n return e.target.height < heightMax;\n };\n return searchEdge(current, isNeeded);\n }\n\n /**\n * Generically searches an edge in the subtree rooted at the {@code current}, which doesn't\n * include the children of the {@code current} that have beem merged to the parent biconnected\n * component.\n *\n * @param current the node to start the searh from\n * @param isNeeded the predicate which the desired edge should satisfy\n * @return an edge which satisfies the {@code predicate}, or null if such an edge doesn't exist\n */\n private Edge searchEdge(Node current, Predicate isNeeded)\n {\n for (Node node : current.separatedDfsChildList) {\n Edge result = searchSubtreeDfs(node, isNeeded);\n if (result != null) {\n return result;\n }\n }\n for (Edge edge : current.backEdges) {\n if (isNeeded.test(edge)) {\n return edge;\n }\n }\n return null;\n }\n\n /**\n * Recursively searches all the subtree root at the node {@code start} to find an edge\n * satisfying the {@code predicate}.\n *\n * @param start the node to start the search from.\n * @param isNeeded a predicate, which the desired edge should satisfy\n * @return a desired edge, or null if no such edge exist.\n */\n private Edge searchSubtreeDfs(Node start, Predicate isNeeded)\n {\n List stack = new ArrayList<>();\n stack.add(start);\n while (!stack.isEmpty()) {\n Node current = stack.remove(stack.size() - 1);\n\n for (Edge edge : current.backEdges) {\n if (isNeeded.test(edge)) {\n return edge;\n }\n }\n for (Edge edge : current.treeEdges) {\n stack.add(edge.target);\n }\n }\n return null;\n }\n\n /**\n * Returns the highest of the two input node, i.e. the node with the greater height\n *\n * @param a a node in the dfs tree\n * @param b a node in the dfs tree\n * @return the highest of the two nodes\n */\n private Node highest(Node a, Node b)\n {\n return a.height > b.height ? a : b;\n }\n\n /**\n * Returns the lowest of the two input node, i.e. the node with the least height.\n *\n * @param a a node in the dfs tree\n * @param b a node in the dfs tree\n * @return the lowest of the two nodes\n */\n private Node lowest(Node a, Node b)\n {\n return a.height < b.height ? a : b;\n }\n\n /**\n * Iteratively sets a boundary height for the nodes on the outer face branch ending at the node\n * {@code w}.\n *\n * @param componentRoot the root of the component\n * @param w the end of the outer face branch\n * @param dir the direction to start the traversal in\n * @param delta a value in $\\{+1, -1\\}$ to set either positive or negative boundary height\n */\n private void setBoundaryDepth(Node componentRoot, Node w, int dir, int delta)\n {\n OuterFaceCirculator circulator = componentRoot.iterator(dir);\n Node current = circulator.next();\n int currentHeight = delta;\n while (current != w) {\n current.boundaryHeight = currentHeight;\n currentHeight += delta;\n current = circulator.next();\n }\n }\n\n /**\n * Clears the visited variable of all the nodes and component roots\n */\n private void clearVisited()\n {\n nodes.forEach(n -> n.visited = 0);\n componentRoots.forEach(n -> n.visited = 0);\n }\n\n /**\n * Generically searches a path from the {@code current} node to the first node satisfying the\n * {@code isFinish} predicate consisting of all the nodes satisfying the {@code canGo}\n * predicate. The key property of this method is that it searches the next edge on the path in\n * the clockwise order starting from the previous edge. The edges of the resulting path are\n * added to the {@code edges}.\n *\n * @param start the start node of the traversal\n * @param startPrev the previous edge of the start node\n * @param canGo specifies where the search can go\n * @param isFinish specifies what nodes are finish nodes\n * @param edges the list containing the resulting path\n * @return true if the search was successful, false otherwise\n */\n private boolean findPathDfs(\n Node start, Edge startPrev, Predicate canGo, Predicate isFinish,\n List edges)\n {\n List stack = new ArrayList<>();\n stack.add(new SearchInfo(start, startPrev, false));\n while (!stack.isEmpty()) {\n SearchInfo info = stack.remove(stack.size() - 1);\n if (isFinish.test(info.current)) {\n edges.add(info.prevEdge);\n edges.remove(0);\n return true;\n }\n if (info.backtrack) {\n edges.remove(edges.size() - 1);\n } else {\n if (info.current.visited != 0) {\n continue;\n }\n info.current.visited = 1;\n stack.add(new SearchInfo(info.current, info.prevEdge, true));\n edges.add(info.prevEdge);\n /*\n * The iteration is performed in the reverse order since the infos are pushed on the\n * stack and therefore will be processed in the again reverse order\n */\n Iterator iterator =\n info.current.embedded.reverseCircularIterator(info.prevEdge);\n while (iterator.hasNext()) {\n Edge currentEdge = iterator.next();\n Node opposite = currentEdge.getOpposite(info.current);\n if ((!canGo.test(opposite) || opposite.visited != 0)\n && !isFinish.test(opposite))\n {\n continue;\n }\n stack.add(new SearchInfo(opposite, currentEdge, false));\n }\n }\n }\n return false;\n }\n\n /**\n * Finds the highest obstructing path in the component rooted at {@code componentRoot}. See the\n * original paper for the definition of the obstructing path. This method heavily relies on the\n * fact that the method\n * {@link BoyerMyrvoldPlanarityInspector#findPathDfs(Node, Edge, Predicate, Predicate, List)}\n * chooses the edges in the clockwise order.\n *\n * @param componentRoot the root of the component\n * @param w the node called {@code w} in the Kuratowski subdivision extraction phase.\n * @return the edges of the desired path as a list\n */\n private List findHighestObstructingPath(Node componentRoot, Node w)\n {\n clearVisited();\n List result = new ArrayList<>();\n OuterFaceCirculator circulator = componentRoot.iterator(0);\n Node current = circulator.next();\n while (current != w) {\n if (findPathDfs(\n current, current.embedded.getFirst(), n -> !n.marked, n -> n.boundaryHeight < 0,\n result))\n {\n return result;\n }\n current = circulator.next();\n }\n return result;\n }\n\n /**\n * Finishes the Kuratowski subdivision extraction by constructing the desired subgraph\n *\n * @param subdivision the edges in the Kuratowski subdivision\n * @return the Kuratowski subgraph of the {@code graph}\n */\n private Graph finish(Set subdivision)\n {\n Set edgeSubset = new HashSet<>();\n Set vertexSubset = new HashSet<>();\n subdivision.forEach(e -> {\n edgeSubset.add(e.graphEdge);\n vertexSubset.add(e.target.graphVertex);\n vertexSubset.add(e.source.graphVertex);\n });\n kuratowskiSubdivision = new AsSubgraph<>(graph, vertexSubset, edgeSubset);\n return kuratowskiSubdivision;\n }\n\n /**\n * Adds the edges on the outer face of the component rooted at {@code componentRoot} to the set\n * {@code edges}\n *\n * @param edges the set to add the edges to\n * @param componentRoot the root of the biconnected component\n */\n private void addBoundaryEdges(Set edges, Node componentRoot)\n {\n OuterFaceCirculator circulator = componentRoot.iterator(0);\n Node current;\n do {\n Edge edge = circulator.edgeToNext();\n edge.source.marked = edge.target.marked = true;\n edges.add(edge);\n current = circulator.next();\n } while (current != componentRoot);\n }\n\n /**\n * Cleans up the dfs trees before the Kuratowski subdivision extraction phase\n */\n private void kuratowskiCleanUp()\n {\n for (Node dfsTreeRoot : dfsTreeRoots) {\n cleanUpDfs(dfsTreeRoot);\n }\n for (Node node : componentRoots) {\n if (node.outerFaceNeighbors[0] != null) {\n node.removeShortCircuitEdges();\n fixBoundaryOrder(node);\n }\n }\n }\n\n /**\n * Recursively cleans up the dfs tree rooted at the {@code dfsTreeRoot} my removing all the\n * short-circuit edges and properly orienting other embedded edges\n *\n * @param dfsTreeRoot the root of the dfs tree to clean up\n */\n private void cleanUpDfs(Node dfsTreeRoot)\n {\n List> stack = new ArrayList<>();\n stack.add(Pair.of(dfsTreeRoot, 1));\n while (!stack.isEmpty()) {\n Pair entry = stack.remove(stack.size() - 1);\n Node current = entry.getFirst();\n int sign = entry.getSecond();\n if (sign < 0) {\n current.embedded.invert();\n }\n current.removeShortCircuitEdges();\n for (Node node : current.separatedDfsChildList) {\n // all the components, that aren't merged, aren't inverted\n node.parentEdge.sign = sign;\n }\n\n for (Edge treeEdge : current.treeEdges) {\n stack.add(Pair.of(treeEdge.target, sign * treeEdge.sign));\n }\n }\n\n }\n\n /**\n * Orient the connections on the outer face of the component rooted at {@code componentRoot}\n * such that they are ordered\n *\n * @param componentRoot the root of the component to process\n */\n private void fixBoundaryOrder(Node componentRoot)\n {\n if (componentRoot.embedded.size() < 2) {\n return;\n }\n Node componentParent = componentRoot.getParent();\n Edge edgeToNext = componentRoot.embedded.getLast(),\n edgeToPrev = componentRoot.embedded.getFirst();\n Node next = edgeToNext.getOpposite(componentParent),\n prev = edgeToPrev.getOpposite(componentParent);\n\n componentRoot.outerFaceNeighbors[0] = next;\n componentRoot.outerFaceNeighbors[1] = prev;\n next.outerFaceNeighbors[1] = componentRoot;\n prev.outerFaceNeighbors[0] = componentRoot;\n Node current = componentRoot.outerFaceNeighbors[0];\n do {\n edgeToNext = current.embedded.getLast();\n edgeToPrev = current.embedded.getFirst();\n next = edgeToNext.getOpposite(current);\n prev = edgeToPrev.getOpposite(current);\n if (prev != componentParent) {\n current.outerFaceNeighbors[1] = prev;\n }\n if (next != componentParent) {\n current.outerFaceNeighbors[0] = next;\n }\n current = next;\n } while (current != componentParent);\n }\n\n /**\n * Removes the edges from the outer face from the {@code start} node to the {@code end} node in\n * the direction {@code dir} from the set {@code edges}\n *\n * @param start the start of the boundary path\n * @param end the end of the boundary path\n * @param dir the direction to take from the {@code start} node\n * @param edges the set of edges to modify\n */\n private void removeUp(Node start, Node end, int dir, Set edges)\n {\n if (start == end) {\n return;\n }\n OuterFaceCirculator circulator = start.iterator(dir);\n Node next;\n do {\n Edge edge = circulator.edgeToNext();\n edges.remove(edge);\n next = circulator.next();\n } while (next != end);\n }\n\n /**\n * Effectively is a method for finding node {@code z} in the notations of the original paper.\n * The search proceeds in the reverse order of the path from the {@code backEdge} to the node\n * {@code w}\n *\n * @param w the start of the path down\n * @param backEdge the last edge on the path\n * @return the desired node {@code z} or null if the source of the {@code backEdge} is equal to\n * {@code w}\n */\n private Node getNextOnPath(Node w, Edge backEdge)\n {\n if (backEdge.source == w) {\n return null;\n }\n Node prev = backEdge.source, current = backEdge.source.getParent();\n while (current != w) {\n prev = current;\n current = current.getParent();\n }\n return prev;\n }\n\n /**\n * Finds a path from some intermediate nodes on the path represented by the list {@code path} to\n * the node {@code v}. The path to {@code v} certainly doesn't exist if the list {@code path}\n * has size 1, because we're looking for a path from some intermediate node\n *\n * @param path the path between left and right outer face branches\n * @param v the parent of the biconnected component\n * @return the path edges in a list, which can be empty\n */\n private List findPathToV(List path, Node v)\n {\n clearVisited();\n int i = 0;\n Edge currentEdge = path.get(i);\n Node current =\n currentEdge.source.boundaryHeight != 0 ? currentEdge.target : currentEdge.source;\n List result = new ArrayList<>();\n while (i < path.size() - 1) {\n if (findPathDfs(current, currentEdge, n -> !n.marked, n -> n == v, result)) {\n return result;\n }\n ++i;\n currentEdge = path.get(i);\n current = currentEdge.getOpposite(current);\n }\n return result;\n }\n\n /**\n * Checks whether the first node {@code a} is strictly higher than nodes {@code b} and {@code c}\n *\n * @param a a node in the dfs tree\n * @param b a node in the dfs tree\n * @param c a node in the dfs tree\n * @return true if the first node in strictly higher that other node, false otherwise\n */\n private boolean firstStrictlyHigher(Node a, Node b, Node c)\n {\n return a.height > b.height && a.height > c.height;\n }\n\n /**\n * Checks whether the biconnected component rooted at {@code componentRoot} can be used to\n * extract a Kuratowski subdivision. It can be used in the case there is one externally active\n * node on each branch of the outer face and there is a pertinent node on the lower part of the\n * outer face between these two externally active nodes.\n *\n * @param componentRoot the root of the biconnected component\n * @param v an ancestor of the nodes in the biconnected component\n * @return an unembedded back edge, which target is {@code v} and which can be used to extract a\n * Kuratowski subdivision, or {@code null} is no such edge exist for this biconnected\n * component\n */\n private Edge checkComponentForFailedEdge(Node componentRoot, Node v)\n {\n OuterFaceCirculator firstDir =\n getExternallyActiveSuccessorOnOuterFace(componentRoot, componentRoot, v, 0);\n Node firstDirNode = firstDir.getCurrent();\n OuterFaceCirculator secondDir =\n getExternallyActiveSuccessorOnOuterFace(componentRoot, componentRoot, v, 1);\n Node secondDirNode = secondDir.getCurrent();\n if (firstDirNode != componentRoot && firstDirNode != secondDirNode) {\n Node current = firstDir.next();\n while (current != secondDirNode) {\n if (current.isPertinentWrtTo(v)) {\n return searchEdge(current, e -> e.target == v && !e.embedded);\n }\n current = firstDir.next();\n }\n }\n return null;\n }\n\n /**\n * Finds an unembedded back edge to {@code v}, which can be used to extract the Kuratowski\n * subdivision. If the merge stack isn't empty, the last biconnected component processed by the\n * walkdown can be used to find such an edge, because walkdown descended to that component\n * (which means that component is pertinent) and couldn't reach a pertinent node. This can only\n * happen by encountering externally active nodes on both branches of the traversal. Otherwise,\n * be have look in all the child biconnected components to find an unembedded back edge. We're\n * guided by the fact that an edge can not be embedded only in the case both traversals of the\n * walkdown could reach all off the pertinent nodes. This in turn can happen only if both\n * traversals get stuck on externally active nodes.\n *

          \n * Note: not every unembedded back edge can be used to extract a Kuratowski subdivision\n *\n * @param v the vertex which has an unembedded back edge incident to it\n * @return the found unembedded back edge which can be used to extract a Kuratowski subdivision\n */\n private Edge findFailedEdge(Node v)\n {\n if (stack.isEmpty()) {\n for (Node child : v.separatedDfsChildList) {\n Node componentRoot = child.initialComponentRoot;\n Edge result = checkComponentForFailedEdge(componentRoot, v);\n if (result != null) {\n return result;\n }\n }\n return null; // should not happen in case node v has an incident unembedded back edge\n } else {\n MergeInfo info = stack.get(stack.size() - 1);\n return checkComponentForFailedEdge(info.child, v);\n }\n }\n\n /**\n * Lazily extracts a Kuratowski subdivision from the {@code graph}. The process of adding the\n * edges of the subdivision to the resulting set of edges had been made explicit for every case.\n *\n * @return a Kuratowski subgraph of the {@code graph}\n */\n private Graph lazyExtractKuratowskiSubdivision()\n {\n if (kuratowskiSubdivision == null) {\n // remove short-circuit edges and orient all embedded lists clockwise\n kuratowskiCleanUp();\n if (DEBUG) {\n printState();\n }\n Set subdivision = new HashSet<>();\n // find the needed unembedded back edge which can be used to find Kuratowski subgraph\n Edge failedEdge = findFailedEdge(failedV);\n assert failedEdge != null;\n /*\n * We're iteratively moving up traversing the outer faces of the biconnected components\n * to find externally active nodes x and y, which are on different branches of the outer\n * face. The way we're finding the nodes x and y helps us eliminate the case E_1\n * described in the original paper. This can be done because we always find the closest\n * to the node w externally active nodes x and y.\n */\n Node x, y, v = failedEdge.target, w = failedEdge.source, componentRoot;\n while (true) {\n componentRoot = getComponentRoot(w);\n x = getExternallyActiveSuccessorOnOuterFace(w, componentRoot, v, 1).getCurrent();\n y = getExternallyActiveSuccessorOnOuterFace(w, componentRoot, v, 0).getCurrent();\n if (x.isRootVertex()) {\n w = x.getParent();\n } else if (y.isRootVertex()) {\n w = y.getParent();\n } else {\n componentRoot = getComponentRoot(w);\n break;\n }\n }\n Edge xBackEdge = searchEdge(x, v.height);\n Edge yBackEdge = searchEdge(y, v.height);\n if (DEBUG) {\n System.out\n .printf(\n \"Failed v = %s, failed edge = %s\\n\", failedV.toString(false),\n failedEdge.toString());\n System.out.printf(\"x = %s, y = %s\\n\", x.toString(false), y.toString(false));\n System.out\n .printf(\n \"xBackEdge = %s, yBackEdge = %s\\n\", xBackEdge.toString(),\n yBackEdge.toString());\n }\n Node backLower = lowest(xBackEdge.target, yBackEdge.target);\n Node backHigher = highest(xBackEdge.target, yBackEdge.target);\n addPathEdges(subdivision, xBackEdge, x);\n addPathEdges(subdivision, yBackEdge, y);\n addBoundaryEdges(subdivision, componentRoot);\n\n if (componentRoot.getParent() != v) {\n // case A, v isn't a parent of the component we've found\n if (PRINT_CASES) {\n System.out.println(\"Case A\");\n }\n addPathEdges(subdivision, componentRoot.getParent(), backLower);\n addPathEdges(subdivision, failedEdge, w);\n return finish(subdivision);\n }\n // node z will be null only if the tree path from w to failedEdge is failedEdge itself\n Node z = getNextOnPath(w, failedEdge);\n Edge backEdge = null;\n if (z != null) {\n backEdge = searchSubtreeDfs(z, e -> e.target.height < v.height && e != failedEdge);\n }\n if (backEdge != null) {\n // case B\n if (PRINT_CASES) {\n System.out.println(\"Case B\");\n }\n addPathEdges(subdivision, backEdge, w);\n addPathEdges(subdivision, failedEdge, w);\n Node highest =\n highest(xBackEdge.target, highest(yBackEdge.target, backEdge.target));\n Node lowest = lowest(xBackEdge.target, lowest(yBackEdge.target, backEdge.target));\n addPathEdges(subdivision, highest, lowest);\n return finish(subdivision);\n }\n /*\n * If we failed to either case A or B, we have to find a highest obstructing path and\n * then deal with cases C - E\n */\n setBoundaryDepth(componentRoot, w, 0, 1);\n setBoundaryDepth(componentRoot, w, 1, -1);\n\n assert x.boundaryHeight > 0;\n List path = findHighestObstructingPath(componentRoot, w);\n assert !path.isEmpty();\n if (DEBUG) {\n System.out.println(\"Path = \" + path);\n }\n\n Edge firstEdge = path.get(0);\n Edge lastEdge = path.get(path.size() - 1);\n Node firstNode =\n firstEdge.source.boundaryHeight > 0 ? firstEdge.source : firstEdge.target;\n Node lastNode = lastEdge.source.boundaryHeight < 0 ? lastEdge.source : lastEdge.target;\n if (firstNode.boundaryHeight < x.boundaryHeight\n || lastNode.boundaryHeight > y.boundaryHeight)\n {\n // case C, either the first node or the last node of the path is higher than x or y\n // respectively\n if (PRINT_CASES) {\n System.out.println(\"Case C\");\n }\n Node removeStart;\n if (lastNode.boundaryHeight > y.boundaryHeight) {\n removeStart = firstNode.boundaryHeight < x.boundaryHeight ? firstNode : x;\n removeUp(removeStart, componentRoot, 1, subdivision);\n } else {\n removeUp(y, componentRoot, 0, subdivision);\n }\n addPathEdges(subdivision, failedEdge, w);\n subdivision.addAll(path);\n addPathEdges(subdivision, v, backLower);\n return finish(subdivision);\n }\n path.forEach(e -> e.source.marked = e.target.marked = true);\n List pathToV = findPathToV(path, v);\n if (!pathToV.isEmpty()) {\n // case D, we have a path to the node v\n if (PRINT_CASES) {\n System.out.println(\"Case D\");\n }\n removeUp(x, componentRoot, 1, subdivision);\n removeUp(y, componentRoot, 0, subdivision);\n subdivision.addAll(path);\n subdivision.addAll(pathToV);\n addPathEdges(subdivision, v, backLower);\n addPathEdges(subdivision, failedEdge, w);\n return finish(subdivision);\n }\n Edge externallyActive = searchEdge(w, v.height, failedEdge);\n assert externallyActive != null;\n if (DEBUG) {\n System.out.printf(\"Externally active edge = %s\\n\", externallyActive.toString());\n }\n addPathEdges(subdivision, externallyActive, w);\n if (firstStrictlyHigher(externallyActive.target, xBackEdge.target, yBackEdge.target)) {\n // case E_2, equivalent to A\n if (PRINT_CASES) {\n System.out.println(\"Case E_2\");\n }\n addPathEdges(subdivision, componentRoot.getParent(), backLower);\n } else if (firstStrictlyHigher(\n xBackEdge.target, yBackEdge.target, externallyActive.target))\n {\n // case E_2, u_x is higher\n if (PRINT_CASES) {\n System.out.println(\"Case E_2, u_x is higher\");\n }\n removeUp(componentRoot, x, 0, subdivision);\n removeUp(w, lastNode, 0, subdivision);\n subdivision.addAll(path);\n addPathEdges(subdivision, failedEdge, w);\n addPathEdges(subdivision, v, lowest(backLower, externallyActive.target));\n } else if (firstStrictlyHigher(\n yBackEdge.target, xBackEdge.target, externallyActive.target))\n {\n // case E_2, u_y is higher\n if (PRINT_CASES) {\n System.out.println(\"Case E_2, u_y is higher\");\n }\n removeUp(y, componentRoot, 0, subdivision);\n removeUp(firstNode, w, 0, subdivision);\n subdivision.addAll(path);\n addPathEdges(subdivision, failedEdge, w);\n addPathEdges(subdivision, v, lowest(backLower, externallyActive.target));\n } else if (firstNode.boundaryHeight > x.boundaryHeight) {\n // case E_4, p_x is lower than x\n if (PRINT_CASES) {\n System.out.println(\"Case E_3, p_x is lower than x\");\n }\n removeUp(w, lastNode, 0, subdivision);\n subdivision.addAll(path);\n addPathEdges(subdivision, failedEdge, w);\n addPathEdges(\n subdivision, highest(backHigher, externallyActive.target),\n lowest(backLower, externallyActive.target));\n } else if (lastNode.boundaryHeight < y.boundaryHeight) {\n // case E_4, p_y is lower than y\n if (PRINT_CASES) {\n System.out.println(\"Case E_3, p_y is lower than y\");\n }\n removeUp(firstNode, w, 0, subdivision);\n subdivision.addAll(path);\n addPathEdges(subdivision, failedEdge, w);\n addPathEdges(\n subdivision, highest(backHigher, externallyActive.target),\n lowest(backLower, externallyActive.target));\n } else {\n // case E, extracting K_5\n if (PRINT_CASES) {\n System.out.println(\"Case E, extracting K_5\");\n }\n subdivision.addAll(path);\n addPathEdges(subdivision, v, lowest(backLower, externallyActive.target));\n addPathEdges(subdivision, failedEdge, w);\n }\n return finish(subdivision);\n }\n return kuratowskiSubdivision;\n }\n\n /**\n * {@inheritDoc}\n *

          \n * Only the first call to this method does the actual computation, all subsequent calls only\n * return the previously computed value.\n */\n @Override\n public boolean isPlanar()\n {\n return lazyTestPlanarity();\n }\n\n /**\n * {@inheritDoc}\n *

          \n * Only the first call to this method does the actual computation, all subsequent calls only\n * return the previously computed value.\n */\n @Override\n public Embedding getEmbedding()\n {\n if (isPlanar()) {\n return lazyComputeEmbedding();\n } else {\n throw new IllegalArgumentException(\"Graph is not planar\");\n }\n }\n\n /**\n * {@inheritDoc}\n *

          \n * Only the first call to this method does the actual computation, all subsequent calls only\n * return the previously computed value.\n */\n @Override\n public Graph getKuratowskiSubdivision()\n {\n if (isPlanar()) {\n throw new IllegalArgumentException(\"Graph is planar\");\n } else {\n return lazyExtractKuratowskiSubdivision();\n }\n }\n\n /**\n * Represents information needed to search a path within a biconnected component\n */\n private class SearchInfo\n {\n /**\n * The current node of the dfs traversal\n */\n Node current;\n /**\n * The edge used to go to the {@code current} vertex\n */\n Edge prevEdge;\n /**\n * Whether dfs is in a forward or a backtracking phase\n */\n boolean backtrack;\n\n /**\n * Creates a new search info\n *\n * @param current the current node of the traversal\n * @param prevEdge the edge used to go to the {@code current} vertex\n * @param backtrack whether dfs is in a forward or a backtracking phase\n */\n SearchInfo(Node current, Edge prevEdge, boolean backtrack)\n {\n this.current = current;\n this.prevEdge = prevEdge;\n this.backtrack = backtrack;\n }\n }\n\n /**\n * Represents information needed to store in the stack during the input {@code graph}\n * orientation.\n */\n private class OrientDfsStackInfo\n {\n /**\n * The current vertex of the dfs traversal\n */\n V current;\n /**\n * The parent vertex of the {@code current} vertex, which is null for dfs tree roots\n */\n V parent;\n /**\n * The edge connecting {@code parent} and {@code current} vertices\n */\n E parentEdge;\n /**\n * Whether dfs is moving forward or backtracking on the {@code current} node\n */\n boolean backtrack;\n\n /**\n * Creates new instance of the information stored on the stack during the orientation of the\n * {@code graph}\n *\n * @param current the vertex dfs is currently processing\n * @param parent the parent of the {@code current} vertex\n * @param parentEdge the edge between {@code current} and {@code parent} vertices\n * @param backtrack whether dfs is moving forward or backtracking on the {@code current}\n * vertex\n */\n OrientDfsStackInfo(V current, V parent, E parentEdge, boolean backtrack)\n {\n this.current = current;\n this.parent = parent;\n this.parentEdge = parentEdge;\n this.backtrack = backtrack;\n }\n }\n\n /**\n * The information needed to merge two consecutive biconnected components\n */\n private class MergeInfo\n {\n /**\n * The node current traversal descended from. This node belongs to the parent biconnected\n * component\n */\n Node parent;\n /**\n * The next node along the traversal of the parent biconnected component\n */\n Node parentNext;\n /**\n * The virtual root of the child biconnected component\n */\n Node child;\n /**\n * The previous node along the traversal of the child biconnected component\n */\n Node childPrev;\n /**\n * The direction used to enter the parent biconnected component.\n *

          \n * Note: this value doesn't specify the direction from {@code parent} node to the\n * {@code parentNext} node, i.e. {@code parent.outerFaceNeighbors[vIn]} may not be equal to\n * the {@code parentNext}. Instead, this value specifies the direction used to start the\n * traversal from the parent's biconnected component virtual root.\n */\n int vIn;\n /**\n * The direction used to start the traversal of the child biconnected component. Since the\n * {@code child} is the component root, {@code child.outerFaceNeighbors[|1-vOut|]} is equal\n * to the {@code childPrev}\n */\n int vOut;\n\n /**\n * Creates new instance of the infromation needed to merge to biconnected components\n *\n * @param parent the node current traversal descended from\n * @param parentNext the next node along the traversal of the parent component\n * @param child the virtual root of the child biconnected component\n * @param childPrev the previous node along the traversal of the child component\n * @param vIn the direction used to enter the parent biconnected component\n * @param vOut the direction used to enter the child biconnected component\n */\n MergeInfo(Node parent, Node parentNext, Node child, Node childPrev, int vIn, int vOut)\n {\n this.parent = parent;\n this.parentNext = parentNext;\n this.child = child;\n this.childPrev = childPrev;\n this.vIn = vIn;\n this.vOut = vOut;\n }\n\n /**\n * Returns true if the traversal was inverted when descending to the child biconnected\n * component, false otherwise\n *\n * @return true if the traversal was inverted when descending to the child biconnected\n * component, false otherwise\n */\n boolean isInverted()\n {\n return vIn != vOut;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n return String\n .format(\n \"Parent dir = {%s -> %s}, child_dir = {%s -> %s}, inverted = %b, vIn = %d, vOut = %d\",\n parent.toString(false), parentNext.toString(false), childPrev.toString(false),\n child.toString(false), isInverted(), vIn, vOut);\n }\n }\n\n /**\n * A circulator over the nodes on the boundary of the biconnected component. Traverses the nodes\n * in the cyclic manner, i.e. it doesn't stop when all the nodes are traversed\n */\n private class OuterFaceCirculator\n implements\n Iterator\n {\n /**\n * The node this circulator will return next\n */\n private Node current;\n /**\n * The previous node along the traversal of the component boundary. This node is needed\n * because the component boundary nodes aren't connected in an ordered way.\n */\n private Node prev;\n\n /**\n * Creates a new instance of the circulator over the biconnected component boundary nodes.\n * The {@code prev} node is considered to be just traversed\n *\n * @param current the node this circulator will return next\n * @param prev the previous node along the traversal\n */\n OuterFaceCirculator(Node current, Node prev)\n {\n this.current = current;\n this.prev = prev;\n }\n\n /**\n * {@inheritDoc}\n *

          \n * Always returns true since this is a circulator\n */\n @Override\n public boolean hasNext()\n {\n return true;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Node next()\n {\n Node t = current;\n current = current.nextOnOuterFace(prev);\n prev = t;\n return prev;\n }\n\n /**\n * Returns an edge connecting previously returned node with node, which will be returned\n * next. If either of the mentioned nodes is virtual, the edge will be incident to its real\n * counterpart.\n *\n * @return an edge from the current node to the next node\n */\n Edge edgeToNext()\n {\n Edge edge = prev.embedded.getFirst();\n Node target = toExistingNode(current);\n Node source = toExistingNode(prev);\n if (edge.getOpposite(source) == target) {\n return edge;\n } else {\n return prev.embedded.getLast();\n }\n }\n\n /**\n * Returns the node this circulator has just traversed\n *\n * @return the node this circulator has just traversed\n */\n Node getCurrent()\n {\n return prev;\n }\n\n /**\n * Returns a node adjacent to the current node along the boundary, which is not equal to the\n * next node along the traversal. If the component consist of just one real node, returns\n * the only neighbor the the current node.\n *\n * @return node before the current node along the traversal\n */\n Node getPrev()\n {\n return prev.nextOnOuterFace(current);\n }\n\n /**\n * Returns either {@code node} or its real counterpart in the case the {@code node} is a\n * component root.\n *\n * @param node the input argument\n * @return the real counterpath of the {@code node}\n */\n private Node toExistingNode(Node node)\n {\n return node.isRootVertex() ? node.getParent() : node;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n return String.format(\"%s -> %s\", prev.toString(false), current.toString(false));\n }\n }\n\n /**\n * Internal representation of the edges of the input {@code graph}.\n */\n private class Edge\n {\n /**\n * The counterpart of this edge in the {@code graph}. This value can be null if the edge was\n * created as a short-circuit edge.\n */\n E graphEdge;\n /**\n * The source node of this edge. For tree edges the {@code source} is lower than the\n * {@code target}, for back edges the {@code target} is lower (having smaller height)\n */\n Node source;\n /**\n * The target of this edge\n */\n Node target;\n /**\n * Either $+1$ or $-1$ for regular and inverted edges respectively. This value is set to\n * $-1$ to flip a biconnected component in $\\mathcal{O}(1)$ time. Note: this\n * operation doesn't flip any of the child biconnected components of this biconnected\n * component\n */\n int sign;\n /**\n * Whether the edge is embedded or not. This value is important for\n */\n boolean embedded;\n /**\n * Whether the edge is real or short-circuit. See the original paper for the definition of\n * the short-circuit edges.\n */\n boolean shortCircuit;\n\n /**\n * Creates a new short-circuit edge with no counterpart in {@code graph}. The {@code source}\n * of this edge is always a real node on the boundary of some biconnected component, and the\n * {@code target} node is the parent node of the biconnected component the source node\n * belongs to, so the edge resembles a regular back edge except for that it doesn't have a\n * counterpart in the {@code graph}\n *\n * @param source the source of the short-circuit edge\n * @param target the target of the short-circuit edge\n */\n Edge(Node source, Node target)\n {\n this(null, source, target);\n this.shortCircuit = true;\n this.embedded = true;\n }\n\n /**\n * Creates a new tree edge.\n *\n * @param graphEdge the counterpart of this edge in the {@code graph}\n * @param source the source node of this edge\n */\n Edge(E graphEdge, Node source)\n {\n this(graphEdge, source, null);\n }\n\n /**\n * Creates a new edge. This constructor is used directly for the creation of the back edges\n *\n * @param graphEdge the counterpart of this edge in the {@code graph}\n * @param source the source node of this edge\n * @param target the target node of this edge\n */\n Edge(E graphEdge, Node source, Node target)\n {\n this.graphEdge = graphEdge;\n this.source = source;\n this.target = target;\n this.sign = 1;\n }\n\n /**\n * True if this edge is incident to the node {@code node}, false otherwise\n *\n * @param node the node to test\n * @return true if this edge is incident to the node {@code node}, false otherwise\n */\n boolean isIncidentTo(Node node)\n {\n return source == node || target == node;\n }\n\n /**\n * Returns the opposite node of the {@code node}\n *\n * @param node an endpoint of this edge\n * @return the other endpoint of this edge\n */\n Node getOpposite(Node node)\n {\n assert isIncidentTo(node); // debug purpose assertion\n return source == node ? target : source;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n String formatString = \"%s -> %s\";\n if (shortCircuit) {\n formatString = \"%s ~ %s\";\n }\n return String.format(formatString, source.toString(false), target.toString(false));\n }\n }\n\n /**\n * The internal representation of the vertices of the graph. Contains necessary information to\n * perform dfs traversals, biconnected component boundary traversals, to embed edges, etc.\n */\n private class Node\n {\n /**\n * The counterpart of this node in the {@code graph}. For the component roots this value is\n * {@code null}.\n */\n V graphVertex;\n /**\n * Whether this node is a root of the biconnected component or not.\n */\n boolean rootVertex;\n /**\n * The dfs index of this node in the graph. Every node has a unique dfs index in the range\n * $[0,|V| - 1]$. This value is used to order the nodes for the embedding of the edges\n * incident to them. The index of the first dfs root is $1$\n */\n int dfsIndex;\n /**\n * The height of the node in the created dfs tree. The root of the tree has height $0$. The\n * smaller this value is, the lower the node is considered to be.\n */\n int height;\n /**\n * The least dfs index of the nodes' least ancestors in the subtree rooted at this\n * node. If the subtree doesn't contain a node with a back edge, that ends lower that this\n * node, this value is equal to the dfs index of this node.\n */\n int lowpoint;\n /**\n * The least dfs index of the nodes adjacent to this node. If the node doesn't have incident\n * back edges, this value is equal to the dfs index of the node itself.\n */\n int leastAncestor;\n /**\n * Stores some value to indicate whether this node is visited in the current context or not.\n * During the testing phase, if this value if equal to the dfs index of the currently\n * processed node $v$, then this node is visited, otherwise not. During the Kuratowski\n * subdivision extraction phase, the value of $0$ indicates that the node isn't visited,\n * otherwise, the node is considered to be visited.\n */\n int visited;\n /**\n * During the process of embedding of the down edges of the node $v$, this variable is set\n * to the dfs index of $v$ to indicate that this node has a back edge incident to $v$, which\n * needs to be embedded.\n */\n int backEdgeFlag;\n /**\n * The height of this node on the boundary of the biconnected component, which is used to\n * extract the Kuratowski subdivision. The height of the component root is $0$, the heights\n * on the left side are positive, on the right side - negative. This value is used to\n * quickly determine for two nodes on the same boundary branch which one is higher (closer\n * to the component root).\n */\n int boundaryHeight;\n /**\n * Used to mark the boundary nodes of the biconnected\n */\n boolean marked;\n /**\n * Edge to the parent node of this node in the dfs tree. For tree roots this value is\n * {@code null}\n */\n Edge parentEdge;\n /**\n * If this node has a back edge incident to the currently processed node $v$, then this\n * variable stores this edge\n */\n Edge edgeToEmbed;\n /**\n * The component root the node is created in. For dfs tree roots this value is {@code null}\n */\n Node initialComponentRoot;\n /**\n * Two neighbors on the outer face of the biconnected component. Their order is completely\n * irrelevant for the algorithm to traverse the outer face.\n */\n Node[] outerFaceNeighbors;\n /**\n * The list containing the dfs children of this node, which are in the different child\n * biconnected component, i.e. their weren't merged in the parent component.\n */\n DoublyLinkedList separatedDfsChildList;\n /**\n * The roots of the pertinent components during the processing of the node $v$. These are\n * the components that have pertinent descendant nodes, i.e. nodes incident to the node $v$\n * via a back edge\n */\n DoublyLinkedList pertinentRoots;\n /**\n * The list of tree edges incident to this node in the dfs tree. This list doesn't contain a\n * parent edge of this node\n */\n List treeEdges;\n /**\n * The list containing the edges from descendants of this node in the dfs tree. For each\n * such descendant the corresponding edge is a back edge.\n */\n List downEdges;\n /**\n * The list of back edges incident to this node.\n */\n List backEdges;\n /**\n * Stores the list node from the {@code separatedDfsChildList} of the parent node this node\n * is stored in. This enable deleting of this node from the {@code separatedDfsChildList}\n * list in $\\mathcal{O}(1)$ time\n */\n DoublyLinkedList.ListNode listNode;\n /**\n * The list of the embedded edges incident to this node in a clockwise or a counterclockwise\n * order. The order is counterclockwise if the product of the signs of the parent edges\n * along the path from the root of the component this node is contained in to this node is\n * equal to $-1$. Otherwise, the order is clockwise.\n */\n DoublyLinkedList embedded;\n\n /**\n * Creates a new real node with the specified parameters.\n *\n * @param graphVertex the counterpart of this node in the {@code graph}\n * @param dfsIndex the dfs index of this node\n * @param height the height of this node in the dfs tree\n * @param initialComponentRoot the component root of this node.\n * @param parentEdge the parent edge of this node\n */\n Node(V graphVertex, int dfsIndex, int height, Node initialComponentRoot, Edge parentEdge)\n {\n this(graphVertex, dfsIndex, parentEdge, false);\n this.height = height;\n this.initialComponentRoot = initialComponentRoot;\n }\n\n /**\n * Creates a new component root. Dfs index of the component root is equal to dfs index of\n * its parent.\n *\n * @param dfsIndex the dfs index of this node\n * @param parentEdge the parent edge of this component root\n */\n Node(int dfsIndex, Edge parentEdge)\n {\n this(null, dfsIndex, parentEdge, true);\n }\n\n /**\n * Creates a new node with the specified parameters\n *\n * @param graphVertex the vertex in the {@code graph} corresponding to this node\n * @param dfsIndex the dfs index of this node\n * @param parentEdge the parent edge of this node\n * @param rootVertex whether this is real or virtual node\n */\n Node(V graphVertex, int dfsIndex, Edge parentEdge, boolean rootVertex)\n {\n this.graphVertex = graphVertex;\n this.dfsIndex = dfsIndex;\n this.parentEdge = parentEdge;\n this.rootVertex = rootVertex;\n this.outerFaceNeighbors = TypeUtil.uncheckedCast(Array.newInstance(Node.class, 2));\n this.embedded = new DoublyLinkedList<>();\n if (parentEdge != null) {\n embedded.add(parentEdge);\n }\n this.visited = this.backEdgeFlag = n;\n if (!rootVertex) {\n separatedDfsChildList = new DoublyLinkedList<>();\n pertinentRoots = new DoublyLinkedList<>();\n treeEdges = new ArrayList<>();\n downEdges = new ArrayList<>();\n backEdges = new ArrayList<>();\n }\n }\n\n /**\n * Checks whether this node is visited in the context of processing the node {@code node}\n *\n * @param node the node that is currently been processed\n * @return true if this node is visited, false otherwise\n */\n boolean isVisitedWrtTo(Node node)\n {\n return node.dfsIndex == visited;\n }\n\n /**\n * Checks whether this node is pertinent in the context of processing the node {@code node}.\n * During the processing of the node {@code node}, a node is pertinent if it has a back edge\n * to {@code node} or it has a child biconnected component, which has a pertinent node.\n *\n * @param node the node that is currently been processed\n * @return true if this node is pertinent, false otherwise\n */\n boolean isPertinentWrtTo(Node node)\n {\n return backEdgeFlag == node.dfsIndex || !pertinentRoots.isEmpty();\n }\n\n /**\n * Checks whether this node has a back edge to the {@code node}.\n *\n * @param node the other endpoint of the edge we're looking for\n * @return true if the edge between this node and {@code node} exists, false otherwise\n */\n boolean hasBackEdgeWrtTo(Node node)\n {\n return backEdgeFlag == node.dfsIndex;\n }\n\n /**\n * Checks whether this node is externally active with respect to the {@code node}. A node is\n * externally active, if it is incident to the edge ending higher than {@code node}, or it\n * has a child biconnected component with a pertinent node\n *\n * @param node an ancestor of this node\n * @return true if this node is externally active with respect to the {@code node}, false\n * otherwise\n */\n boolean isExternallyActiveWrtTo(Node node)\n {\n return leastAncestor < node.dfsIndex || (!separatedDfsChildList.isEmpty()\n && separatedDfsChildList.getFirst().lowpoint < node.dfsIndex);\n }\n\n /**\n * Returns true if the node is a component root, false otherwise\n *\n * @return true if the node is a component root, false otherwise\n */\n boolean isRootVertex()\n {\n return rootVertex;\n }\n\n /**\n * Check whether this node is internally active. A node is internally active if it's\n * pertinent and not externally active\n *\n * @param node an ancestor of this node\n * @return true if this node is internally active, false otherwise\n */\n boolean isInternallyActiveWrtTo(Node node)\n {\n return isPertinentWrtTo(node) && !isExternallyActiveWrtTo(node);\n }\n\n /**\n * Check whether this node is inactive. A node is inactive it is neither pertinent nor\n * externally active\n *\n * @param node an ancestor of this node\n * @return true if this node is inactive, false otherwise\n */\n boolean isInactiveWrtTo(Node node)\n {\n return !isExternallyActiveWrtTo(node) && !isPertinentWrtTo(node);\n }\n\n /**\n * Check whether this node is active. A node is active it is either pertinent or externally\n * active\n *\n * @param node an ancestor of this node\n * @return true if this node is active, false otherwise\n */\n boolean isActiveWrtTo(Node node)\n {\n return !isInactiveWrtTo(node);\n }\n\n /**\n * Returns a circulator, that moves in the direction {@code direction}. The next node along\n * the traversal will be {@code this.outerFaceNeighbor[direction]}.\n *\n * @param direction the direction to move in\n * @return an iterator over the boundary nodes in the direction {@code direction}\n */\n OuterFaceCirculator iterator(int direction)\n {\n return new OuterFaceCirculator(outerFaceNeighbors[direction], this);\n }\n\n void removeShortCircuitEdges()\n {\n embedded.removeIf(e -> e.shortCircuit);\n }\n\n /**\n * Returns the parent of this node in the dfs tree. Tree parent of the dfs root node is\n * {@code null}\n *\n * @return the parent of this node in the dfs tree\n */\n Node getParent()\n {\n return parentEdge == null ? null : parentEdge.source;\n }\n\n /**\n * Checks whether this node has a neighbor {@code node} on the boundary of the biconnected\n * component\n *\n * @param node a possible neighbor of this node\n */\n void checkIsAdjacent(Node node)\n {\n assert node == outerFaceNeighbors[0] || node == outerFaceNeighbors[1];\n }\n\n /**\n * Swaps the outer face neighbors of this node\n */\n void swapNeighbors()\n {\n Node t = outerFaceNeighbors[0];\n outerFaceNeighbors[0] = outerFaceNeighbors[1];\n outerFaceNeighbors[1] = t;\n }\n\n /**\n * Substitutes the neighbor {@code node} with a {@code newNeighbor}\n *\n * @param node an old neighbor\n * @param newNeighbor a new neighbor\n */\n void substitute(Node node, Node newNeighbor)\n {\n checkIsAdjacent(node);\n if (outerFaceNeighbors[0] == node) {\n outerFaceNeighbors[0] = newNeighbor;\n } else {\n outerFaceNeighbors[1] = newNeighbor;\n }\n }\n\n /**\n * Substitutes a neighbor of this node, which is not equal to the {@code node}, with the\n * {@code newNeighbor}\n *\n * @param node the remaining neighbor\n * @param newNeighbor a new neighbor\n */\n void substituteAnother(Node node, Node newNeighbor)\n {\n checkIsAdjacent(node);\n if (outerFaceNeighbors[0] == node) {\n outerFaceNeighbors[1] = newNeighbor;\n } else {\n outerFaceNeighbors[0] = newNeighbor;\n }\n }\n\n /**\n * Checks whether this node has a neighbor, which is a root of a biconnected component\n *\n * @return true, if this node has a root node neighbor, false otherwise\n */\n boolean hasRootNeighbor()\n {\n return outerFaceNeighbors[0].isRootVertex() || outerFaceNeighbors[1].isRootVertex();\n }\n\n /**\n * Returns a neighbor of this node which is not equal to the {@code prev}\n *\n * @param prev a neighbor of this node\n * @return a neightbor, which is not equal to the {@code prev}\n */\n Node nextOnOuterFace(Node prev)\n {\n checkIsAdjacent(prev);\n if (outerFaceNeighbors[0] == prev) {\n return outerFaceNeighbors[1];\n } else {\n return outerFaceNeighbors[0];\n }\n }\n\n /**\n * Adds {@code edge} to the list of the embedded edges such that the {@code prev} node\n * becomes an inner node.\n *\n * @param edge an edge to embed\n * @param prev the node which should be on the new inner face\n */\n void embedBackEdge(Edge edge, Node prev)\n {\n assert !embedded.isEmpty();\n if (prev.isRootVertex()) {\n prev = prev.getParent();\n }\n Edge firstEdge = embedded.getFirst();\n if (firstEdge.getOpposite(this) == prev) {\n // edge on the new inner face is at the beginning of the list\n embedded.addFirst(edge);\n } else {\n embedded.addLast(edge);\n }\n }\n\n /**\n * Merges the embedded edges of the child component root into this node's embedded edges.\n * Note, that the edges in the {@code edges} list are always in the clockwise order. There\n * are 3 parameters which determine how the {@code edges} list is merged: the {@code vIn}\n * direction, the {@code vOut} direction and the orientation of the edges around this node\n * (clockwise or counterclockwise). The edges in the {@code edges} list should have the same\n * orientation. If this list is inverted, the sign of the {@code parentEdge} is set to $-1$.\n *\n * @param edges the edges from the child component root\n * @param vIn the direction used to enter the parent component\n * @param vOut the direction used to enter the child component\n * @param parentNext the next node along the traversal of the parent biconnected component\n * @param parentEdge the parent edge if the child component\n */\n void mergeChildEdges(\n DoublyLinkedList edges, int vIn, int vOut, Node parentNext, Edge parentEdge)\n {\n assert !embedded.isEmpty();\n Node firstOpposite = embedded.getFirst().getOpposite(this);\n boolean alongParentTraversal = firstOpposite != parentNext;\n boolean actionAppend = false, invert = false;\n if (vIn == 0) {\n if (vOut == 0) {\n if (!alongParentTraversal) {\n invert = actionAppend = true;\n }\n } else {\n if (alongParentTraversal) {\n invert = true;\n } else {\n actionAppend = true;\n }\n }\n } else {\n if (vOut == 0) {\n if (!alongParentTraversal) {\n invert = actionAppend = true;\n }\n } else {\n if (alongParentTraversal) {\n invert = true;\n } else {\n actionAppend = true;\n }\n }\n }\n if (invert) {\n parentEdge.sign = -1;\n edges.invert();\n }\n if (actionAppend) {\n embedded.append(edges);\n } else {\n embedded.prepend(edges);\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString()\n {\n String neighbor1 =\n outerFaceNeighbors[0] == null ? \"null\" : outerFaceNeighbors[0].toString(false);\n String neighbor2 =\n outerFaceNeighbors[1] == null ? \"null\" : outerFaceNeighbors[1].toString(false);\n String childListString = \"null\";\n if (separatedDfsChildList != null) {\n StringBuilder builder = new StringBuilder(\"{\");\n separatedDfsChildList.forEach(n -> builder.append(n.toString(false)).append(\", \"));\n childListString = builder.append(\"}\").toString();\n }\n if (rootVertex) {\n return String\n .format(\n \"R {%s}: neighbors = [%s, %s], embedded = %s, visited = %d, back_edge_flag = %d, dfs_index = %d\",\n toString(false), neighbor1, neighbor2, embedded.toString(), visited,\n backEdgeFlag, dfsIndex);\n } else {\n return String\n .format(\n \"{%s}: neighbors = [%s, %s], embedded = %s, visited = %d, back_edge_flag = %d, dfs_index = %d, separated = %s, tree_edges = %s, down_edges = %s, back_edges = %s, parent = %s, lowpoint = %d, least_ancestor = %d\",\n toString(false), neighbor1, neighbor2, embedded.toString(), visited,\n backEdgeFlag, dfsIndex, childListString, treeEdges.toString(),\n downEdges.toString(), backEdges.toString(),\n parentEdge == null ? \"null\" : parentEdge.source.toString(false), lowpoint,\n leastAncestor);\n }\n }\n\n /**\n * Returns a full or a partial string representation of this node\n *\n * @param full whether to return full or partial string representation of this node\n * @return either full or partial string representation of this node\n */\n public String toString(boolean full)\n {\n if (!full) {\n if (rootVertex) {\n return String\n .format(\n \"%s^%s\", parentEdge.source.graphVertex.toString(),\n parentEdge.target.graphVertex.toString());\n } else {\n return graphVertex.toString();\n }\n } else {\n return toString();\n }\n }\n }\n}\n", "file_name": "BoyerMyrvoldPlanarityInspector.java", "human_label": "Return the edge connecting the previously returned node with the current node.", "level": "class_runnable", "lineno": "1727", "name": "edgeToNext", "oracle_context": "{ \"apis\" : \"[getFirst, toExistingNode, getOpposite, getLast, Edge, Node]\", \"classes\" : \"[Edge, Node, prev]\", \"vars\" : \"[embedded, prev, current]\" }", "package": "org.jgrapht.alg.planar", "project": "jgrapht-master" }, { "_id": "6367676b1a6d9265ec0181e9", "all_context": "{ \"class_level\" : \"import java.nio.charset.Charset;\\nimport java.util.ArrayList;\\nimport java.util.Arrays;\\nimport java.util.Collection;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.LinkedList;\\nimport java.util.List;\\nimport java.util.Locale;\\nimport java.util.Properties;\\nimport java.util.Set;\\nimport java.util.StringTokenizer;\\nimport java.util.TreeSet;\\nString FOLDER_SEPARATOR;\\nString WINDOWS_FOLDER_SEPARATOR;\\nString TOP_PATH;\\nString CURRENT_PATH;\\nchar EXTENSION_SEPARATOR;\\nCharset UTF_8;\\nStrings();\\nhasLength(String str);\\nhasText(CharSequence str);\\nhasText(String str);\\ncontainsWhitespace(CharSequence str);\\ncontainsWhitespace(String str);\\ntrimWhitespace(String str);\\ntrimWhitespace(CharSequence str);\\nclean(String str);\\nclean(CharSequence str);\\ntrimAllWhitespace(String str);\\ntrimLeadingWhitespace(String str);\\ntrimTrailingWhitespace(String str);\\ntrimLeadingCharacter(String str,char leadingCharacter);\\ntrimTrailingCharacter(String str,char trailingCharacter);\\nstartsWithIgnoreCase(String str,String prefix);\\nendsWithIgnoreCase(String str,String suffix);\\nsubstringMatch(CharSequence str,int index,CharSequence substring);\\ncountOccurrencesOf(String str,String sub);\\nreplace(String inString,String oldPattern,String newPattern);\\ndelete(String inString,String pattern);\\ndeleteAny(String inString,String charsToDelete);\\nquote(String str);\\nquoteIfString(Object obj);\\nunqualify(String qualifiedName);\\nunqualify(String qualifiedName,char separator);\\ncapitalize(String str);\\nuncapitalize(String str);\\nchangeFirstCharacterCase(String str,boolean capitalize);\\ngetFilename(String path);\\ngetFilenameExtension(String path);\\nstripFilenameExtension(String path);\\napplyRelativePath(String path,String relativePath);\\ncleanPath(String path);\\npathEquals(String path1,String path2);\\nparseLocaleString(String localeString);\\nvalidateLocalePart(String localePart);\\ntoLanguageTag(Locale locale);\\naddStringToArray(String[] array,String str);\\nconcatenateStringArrays(String[] array1,String[] array2);\\nmergeStringArrays(String[] array1,String[] array2);\\nsortStringArray(String[] array);\\ntoStringArray(Collection collection);\\ntoStringArray(Enumeration enumeration);\\ntrimArrayElements(String[] array);\\nremoveDuplicateStrings(String[] array);\\nsplit(String toSplit,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter);\\nsplitArrayElementsIntoProperties(String[] array,String delimiter,String charsToDelete);\\ntokenizeToStringArray(String str,String delimiters);\\ntokenizeToStringArray(String str,String delimiters,boolean trimTokens,boolean ignoreEmptyTokens);\\ndelimitedListToStringArray(String str,String delimiter);\\ndelimitedListToStringArray(String str,String delimiter,String charsToDelete);\\ncommaDelimitedListToStringArray(String str);\\ncommaDelimitedListToSet(String str);\\ncollectionToDelimitedString(Collection coll,String delim,String prefix,String suffix);\\ncollectionToDelimitedString(Collection coll,String delim);\\ncollectionToCommaDelimitedString(Collection coll);\\narrayToDelimitedString(Object[] arr,String delim);\\narrayToCommaDelimitedString(Object[] arr);\\nhasLength(CharSequence str);\\n\", \"repo_level\" : \"\" }", "class_name": "Strings", "code": "public static boolean substringMatch(CharSequence str,int index,CharSequence substring){\n for (int j=0; j < substring.length(); j++) {\n int i=index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n}\n", "docstring": "/** \n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n", "end_lineno": "350", "file_content": "/*\n * Copyright (C) 2014 jsonwebtoken.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.jsonwebtoken.lang;\n\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.TreeSet;\n\npublic final class Strings {\n\n private static final String FOLDER_SEPARATOR = \"/\";\n\n private static final String WINDOWS_FOLDER_SEPARATOR = \"\\\\\";\n\n private static final String TOP_PATH = \"..\";\n\n private static final String CURRENT_PATH = \".\";\n\n private static final char EXTENSION_SEPARATOR = '.';\n\n public static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\n private Strings(){} //prevent instantiation\n\n //---------------------------------------------------------------------\n // General convenience methods for working with Strings\n //---------------------------------------------------------------------\n\n /**\n * Check that the given CharSequence is neither null nor of length 0.\n * Note: Will return true for a CharSequence that purely consists of whitespace.\n *

          \n     * Strings.hasLength(null) = false\n     * Strings.hasLength(\"\") = false\n     * Strings.hasLength(\" \") = true\n     * Strings.hasLength(\"Hello\") = true\n     * 
          \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null and has length\n * @see #hasText(String)\n */\n public static boolean hasLength(CharSequence str) {\n return (str != null && str.length() > 0);\n }\n\n /**\n * Check that the given String is neither null nor of length 0.\n * Note: Will return true for a String that purely consists of whitespace.\n * @param str the String to check (may be null)\n * @return true if the String is not null and has length\n * @see #hasLength(CharSequence)\n */\n public static boolean hasLength(String str) {\n return hasLength((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n *
          \n     * Strings.hasText(null) = false\n     * Strings.hasText(\"\") = false\n     * Strings.hasText(\" \") = false\n     * Strings.hasText(\"12345\") = true\n     * Strings.hasText(\" 12345 \") = true\n     * 
          \n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not null,\n * its length is greater than 0, and it does not contain whitespace only\n * @see java.lang.Character#isWhitespace\n */\n public static boolean hasText(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String has actual text.\n * More specifically, returns true if the string not null,\n * its length is greater than 0, and it contains at least one non-whitespace character.\n * @param str the String to check (may be null)\n * @return true if the String is not null, its length is\n * greater than 0, and it does not contain whitespace only\n * @see #hasText(CharSequence)\n */\n public static boolean hasText(String str) {\n return hasText((CharSequence) str);\n }\n\n /**\n * Check whether the given CharSequence contains any whitespace characters.\n * @param str the CharSequence to check (may be null)\n * @return true if the CharSequence is not empty and\n * contains at least 1 whitespace character\n * @see java.lang.Character#isWhitespace\n */\n public static boolean containsWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return false;\n }\n int strLen = str.length();\n for (int i = 0; i < strLen; i++) {\n if (Character.isWhitespace(str.charAt(i))) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Check whether the given String contains any whitespace characters.\n * @param str the String to check (may be null)\n * @return true if the String is not empty and\n * contains at least 1 whitespace character\n * @see #containsWhitespace(CharSequence)\n */\n public static boolean containsWhitespace(String str) {\n return containsWhitespace((CharSequence) str);\n }\n\n /**\n * Trim leading and trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimWhitespace(String str) {\n return (String) trimWhitespace((CharSequence)str);\n }\n \n \n private static CharSequence trimWhitespace(CharSequence str) {\n if (!hasLength(str)) {\n return str;\n }\n final int length = str.length();\n\n int start = 0;\n\t\twhile (start < length && Character.isWhitespace(str.charAt(start))) {\n start++;\n }\n \n\t\tint end = length;\n while (start < length && Character.isWhitespace(str.charAt(end - 1))) {\n end--;\n }\n \n return ((start > 0) || (end < length)) ? str.subSequence(start, end) : str;\n }\n\n public static String clean(String str) {\n \tCharSequence result = clean((CharSequence) str);\n \n return result!=null?result.toString():null;\n }\n \n public static CharSequence clean(CharSequence str) {\n str = trimWhitespace(str);\n if (!hasLength(str)) {\n return null;\n }\n return str;\n }\n\n /**\n * Trim all whitespace from the given String:\n * leading, trailing, and intermediate characters.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimAllWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n int index = 0;\n while (sb.length() > index) {\n if (Character.isWhitespace(sb.charAt(index))) {\n sb.deleteCharAt(index);\n }\n else {\n index++;\n }\n }\n return sb.toString();\n }\n\n /**\n * Trim leading whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimLeadingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim trailing whitespace from the given String.\n * @param str the String to check\n * @return the trimmed String\n * @see java.lang.Character#isWhitespace\n */\n public static String trimTrailingWhitespace(String str) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied leading character from the given String.\n * @param str the String to check\n * @param leadingCharacter the leading character to be trimmed\n * @return the trimmed String\n */\n public static String trimLeadingCharacter(String str, char leadingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n }\n\n /**\n * Trim all occurrences of the supplied trailing character from the given String.\n * @param str the String to check\n * @param trailingCharacter the trailing character to be trimmed\n * @return the trimmed String\n */\n public static String trimTrailingCharacter(String str, char trailingCharacter) {\n if (!hasLength(str)) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str);\n while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {\n sb.deleteCharAt(sb.length() - 1);\n }\n return sb.toString();\n }\n\n\n /**\n * Returns {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @param str the String to check\n * @param prefix the prefix to look for\n * @return {@code true} if the given string starts with the specified case-insensitive prefix, {@code false} otherwise.\n * @see java.lang.String#startsWith\n */\n public static boolean startsWithIgnoreCase(String str, String prefix) {\n if (str == null || prefix == null) {\n return false;\n }\n if (str.startsWith(prefix)) {\n return true;\n }\n if (str.length() < prefix.length()) {\n return false;\n }\n String lcStr = str.substring(0, prefix.length()).toLowerCase();\n String lcPrefix = prefix.toLowerCase();\n return lcStr.equals(lcPrefix);\n }\n\n /**\n * Returns {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @param str the String to check\n * @param suffix the suffix to look for\n * @return {@code true} if the given string ends with the specified case-insensitive suffix, {@code false} otherwise.\n * @see java.lang.String#endsWith\n */\n public static boolean endsWithIgnoreCase(String str, String suffix) {\n if (str == null || suffix == null) {\n return false;\n }\n if (str.endsWith(suffix)) {\n return true;\n }\n if (str.length() < suffix.length()) {\n return false;\n }\n\n String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();\n String lcSuffix = suffix.toLowerCase();\n return lcStr.equals(lcSuffix);\n }\n\n /**\n * Returns {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n * @param str the original string (or StringBuilder)\n * @param index the index in the original string to start matching against\n * @param substring the substring to match at the given index\n * @return {@code true} if the given string matches the given substring at the given index, {@code false} otherwise.\n */\n public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {\n for (int j = 0; j < substring.length(); j++) {\n int i = index + j;\n if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Returns the number of occurrences the substring {@code sub} appears in string {@code str}.\n * @param str string to search in. Return 0 if this is null.\n * @param sub string to search for. Return 0 if this is null.\n * @return the number of occurrences the substring {@code sub} appears in string {@code str}.\n */\n public static int countOccurrencesOf(String str, String sub) {\n if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {\n return 0;\n }\n int count = 0;\n int pos = 0;\n int idx;\n while ((idx = str.indexOf(sub, pos)) != -1) {\n ++count;\n pos = idx + sub.length();\n }\n return count;\n }\n\n /**\n * Replace all occurrences of a substring within a string with\n * another string.\n * @param inString String to examine\n * @param oldPattern String to replace\n * @param newPattern String to insert\n * @return a String with the replacements\n */\n public static String replace(String inString, String oldPattern, String newPattern) {\n if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n int pos = 0; // our position in the old string\n int index = inString.indexOf(oldPattern);\n // the index of an occurrence we've found, or -1\n int patLen = oldPattern.length();\n while (index >= 0) {\n sb.append(inString.substring(pos, index));\n sb.append(newPattern);\n pos = index + patLen;\n index = inString.indexOf(oldPattern, pos);\n }\n sb.append(inString.substring(pos));\n // remember to append any characters to the right of a match\n return sb.toString();\n }\n\n /**\n * Delete all occurrences of the given substring.\n * @param inString the original String\n * @param pattern the pattern to delete all occurrences of\n * @return the resulting String\n */\n public static String delete(String inString, String pattern) {\n return replace(inString, pattern, \"\");\n }\n\n /**\n * Delete any character in a given String.\n * @param inString the original String\n * @param charsToDelete a set of characters to delete.\n * E.g. \"az\\n\" will delete 'a's, 'z's and new lines.\n * @return the resulting String\n */\n public static String deleteAny(String inString, String charsToDelete) {\n if (!hasLength(inString) || !hasLength(charsToDelete)) {\n return inString;\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < inString.length(); i++) {\n char c = inString.charAt(i);\n if (charsToDelete.indexOf(c) == -1) {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with formatted Strings\n //---------------------------------------------------------------------\n\n /**\n * Quote the given String with single quotes.\n * @param str the input String (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or null if the input was null\n */\n public static String quote(String str) {\n return (str != null ? \"'\" + str + \"'\" : null);\n }\n\n /**\n * Turn the given Object into a String with single quotes\n * if it is a String; keeping the Object as-is else.\n * @param obj the input Object (e.g. \"myString\")\n * @return the quoted String (e.g. \"'myString'\"),\n * or the input object as-is if not a String\n */\n public static Object quoteIfString(Object obj) {\n return (obj instanceof String ? quote((String) obj) : obj);\n }\n\n /**\n * Unqualify a string qualified by a '.' dot character. For example,\n * \"this.name.is.qualified\", returns \"qualified\".\n * @param qualifiedName the qualified name\n * @return an unqualified string by stripping all previous text before (and including) the last period character.\n */\n public static String unqualify(String qualifiedName) {\n return unqualify(qualifiedName, '.');\n }\n\n /**\n * Unqualify a string qualified by a separator character. For example,\n * \"this:name:is:qualified\" returns \"qualified\" if using a ':' separator.\n * @param qualifiedName the qualified name\n * @param separator the separator\n * @return an unqualified string by stripping all previous text before and including the last {@code separator} character.\n */\n public static String unqualify(String qualifiedName, char separator) {\n return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);\n }\n\n /**\n * Capitalize a String, changing the first letter to\n * upper case as per {@link Character#toUpperCase(char)}.\n * No other letters are changed.\n * @param str the String to capitalize, may be null\n * @return the capitalized String, null if null\n */\n public static String capitalize(String str) {\n return changeFirstCharacterCase(str, true);\n }\n\n /**\n * Uncapitalize a String, changing the first letter to\n * lower case as per {@link Character#toLowerCase(char)}.\n * No other letters are changed.\n * @param str the String to uncapitalize, may be null\n * @return the uncapitalized String, null if null\n */\n public static String uncapitalize(String str) {\n return changeFirstCharacterCase(str, false);\n }\n\n private static String changeFirstCharacterCase(String str, boolean capitalize) {\n if (str == null || str.length() == 0) {\n return str;\n }\n StringBuilder sb = new StringBuilder(str.length());\n if (capitalize) {\n sb.append(Character.toUpperCase(str.charAt(0)));\n }\n else {\n sb.append(Character.toLowerCase(str.charAt(0)));\n }\n sb.append(str.substring(1));\n return sb.toString();\n }\n\n /**\n * Extract the filename from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"myfile.txt\".\n * @param path the file path (may be null)\n * @return the extracted filename, or null if none\n */\n public static String getFilename(String path) {\n if (path == null) {\n return null;\n }\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);\n }\n\n /**\n * Extract the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"txt\".\n * @param path the file path (may be null)\n * @return the extracted filename extension, or null if none\n */\n public static String getFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return null;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return null;\n }\n return path.substring(extIndex + 1);\n }\n\n /**\n * Strip the filename extension from the given path,\n * e.g. \"mypath/myfile.txt\" -> \"mypath/myfile\".\n * @param path the file path (may be null)\n * @return the path with stripped filename extension,\n * or null if none\n */\n public static String stripFilenameExtension(String path) {\n if (path == null) {\n return null;\n }\n int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);\n if (extIndex == -1) {\n return path;\n }\n int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (folderIndex > extIndex) {\n return path;\n }\n return path.substring(0, extIndex);\n }\n\n /**\n * Apply the given relative path to the given path,\n * assuming standard Java folder separation (i.e. \"/\" separators).\n * @param path the path to start from (usually a full file path)\n * @param relativePath the relative path to apply\n * (relative to the full file path above)\n * @return the full file path that results from applying the relative path\n */\n public static String applyRelativePath(String path, String relativePath) {\n int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);\n if (separatorIndex != -1) {\n String newPath = path.substring(0, separatorIndex);\n if (!relativePath.startsWith(FOLDER_SEPARATOR)) {\n newPath += FOLDER_SEPARATOR;\n }\n return newPath + relativePath;\n }\n else {\n return relativePath;\n }\n }\n\n /**\n * Normalize the path by suppressing sequences like \"path/..\" and\n * inner simple dots.\n *

          The result is convenient for path comparison. For other uses,\n * notice that Windows separators (\"\\\") are replaced by simple slashes.\n * @param path the original path\n * @return the normalized path\n */\n public static String cleanPath(String path) {\n if (path == null) {\n return null;\n }\n String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);\n\n // Strip prefix from path to analyze, to not treat it as part of the\n // first path element. This is necessary to correctly parse paths like\n // \"file:core/../core/io/Resource.class\", where the \"..\" should just\n // strip the first \"core\" directory while keeping the \"file:\" prefix.\n int prefixIndex = pathToUse.indexOf(\":\");\n String prefix = \"\";\n if (prefixIndex != -1) {\n prefix = pathToUse.substring(0, prefixIndex + 1);\n pathToUse = pathToUse.substring(prefixIndex + 1);\n }\n if (pathToUse.startsWith(FOLDER_SEPARATOR)) {\n prefix = prefix + FOLDER_SEPARATOR;\n pathToUse = pathToUse.substring(1);\n }\n\n String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);\n List pathElements = new LinkedList();\n int tops = 0;\n\n for (int i = pathArray.length - 1; i >= 0; i--) {\n String element = pathArray[i];\n if (CURRENT_PATH.equals(element)) {\n // Points to current directory - drop it.\n }\n else if (TOP_PATH.equals(element)) {\n // Registering top path found.\n tops++;\n }\n else {\n if (tops > 0) {\n // Merging path element with element corresponding to top path.\n tops--;\n }\n else {\n // Normal path element found.\n pathElements.add(0, element);\n }\n }\n }\n\n // Remaining top paths need to be retained.\n for (int i = 0; i < tops; i++) {\n pathElements.add(0, TOP_PATH);\n }\n\n return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);\n }\n\n /**\n * Compare two paths after normalization of them.\n * @param path1 first path for comparison\n * @param path2 second path for comparison\n * @return whether the two paths are equivalent after normalization\n */\n public static boolean pathEquals(String path1, String path2) {\n return cleanPath(path1).equals(cleanPath(path2));\n }\n\n /**\n * Parse the given localeString value into a {@link java.util.Locale}.\n *

          This is the inverse operation of {@link java.util.Locale#toString Locale's toString}.\n * @param localeString the locale string, following Locale's\n * toString() format (\"en\", \"en_UK\", etc);\n * also accepts spaces as separators, as an alternative to underscores\n * @return a corresponding Locale instance\n */\n public static Locale parseLocaleString(String localeString) {\n String[] parts = tokenizeToStringArray(localeString, \"_ \", false, false);\n String language = (parts.length > 0 ? parts[0] : \"\");\n String country = (parts.length > 1 ? parts[1] : \"\");\n validateLocalePart(language);\n validateLocalePart(country);\n String variant = \"\";\n if (parts.length >= 2) {\n // There is definitely a variant, and it is everything after the country\n // code sans the separator between the country code and the variant.\n int endIndexOfCountryCode = localeString.indexOf(country) + country.length();\n // Strip off any leading '_' and whitespace, what's left is the variant.\n variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));\n if (variant.startsWith(\"_\")) {\n variant = trimLeadingCharacter(variant, '_');\n }\n }\n return (language.length() > 0 ? new Locale(language, country, variant) : null);\n }\n\n private static void validateLocalePart(String localePart) {\n for (int i = 0; i < localePart.length(); i++) {\n char ch = localePart.charAt(i);\n if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {\n throw new IllegalArgumentException(\n \"Locale part \\\"\" + localePart + \"\\\" contains invalid characters\");\n }\n }\n }\n\n /**\n * Determine the RFC 3066 compliant language tag,\n * as used for the HTTP \"Accept-Language\" header.\n * @param locale the Locale to transform to a language tag\n * @return the RFC 3066 compliant language tag as String\n */\n public static String toLanguageTag(Locale locale) {\n return locale.getLanguage() + (hasText(locale.getCountry()) ? \"-\" + locale.getCountry() : \"\");\n }\n\n\n //---------------------------------------------------------------------\n // Convenience methods for working with String arrays\n //---------------------------------------------------------------------\n\n /**\n * Append the given String to the given String array, returning a new array\n * consisting of the input array contents plus the given String.\n * @param array the array to append to (can be null)\n * @param str the String to append\n * @return the new array (never null)\n */\n public static String[] addStringToArray(String[] array, String str) {\n if (Objects.isEmpty(array)) {\n return new String[] {str};\n }\n String[] newArr = new String[array.length + 1];\n System.arraycopy(array, 0, newArr, 0, array.length);\n newArr[array.length] = str;\n return newArr;\n }\n\n /**\n * Concatenate the given String arrays into one,\n * with overlapping array elements included twice.\n *

          The order of elements in the original arrays is preserved.\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] concatenateStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n String[] newArr = new String[array1.length + array2.length];\n System.arraycopy(array1, 0, newArr, 0, array1.length);\n System.arraycopy(array2, 0, newArr, array1.length, array2.length);\n return newArr;\n }\n\n /**\n * Merge the given String arrays into one, with overlapping\n * array elements only included once.\n *

          The order of elements in the original arrays is preserved\n * (with the exception of overlapping elements, which are only\n * included on their first occurrence).\n * @param array1 the first array (can be null)\n * @param array2 the second array (can be null)\n * @return the new array (null if both given arrays were null)\n */\n public static String[] mergeStringArrays(String[] array1, String[] array2) {\n if (Objects.isEmpty(array1)) {\n return array2;\n }\n if (Objects.isEmpty(array2)) {\n return array1;\n }\n List result = new ArrayList();\n result.addAll(Arrays.asList(array1));\n for (String str : array2) {\n if (!result.contains(str)) {\n result.add(str);\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Turn given source String array into sorted array.\n * @param array the source array\n * @return the sorted array (never null)\n */\n public static String[] sortStringArray(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n Arrays.sort(array);\n return array;\n }\n\n /**\n * Copy the given Collection into a String array.\n * The Collection must contain String elements only.\n * @param collection the Collection to copy\n * @return the String array (null if the passed-in\n * Collection was null)\n */\n public static String[] toStringArray(Collection collection) {\n if (collection == null) {\n return null;\n }\n return collection.toArray(new String[collection.size()]);\n }\n\n /**\n * Copy the given Enumeration into a String array.\n * The Enumeration must contain String elements only.\n * @param enumeration the Enumeration to copy\n * @return the String array (null if the passed-in\n * Enumeration was null)\n */\n public static String[] toStringArray(Enumeration enumeration) {\n if (enumeration == null) {\n return null;\n }\n List list = java.util.Collections.list(enumeration);\n return list.toArray(new String[list.size()]);\n }\n\n /**\n * Trim the elements of the given String array,\n * calling String.trim() on each of them.\n * @param array the original String array\n * @return the resulting array (of the same size) with trimmed elements\n */\n public static String[] trimArrayElements(String[] array) {\n if (Objects.isEmpty(array)) {\n return new String[0];\n }\n String[] result = new String[array.length];\n for (int i = 0; i < array.length; i++) {\n String element = array[i];\n result[i] = (element != null ? element.trim() : null);\n }\n return result;\n }\n\n /**\n * Remove duplicate Strings from the given array.\n * Also sorts the array, as it uses a TreeSet.\n * @param array the String array\n * @return an array without duplicates, in natural sort order\n */\n public static String[] removeDuplicateStrings(String[] array) {\n if (Objects.isEmpty(array)) {\n return array;\n }\n Set set = new TreeSet();\n for (String element : array) {\n set.add(element);\n }\n return toStringArray(set);\n }\n\n /**\n * Split a String at the first occurrence of the delimiter.\n * Does not include the delimiter in the result.\n * @param toSplit the string to split\n * @param delimiter to split the string up with\n * @return a two element array with index 0 being before the delimiter, and\n * index 1 being after the delimiter (neither element includes the delimiter);\n * or null if the delimiter wasn't found in the given input String\n */\n public static String[] split(String toSplit, String delimiter) {\n if (!hasLength(toSplit) || !hasLength(delimiter)) {\n return null;\n }\n int offset = toSplit.indexOf(delimiter);\n if (offset < 0) {\n return null;\n }\n String beforeDelimiter = toSplit.substring(0, offset);\n String afterDelimiter = toSplit.substring(offset + delimiter.length());\n return new String[] {beforeDelimiter, afterDelimiter};\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

          Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {\n return splitArrayElementsIntoProperties(array, delimiter, null);\n }\n\n /**\n * Take an array Strings and split each element based on the given delimiter.\n * A Properties instance is then generated, with the left of the\n * delimiter providing the key, and the right of the delimiter providing the value.\n *

          Will trim both the key and value before adding them to the\n * Properties instance.\n * @param array the array to process\n * @param delimiter to split each element using (typically the equals symbol)\n * @param charsToDelete one or more characters to remove from each element\n * prior to attempting the split operation (typically the quotation mark\n * symbol), or null if no removal should occur\n * @return a Properties instance representing the array contents,\n * or null if the array to process was null or empty\n */\n public static Properties splitArrayElementsIntoProperties(\n String[] array, String delimiter, String charsToDelete) {\n\n if (Objects.isEmpty(array)) {\n return null;\n }\n Properties result = new Properties();\n for (String element : array) {\n if (charsToDelete != null) {\n element = deleteAny(element, charsToDelete);\n }\n String[] splittedElement = split(element, delimiter);\n if (splittedElement == null) {\n continue;\n }\n result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());\n }\n return result;\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n * Trims tokens and omits empty tokens.\n *

          The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter).\n * @return an array of the tokens\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(String str, String delimiters) {\n return tokenizeToStringArray(str, delimiters, true, true);\n }\n\n /**\n * Tokenize the given String into a String array via a StringTokenizer.\n *

          The given delimiters string is supposed to consist of any number of\n * delimiter characters. Each of those characters can be used to separate\n * tokens. A delimiter is always a single character; for multi-character\n * delimiters, consider using delimitedListToStringArray\n * @param str the String to tokenize\n * @param delimiters the delimiter characters, assembled as String\n * (each of those characters is individually considered as delimiter)\n * @param trimTokens trim the tokens via String's trim\n * @param ignoreEmptyTokens omit empty tokens from the result array\n * (only applies to tokens that are empty after trimming; StringTokenizer\n * will not consider subsequent delimiters as token in the first place).\n * @return an array of the tokens (null if the input String\n * was null)\n * @see java.util.StringTokenizer\n * @see java.lang.String#trim()\n * @see #delimitedListToStringArray\n */\n public static String[] tokenizeToStringArray(\n String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {\n\n if (str == null) {\n return null;\n }\n StringTokenizer st = new StringTokenizer(str, delimiters);\n List tokens = new ArrayList();\n while (st.hasMoreTokens()) {\n String token = st.nextToken();\n if (trimTokens) {\n token = token.trim();\n }\n if (!ignoreEmptyTokens || token.length() > 0) {\n tokens.add(token);\n }\n }\n return toStringArray(tokens);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

          A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter) {\n return delimitedListToStringArray(str, delimiter, null);\n }\n\n /**\n * Take a String which is a delimited list and convert it to a String array.\n *

          A single delimiter can consists of more than one character: It will still\n * be considered as single delimiter string, rather than as bunch of potential\n * delimiter characters - in contrast to tokenizeToStringArray.\n * @param str the input String\n * @param delimiter the delimiter between elements (this is a single delimiter,\n * rather than a bunch individual delimiter characters)\n * @param charsToDelete a set of characters to delete. Useful for deleting unwanted\n * line breaks: e.g. \"\\r\\n\\f\" will delete all new lines and line feeds in a String.\n * @return an array of the tokens in the list\n * @see #tokenizeToStringArray\n */\n public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {\n if (str == null) {\n return new String[0];\n }\n if (delimiter == null) {\n return new String[] {str};\n }\n List result = new ArrayList();\n if (\"\".equals(delimiter)) {\n for (int i = 0; i < str.length(); i++) {\n result.add(deleteAny(str.substring(i, i + 1), charsToDelete));\n }\n }\n else {\n int pos = 0;\n int delPos;\n while ((delPos = str.indexOf(delimiter, pos)) != -1) {\n result.add(deleteAny(str.substring(pos, delPos), charsToDelete));\n pos = delPos + delimiter.length();\n }\n if (str.length() > 0 && pos <= str.length()) {\n // Add rest of String, but not in case of empty input.\n result.add(deleteAny(str.substring(pos), charsToDelete));\n }\n }\n return toStringArray(result);\n }\n\n /**\n * Convert a CSV list into an array of Strings.\n * @param str the input String\n * @return an array of Strings, or the empty array in case of empty input\n */\n public static String[] commaDelimitedListToStringArray(String str) {\n return delimitedListToStringArray(str, \",\");\n }\n\n /**\n * Convenience method to convert a CSV string list to a set.\n * Note that this will suppress duplicates.\n * @param str the input String\n * @return a Set of String entries in the list\n */\n public static Set commaDelimitedListToSet(String str) {\n Set set = new TreeSet();\n String[] tokens = commaDelimitedListToStringArray(str);\n for (String token : tokens) {\n set.add(token);\n }\n return set;\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @param prefix the String to start each element with\n * @param suffix the String to end each element with\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) {\n if (Collections.isEmpty(coll)) {\n return \"\";\n }\n StringBuilder sb = new StringBuilder();\n Iterator it = coll.iterator();\n while (it.hasNext()) {\n sb.append(prefix).append(it.next()).append(suffix);\n if (it.hasNext()) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a Collection as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String collectionToDelimitedString(Collection coll, String delim) {\n return collectionToDelimitedString(coll, delim, \"\", \"\");\n }\n\n /**\n * Convenience method to return a Collection as a CSV String.\n * E.g. useful for toString() implementations.\n * @param coll the Collection to display\n * @return the delimited String\n */\n public static String collectionToCommaDelimitedString(Collection coll) {\n return collectionToDelimitedString(coll, \",\");\n }\n\n /**\n * Convenience method to return a String array as a delimited (e.g. CSV)\n * String. E.g. useful for toString() implementations.\n * @param arr the array to display\n * @param delim the delimiter to use (probably a \",\")\n * @return the delimited String\n */\n public static String arrayToDelimitedString(Object[] arr, String delim) {\n if (Objects.isEmpty(arr)) {\n return \"\";\n }\n if (arr.length == 1) {\n return Objects.nullSafeToString(arr[0]);\n }\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < arr.length; i++) {\n if (i > 0) {\n sb.append(delim);\n }\n sb.append(arr[i]);\n }\n return sb.toString();\n }\n\n /**\n * Convenience method to return a String array as a CSV String.\n * E.g. useful for toString() implementations.\n * @param arr the array to display\n * @return the delimited String\n */\n public static String arrayToCommaDelimitedString(Object[] arr) {\n return arrayToDelimitedString(arr, \",\");\n }\n\n}\n\n", "file_name": "Strings.java", "human_label": "Return true if starting at the given index,the given string matches the given substring.Otherwise return false.", "level": "slib_runnable", "lineno": "335", "name": "substringMatch", "oracle_context": "{ \"apis\" : \"[length, charAt]\", \"classes\" : \"[]\", \"vars\" : \"[]\" }", "package": "io.jsonwebtoken.lang", "project": "jjwt-master" }, { "_id": "636767781a6d9265ec01823e", "all_context": "{ \"class_level\" : \"import org.apache.log4j.AppenderSkeleton;\\nimport org.apache.log4j.helpers.LogLog;\\nimport org.apache.log4j.spi.LoggingEvent;\\nimport java.io.IOException;\\nimport java.io.PrintWriter;\\nimport java.io.InterruptedIOException;\\nimport java.net.ServerSocket;\\nimport java.net.Socket;\\nimport java.util.Enumeration;\\nimport java.util.Iterator;\\nimport java.util.Vector;\\nSocketHandler sh;\\nint port;\\nVector writers;\\nVector connections;\\nServerSocket serverSocket;\\nint MAX_CONNECTIONS;\\nactivateOptions();\\ngetPort();\\nsetPort(int port);\\nclose();\\nappend(LoggingEvent event);\\nfinalize();\\nsend(String message);\\nrun();\\nSocketHandler(int port);\\nrequiresLayout();\\n\", \"repo_level\" : \"public interface AppenderSkeleton {public void activateOptions();\\npublic void addFilter(Filter newFilter);\\nprotected void append(LoggingEvent event);\\npublic void clearFilters();\\npublic void finalize();\\npublic ErrorHandler getErrorHandler();\\npublic Filter getFilter();\\nfinal Filter getFirstFilter();\\npublic Layout getLayout();\\nfinal String getName();\\npublic Priority getThreshold();\\npublic boolean isAsSevereAsThreshold(Priority priority);\\nsynchronized void doAppend(LoggingEvent event);\\nsynchronized void setErrorHandler(ErrorHandler eh);\\npublic void setLayout(Layout layout);\\npublic void setName(String name);\\npublic void setThreshold(Priority threshold);\\n }\\npublic interface LogLog {public void setInternalDebugging(boolean enabled);\\nstatic void debug(String msg);\\nstatic void debug(String msg,Throwable t);\\nstatic void error(String msg);\\nstatic void error(String msg,Throwable t);\\nstatic void setQuietMode(boolean quietMode);\\nstatic void warn(String msg);\\nstatic void warn(String msg,Throwable t);\\n }\\npublic interface LoggingEvent {public LocationInfo getLocationInformation();\\npublic Level getLevel();\\npublic String getLoggerName();\\npublic Category getLogger();\\npublic Object getMessage();\\npublic String getNDC();\\npublic Object getMDC(String key);\\npublic void getMDCCopy();\\npublic String getRenderedMessage();\\nstatic long getStartTime();\\npublic String getThreadName();\\npublic ThrowableInformation getThrowableInformation();\\npublic String[] getThrowableStrRep();\\nfinal void setProperty(String propName,String propValue);\\nfinal String getProperty(String key);\\nfinal boolean locationInformationExists();\\nfinal long getTimeStamp();\\npublic Set getPropertyKeySet();\\npublic Map getProperties();\\npublic String getFQNOfLoggerClass();\\npublic Object removeProperty(String propName);\\n }\\n\" }", "class_name": "TelnetAppender", "code": "protected void append(LoggingEvent event){\n if (sh != null) {\n sh.send(layout.format(event));\n if (layout.ignoresThrowable()) {\n String[] s=event.getThrowableStrRep();\n if (s != null) {\n StringBuffer buf=new StringBuffer();\n for (int i=0; i < s.length; i++) {\n buf.append(s[i]);\n buf.append(\"\\r\\n\");\n }\n sh.send(buf.toString());\n }\n }\n }\n}\n", "docstring": "/** \n * Handles a log event. For this appender, that means writing the message to each connected client. \n */\n", "end_lineno": "131", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.apache.log4j.net;\n\nimport org.apache.log4j.AppenderSkeleton;\nimport org.apache.log4j.helpers.LogLog;\nimport org.apache.log4j.spi.LoggingEvent;\n\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.io.InterruptedIOException;\nimport java.net.ServerSocket;\nimport java.net.Socket;\nimport java.util.Enumeration;\nimport java.util.Iterator;\nimport java.util.Vector;\n\n/**\n

          The TelnetAppender is a log4j appender that specializes in\n writing to a read-only socket. The output is provided in a\n telnet-friendly way so that a log can be monitored over TCP/IP.\n Clients using telnet connect to the socket and receive log data.\n This is handy for remote monitoring, especially when monitoring a\n servlet.\n\n

          Here is a list of the available configuration options:\n\n \n \n \n \n \n \n \n\n \n \n \n \n \n
          NameRequirementDescriptionSample Value
          PortoptionalThis parameter determines the port to use for announcing log events. The default port is 23 (telnet).5875
          \n\n @author Jay Funnell\n*/\n\npublic class TelnetAppender extends AppenderSkeleton {\n\n private SocketHandler sh;\n private int port = 23;\n\n /** \n This appender requires a layout to format the text to the\n attached client(s). */\n public boolean requiresLayout() {\n return true;\n }\n\n /** all of the options have been set, create the socket handler and\n wait for connections. */\n public void activateOptions() {\n try {\n sh = new SocketHandler(port);\n sh.start();\n }\n catch(InterruptedIOException e) {\n Thread.currentThread().interrupt();\n e.printStackTrace();\n } catch(IOException e) {\n e.printStackTrace();\n } catch(RuntimeException e) {\n e.printStackTrace();\n }\n super.activateOptions();\n }\n\n public\n int getPort() {\n return port;\n }\n\n public\n void setPort(int port) {\n this.port = port;\n }\n\n\n /** shuts down the appender. */\n public void close() {\n if (sh != null) {\n sh.close();\n try {\n sh.join();\n } catch(InterruptedException ex) {\n Thread.currentThread().interrupt();\n }\n }\n }\n\n /** Handles a log event. For this appender, that means writing the\n message to each connected client. */\n protected void append(LoggingEvent event) {\n if(sh != null) {\n sh.send(layout.format(event));\n if(layout.ignoresThrowable()) {\n String[] s = event.getThrowableStrRep();\n if (s != null) {\n StringBuffer buf = new StringBuffer();\n for(int i = 0; i < s.length; i++) {\n buf.append(s[i]);\n buf.append(\"\\r\\n\");\n }\n sh.send(buf.toString());\n }\n }\n }\n }\n\n //---------------------------------------------------------- SocketHandler:\n\n /** The SocketHandler class is used to accept connections from\n clients. It is threaded so that clients can connect/disconnect\n asynchronously. */\n protected class SocketHandler extends Thread {\n\n private Vector writers = new Vector();\n private Vector connections = new Vector();\n private ServerSocket serverSocket;\n private int MAX_CONNECTIONS = 20;\n\n public void finalize() {\n close();\n }\n \n /** \n * make sure we close all network connections when this handler is destroyed.\n * @since 1.2.15 \n */\n public void close() {\n synchronized(this) {\n for(Enumeration e = connections.elements();e.hasMoreElements();) {\n try {\n ((Socket)e.nextElement()).close();\n } catch(InterruptedIOException ex) {\n Thread.currentThread().interrupt();\n } catch(IOException ex) {\n } catch(RuntimeException ex) {\n }\n }\n }\n\n try {\n serverSocket.close();\n } catch(InterruptedIOException ex) {\n Thread.currentThread().interrupt();\n } catch(IOException ex) {\n } catch(RuntimeException ex) {\n }\n }\n\n /** sends a message to each of the clients in telnet-friendly output. */\n public synchronized void send(final String message) {\n Iterator ce = connections.iterator();\n for(Iterator e = writers.iterator();e.hasNext();) {\n ce.next();\n PrintWriter writer = (PrintWriter)e.next();\n writer.print(message);\n if(writer.checkError()) {\n ce.remove();\n e.remove();\n }\n }\n }\n\n /** \n\tContinually accepts client connections. Client connections\n are refused when MAX_CONNECTIONS is reached. \n */\n public void run() {\n while(!serverSocket.isClosed()) {\n try {\n Socket newClient = serverSocket.accept();\n PrintWriter pw = new PrintWriter(newClient.getOutputStream());\n if(connections.size() < MAX_CONNECTIONS) {\n synchronized(this) {\n connections.addElement(newClient);\n writers.addElement(pw);\n pw.print(\"TelnetAppender v1.0 (\" + connections.size()\n\t\t + \" active connections)\\r\\n\\r\\n\");\n pw.flush();\n }\n } else {\n pw.print(\"Too many connections.\\r\\n\");\n pw.flush();\n newClient.close();\n }\n } catch(Exception e) {\n if (e instanceof InterruptedIOException || e instanceof InterruptedException) {\n Thread.currentThread().interrupt();\n }\n if (!serverSocket.isClosed()) {\n LogLog.error(\"Encountered error while in SocketHandler loop.\", e);\n }\n break;\n }\n }\n\n try {\n serverSocket.close();\n } catch(InterruptedIOException ex) {\n Thread.currentThread().interrupt();\n } catch(IOException ex) {\n }\n }\n\n public SocketHandler(int port) throws IOException {\n serverSocket = new ServerSocket(port);\n setName(\"TelnetAppender-\" + getName() + \"-\" + port);\n }\n\n }\n}\n", "file_name": "TelnetAppender.java", "human_label": "Haddling a logging event by using layout.format(),and if layout.ignoresThrowable() is true,it will continue to send the StrRep of the event.", "level": "project_runnable", "lineno": "114", "name": "append", "oracle_context": "{ \"apis\" : \"[send, format, ignoresThrowable, getThrowableStrRep, toString]\", \"classes\" : \"[String[], StringBuffer]\", \"vars\" : \"[length, sh]\" }", "package": "org.apache.log4j.net", "project": "logging-log4j1-main" }, { "_id": "6367670b1a6d9265ec017a05", "all_context": "{ \"class_level\" : \"String CHAR_STRING;\\nString[] CHAR_STRING_ARRAY;\\nCharacter[] CHAR_ARRAY;\\nchar LF;\\nchar CR;\\nCharUtils();\\ntoCharacterObject(String str);\\ntoChar(Character ch);\\ntoChar(Character ch,char defaultValue);\\ntoChar(String str);\\ntoChar(String str,char defaultValue);\\ntoIntValue(char ch);\\ntoIntValue(char ch,int defaultValue);\\ntoIntValue(Character ch);\\ntoIntValue(Character ch,int defaultValue);\\ntoString(char ch);\\ntoString(Character ch);\\nunicodeEscaped(char ch);\\nunicodeEscaped(Character ch);\\nisAscii(char ch);\\nisAsciiPrintable(char ch);\\nisAsciiControl(char ch);\\nisAsciiAlpha(char ch);\\nisAsciiAlphaUpper(char ch);\\nisAsciiAlphaLower(char ch);\\nisAsciiNumeric(char ch);\\nisAsciiAlphanumeric(char ch);\\nisHighSurrogate(char ch);\\nisCharType(Class targetType);\\ntoCharacterObject(char ch);\\n\", \"repo_level\" : \"\" }", "class_name": "CharUtils", "code": "public static String toString(final char ch){\n if (ch < 128) {\n return CharUtils.CHAR_STRING_ARRAY[ch];\n }\n return new String(new char[]{ch});\n}\n", "docstring": "/** \n *

          Converts the character to a String that contains the one character.

          For ASCII 7 bit characters, this uses a cache that will return the same String object each time.

           CharUtils.toString(' ')  = \" \" CharUtils.toString('A')  = \"A\" 
          \n * @param ch the character to convert\n * @return a String containing the one specified character\n */\n", "end_lineno": "329", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage net.hasor.utils;\n/**\n *

          Operations on char primitives and Character objects.

          \n *\n *

          This class tries to handle null input gracefully.\n * An exception will not be thrown for a null input.\n * Each method documents its behaviour in more detail.

          \n *\n *

          #ThreadSafe#

          \n * @author Apache Software Foundation\n * @since 2.1\n * @version $Id: CharUtils.java 1056988 2011-01-09 17:58:53Z niallp $\n */\npublic class CharUtils {\n private static final String CHAR_STRING = //\n \"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\" +//\n \"\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\" + //\n \"\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\" + //\n \"\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\" +//\n \"\\u0020\\u0021\\\"\\u0023\\u0024\\u0025\\u0026\\u0027\" + //\n \"\\u0028\\u0029\\u002a\\u002b\\u002c\\u002d\\u002e\\u002f\" + //\n \"\\u0030\\u0031\\u0032\\u0033\\u0034\\u0035\\u0036\\u0037\" + //\n \"\\u0038\\u0039\\u003a\\u003b\\u003c\\u003d\\u003e\\u003f\" + //\n \"\\u0040\\u0041\\u0042\\u0043\\u0044\\u0045\\u0046\\u0047\" + //\n \"\\u0048\\u0049\\u004a\\u004b\\u004c\\u004d\\u004e\\u004f\" + //\n \"\\u0050\\u0051\\u0052\\u0053\\u0054\\u0055\\u0056\\u0057\" +//\n \"\\u0058\\u0059\\u005a\\u005b\\\\\\u005d\\u005e\\u005f\" + //\n \"\\u0060\\u0061\\u0062\\u0063\\u0064\\u0065\\u0066\\u0067\" +//\n \"\\u0068\\u0069\\u006a\\u006b\\u006c\\u006d\\u006e\\u006f\" +//\n \"\\u0070\\u0071\\u0072\\u0073\\u0074\\u0075\\u0076\\u0077\" +//\n \"\\u0078\\u0079\\u007a\\u007b\\u007c\\u007d\\u007e\\u007f\";\n private static final String[] CHAR_STRING_ARRAY = new String[128];\n private static final Character[] CHAR_ARRAY = new Character[128];\n /**\n * \n linefeed LF ('\\n').\n *\n * @see JLF: Escape Sequences\n * for Character and String Literals\n * @since 2.2\n */\n public static final char LF = '\\n';\n /**\n * carriage return CR ('\\r').\n *\n * @see JLF: Escape Sequences\n * for Character and String Literals\n * @since 2.2\n */\n public static final char CR = '\\r';\n\n static {\n for (int i = 127; i >= 0; i--) {\n CharUtils.CHAR_STRING_ARRAY[i] = CharUtils.CHAR_STRING.substring(i, i + 1);\n CharUtils.CHAR_ARRAY[i] = new Character((char) i);\n }\n }\n\n /**\n *

          CharUtils instances should NOT be constructed in standard programming.\n * Instead, the class should be used as CharUtils.toString('c');.

          \n *\n *

          This constructor i public to permit tools that require a JavaBean instance\n * to operate.

          \n */\n public CharUtils() {\n super();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Converts the character to a Character.

          \n *\n *

          For ASCII 7 bit characters, this uses a cache that will return the\n * same Character object each time.

          \n *\n *
          \n     *   CharUtils.toCharacterObject(' ')  = ' '\n     *   CharUtils.toCharacterObject('A')  = 'A'\n     * 
          \n *\n * @param ch the character to convert\n * @return a Character of the specified character\n */\n public static Character toCharacterObject(final char ch) {\n if (ch < CharUtils.CHAR_ARRAY.length) {\n return CharUtils.CHAR_ARRAY[ch];\n }\n return new Character(ch);\n }\n\n /**\n *

          Converts the String to a Character using the first character, returning\n * null for empty Strings.

          \n *\n *

          For ASCII 7 bit characters, this uses a cache that will return the\n * same Character object each time.

          \n *\n *
          \n     *   CharUtils.toCharacterObject(null) = null\n     *   CharUtils.toCharacterObject(\"\")   = null\n     *   CharUtils.toCharacterObject(\"A\")  = 'A'\n     *   CharUtils.toCharacterObject(\"BA\") = 'B'\n     * 
          \n *\n * @param str the character to convert\n * @return the Character value of the first letter of the String\n */\n public static Character toCharacterObject(final String str) {\n if (StringUtils.isEmpty(str)) {\n return null;\n }\n return CharUtils.toCharacterObject(str.charAt(0));\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Converts the Character to a char throwing an exception for null.

          \n *\n *
          \n     *   CharUtils.toChar(null) = IllegalArgumentException\n     *   CharUtils.toChar(' ')  = ' '\n     *   CharUtils.toChar('A')  = 'A'\n     * 
          \n *\n * @param ch the character to convert\n * @return the char value of the Character\n * @throws IllegalArgumentException if the Character is null\n */\n public static char toChar(final Character ch) {\n if (ch == null) {\n throw new IllegalArgumentException(\"The Character must not be null\");\n }\n return ch.charValue();\n }\n\n /**\n *

          Converts the Character to a char handling null.

          \n *\n *
          \n     *   CharUtils.toChar(null, 'X') = 'X'\n     *   CharUtils.toChar(' ', 'X')  = ' '\n     *   CharUtils.toChar('A', 'X')  = 'A'\n     * 
          \n *\n * @param ch the character to convert\n * @param defaultValue the value to use if the Character is null\n * @return the char value of the Character or the default if null\n */\n public static char toChar(final Character ch, final char defaultValue) {\n if (ch == null) {\n return defaultValue;\n }\n return ch.charValue();\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Converts the String to a char using the first character, throwing\n * an exception on empty Strings.

          \n *\n *
          \n     *   CharUtils.toChar(null) = IllegalArgumentException\n     *   CharUtils.toChar(\"\")   = IllegalArgumentException\n     *   CharUtils.toChar(\"A\")  = 'A'\n     *   CharUtils.toChar(\"BA\") = 'B'\n     * 
          \n *\n * @param str the character to convert\n * @return the char value of the first letter of the String\n * @throws IllegalArgumentException if the String is empty\n */\n public static char toChar(final String str) {\n if (StringUtils.isEmpty(str)) {\n throw new IllegalArgumentException(\"The String must not be empty\");\n }\n return str.charAt(0);\n }\n\n /**\n *

          Converts the String to a char using the first character, defaulting\n * the value on empty Strings.

          \n *\n *
          \n     *   CharUtils.toChar(null, 'X') = 'X'\n     *   CharUtils.toChar(\"\", 'X')   = 'X'\n     *   CharUtils.toChar(\"A\", 'X')  = 'A'\n     *   CharUtils.toChar(\"BA\", 'X') = 'B'\n     * 
          \n *\n * @param str the character to convert\n * @param defaultValue the value to use if the Character is null\n * @return the char value of the first letter of the String or the default if null\n */\n public static char toChar(final String str, final char defaultValue) {\n if (StringUtils.isEmpty(str)) {\n return defaultValue;\n }\n return str.charAt(0);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

          \n *\n *

          This method coverts the char '1' to the int 1 and so on.

          \n *\n *
          \n     *   CharUtils.toIntValue('3')  = 3\n     *   CharUtils.toIntValue('A')  = IllegalArgumentException\n     * 
          \n *\n * @param ch the character to convert\n * @return the int value of the character\n * @throws IllegalArgumentException if the character is not ASCII numeric\n */\n public static int toIntValue(final char ch) {\n if (CharUtils.isAsciiNumeric(ch) == false) {\n throw new IllegalArgumentException(\"The character \" + ch + \" is not in the range '0' - '9'\");\n }\n return ch - 48;\n }\n\n /**\n *

          Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

          \n *\n *

          This method coverts the char '1' to the int 1 and so on.

          \n *\n *
          \n     *   CharUtils.toIntValue('3', -1)  = 3\n     *   CharUtils.toIntValue('A', -1)  = -1\n     * 
          \n *\n * @param ch the character to convert\n * @param defaultValue the default value to use if the character is not numeric\n * @return the int value of the character\n */\n public static int toIntValue(final char ch, final int defaultValue) {\n if (CharUtils.isAsciiNumeric(ch) == false) {\n return defaultValue;\n }\n return ch - 48;\n }\n\n /**\n *

          Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

          \n *\n *

          This method coverts the char '1' to the int 1 and so on.

          \n *\n *
          \n     *   CharUtils.toIntValue(null) = IllegalArgumentException\n     *   CharUtils.toIntValue('3')  = 3\n     *   CharUtils.toIntValue('A')  = IllegalArgumentException\n     * 
          \n *\n * @param ch the character to convert, not null\n * @return the int value of the character\n * @throws IllegalArgumentException if the Character is not ASCII numeric or is null\n */\n public static int toIntValue(final Character ch) {\n if (ch == null) {\n throw new IllegalArgumentException(\"The character must not be null\");\n }\n return CharUtils.toIntValue(ch.charValue());\n }\n\n /**\n *

          Converts the character to the Integer it represents, throwing an\n * exception if the character is not numeric.

          \n *\n *

          This method coverts the char '1' to the int 1 and so on.

          \n *\n *
          \n     *   CharUtils.toIntValue(null, -1) = -1\n     *   CharUtils.toIntValue('3', -1)  = 3\n     *   CharUtils.toIntValue('A', -1)  = -1\n     * 
          \n *\n * @param ch the character to convert\n * @param defaultValue the default value to use if the character is not numeric\n * @return the int value of the character\n */\n public static int toIntValue(final Character ch, final int defaultValue) {\n if (ch == null) {\n return defaultValue;\n }\n return CharUtils.toIntValue(ch.charValue(), defaultValue);\n }\n //-----------------------------------------------------------------------\n\n /**\n *

          Converts the character to a String that contains the one character.

          \n *\n *

          For ASCII 7 bit characters, this uses a cache that will return the\n * same String object each time.

          \n *\n *
          \n     *   CharUtils.toString(' ')  = \" \"\n     *   CharUtils.toString('A')  = \"A\"\n     * 
          \n *\n * @param ch the character to convert\n * @return a String containing the one specified character\n */\n public static String toString(final char ch) {\n if (ch < 128) {\n return CharUtils.CHAR_STRING_ARRAY[ch];\n }\n return new String(new char[] { ch });\n }\n\n /**\n *

          Converts the character to a String that contains the one character.

          \n *\n *

          For ASCII 7 bit characters, this uses a cache that will return the\n * same String object each time.

          \n *\n *

          If null is passed in, null will be returned.

          \n *\n *
          \n     *   CharUtils.toString(null) = null\n     *   CharUtils.toString(' ')  = \" \"\n     *   CharUtils.toString('A')  = \"A\"\n     * 
          \n *\n * @param ch the character to convert\n * @return a String containing the one specified character\n */\n public static String toString(final Character ch) {\n if (ch == null) {\n return null;\n }\n return CharUtils.toString(ch.charValue());\n }\n //--------------------------------------------------------------------------\n\n /**\n *

          Converts the string to the unicode format '\\u0020'.

          \n *\n *

          This format is the Java source code format.

          \n *\n *
          \n     *   CharUtils.unicodeEscaped(' ') = \"\\u0020\"\n     *   CharUtils.unicodeEscaped('A') = \"\\u0041\"\n     * 
          \n *\n * @param ch the character to convert\n * @return the escaped unicode string\n */\n public static String unicodeEscaped(final char ch) {\n if (ch < 0x10) {\n return \"\\\\u000\" + Integer.toHexString(ch);\n } else if (ch < 0x100) {\n return \"\\\\u00\" + Integer.toHexString(ch);\n } else if (ch < 0x1000) {\n return \"\\\\u0\" + Integer.toHexString(ch);\n }\n return \"\\\\u\" + Integer.toHexString(ch);\n }\n\n /**\n *

          Converts the string to the unicode format '\\u0020'.

          \n *\n *

          This format is the Java source code format.

          \n *\n *

          If null is passed in, null will be returned.

          \n *\n *
          \n     *   CharUtils.unicodeEscaped(null) = null\n     *   CharUtils.unicodeEscaped(' ')  = \"\\u0020\"\n     *   CharUtils.unicodeEscaped('A')  = \"\\u0041\"\n     * 
          \n *\n * @param ch the character to convert, may be null\n * @return the escaped unicode string, null if null input\n */\n public static String unicodeEscaped(final Character ch) {\n if (ch == null) {\n return null;\n }\n return CharUtils.unicodeEscaped(ch.charValue());\n }\n //--------------------------------------------------------------------------\n\n /**\n *

          Checks whether the character is ASCII 7 bit.

          \n *\n *
          \n     *   CharUtils.isAscii('a')  = true\n     *   CharUtils.isAscii('A')  = true\n     *   CharUtils.isAscii('3')  = true\n     *   CharUtils.isAscii('-')  = true\n     *   CharUtils.isAscii('\\n') = true\n     *   CharUtils.isAscii('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if less than 128\n */\n public static boolean isAscii(final char ch) {\n return ch < 128;\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit printable.

          \n *\n *
          \n     *   CharUtils.isAsciiPrintable('a')  = true\n     *   CharUtils.isAsciiPrintable('A')  = true\n     *   CharUtils.isAsciiPrintable('3')  = true\n     *   CharUtils.isAsciiPrintable('-')  = true\n     *   CharUtils.isAsciiPrintable('\\n') = false\n     *   CharUtils.isAsciiPrintable('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if between 32 and 126 inclusive\n */\n public static boolean isAsciiPrintable(final char ch) {\n return ch >= 32 && ch < 127;\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit control.

          \n *\n *
          \n     *   CharUtils.isAsciiControl('a')  = false\n     *   CharUtils.isAsciiControl('A')  = false\n     *   CharUtils.isAsciiControl('3')  = false\n     *   CharUtils.isAsciiControl('-')  = false\n     *   CharUtils.isAsciiControl('\\n') = true\n     *   CharUtils.isAsciiControl('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if less than 32 or equals 127\n */\n public static boolean isAsciiControl(final char ch) {\n return ch < 32 || ch == 127;\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit alphabetic.

          \n *\n *
          \n     *   CharUtils.isAsciiAlpha('a')  = true\n     *   CharUtils.isAsciiAlpha('A')  = true\n     *   CharUtils.isAsciiAlpha('3')  = false\n     *   CharUtils.isAsciiAlpha('-')  = false\n     *   CharUtils.isAsciiAlpha('\\n') = false\n     *   CharUtils.isAsciiAlpha('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if between 65 and 90 or 97 and 122 inclusive\n */\n public static boolean isAsciiAlpha(final char ch) {\n return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z';\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit alphabetic upper case.

          \n *\n *
          \n     *   CharUtils.isAsciiAlphaUpper('a')  = false\n     *   CharUtils.isAsciiAlphaUpper('A')  = true\n     *   CharUtils.isAsciiAlphaUpper('3')  = false\n     *   CharUtils.isAsciiAlphaUpper('-')  = false\n     *   CharUtils.isAsciiAlphaUpper('\\n') = false\n     *   CharUtils.isAsciiAlphaUpper('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if between 65 and 90 inclusive\n */\n public static boolean isAsciiAlphaUpper(final char ch) {\n return ch >= 'A' && ch <= 'Z';\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit alphabetic lower case.

          \n *\n *
          \n     *   CharUtils.isAsciiAlphaLower('a')  = true\n     *   CharUtils.isAsciiAlphaLower('A')  = false\n     *   CharUtils.isAsciiAlphaLower('3')  = false\n     *   CharUtils.isAsciiAlphaLower('-')  = false\n     *   CharUtils.isAsciiAlphaLower('\\n') = false\n     *   CharUtils.isAsciiAlphaLower('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if between 97 and 122 inclusive\n */\n public static boolean isAsciiAlphaLower(final char ch) {\n return ch >= 'a' && ch <= 'z';\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit numeric.

          \n *\n *
          \n     *   CharUtils.isAsciiNumeric('a')  = false\n     *   CharUtils.isAsciiNumeric('A')  = false\n     *   CharUtils.isAsciiNumeric('3')  = true\n     *   CharUtils.isAsciiNumeric('-')  = false\n     *   CharUtils.isAsciiNumeric('\\n') = false\n     *   CharUtils.isAsciiNumeric('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if between 48 and 57 inclusive\n */\n public static boolean isAsciiNumeric(final char ch) {\n return ch >= '0' && ch <= '9';\n }\n\n /**\n *

          Checks whether the character is ASCII 7 bit numeric.

          \n *\n *
          \n     *   CharUtils.isAsciiAlphanumeric('a')  = true\n     *   CharUtils.isAsciiAlphanumeric('A')  = true\n     *   CharUtils.isAsciiAlphanumeric('3')  = true\n     *   CharUtils.isAsciiAlphanumeric('-')  = false\n     *   CharUtils.isAsciiAlphanumeric('\\n') = false\n     *   CharUtils.isAsciiAlphanumeric('©') = false\n     * 
          \n *\n * @param ch the character to check\n * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive\n */\n public static boolean isAsciiAlphanumeric(final char ch) {\n return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9';\n }\n // ----------------- Following code copied from Apache Harmony (Character class)\n\n /**\n * Indicates whether {@code ch} is a high- (or leading-) surrogate code unit\n * that is used for representing supplementary characters in UTF-16\n * encoding.\n *\n * @param ch\n * the character to test.\n * @return {@code true} if {@code ch} is a high-surrogate code unit;\n * {@code false} otherwise.\n */\n static boolean isHighSurrogate(final char ch) {\n return '\\uD800' <= ch && '\\uDBFF' >= ch;\n }\n\n //\n public static boolean isCharType(Class targetType) {\n return targetType.equals(Character.class) || targetType.equals(Character.TYPE);\n }\n}\n", "file_name": "CharUtils.java", "human_label": "Return the String object that contains the given character.", "level": "class_runnable", "lineno": "310", "name": "toString", "oracle_context": "{ \"apis\" : \"[CharUtils]\", \"classes\" : \"[CharUtils]\", \"vars\" : \"[CHAR_STRING_ARRAY]\" }", "package": "net.hasor.utils", "project": "hasor-master" }, { "_id": "636767a31a6d9265ec01854f", "all_context": "{ \"class_level\" : \"import java.io.DataInput;\\nimport java.io.IOException;\\nimport java.io.InputStream;\\nimport java.nio.ByteBuffer;\\nimport java.util.ArrayList;\\nimport java.util.List;\\nimport io.protostuff.StringSerializer.STRING;\\nimport static io.protostuff.WireFormat.TAG_TYPE_BITS;\\nimport static io.protostuff.WireFormat.TAG_TYPE_MASK;\\nimport static io.protostuff.WireFormat.WIRETYPE_END_GROUP;\\nimport static io.protostuff.WireFormat.WIRETYPE_LENGTH_DELIMITED;\\nimport static io.protostuff.WireFormat.WIRETYPE_TAIL_DELIMITER;\\nbyte[] buffer;\\nint bufferSize;\\nint bufferSizeAfterLimit;\\nint bufferPos;\\nInputStream input;\\nint lastTag;\\nint packedLimit;\\nint totalBytesRetired;\\nint currentLimit;\\nboolean decodeNestedMessageAsGroup;\\nint sizeLimit;\\nint DEFAULT_SIZE_LIMIT;\\nint DEFAULT_BUFFER_SIZE;\\nnewInstance(byte[] buf);\\nnewInstance(byte[] buf,int off,int len);\\nreadTag();\\ncheckLastTagWas(int value);\\nskipField(int tag);\\nskipMessage();\\nreadDouble();\\nreadFloat();\\nreadUInt64();\\nreadInt64();\\nreadInt32();\\nreadFixed64();\\nreadFixed32();\\nreadBool();\\nreadString();\\nreadBytes(ByteBuffer bb);\\nmergeObject(T value,Schema schema);\\nmergeObjectEncodedAsGroup(T value,Schema schema);\\nreadBytes();\\nreadUInt32();\\nreadEnum();\\nreadSFixed32();\\nreadSFixed64();\\nreadSInt32();\\nreadSInt64();\\nreadRawVarint32();\\nreadRawVarint32(InputStream input);\\nreadRawVarint32(InputStream input,int firstByte);\\nreadRawVarint32(DataInput input,byte firstByte);\\nreadRawVarint64();\\nreadRawLittleEndian32();\\nreadRawLittleEndian64();\\ndecodeZigZag32(int n);\\ndecodeZigZag64(long n);\\nCodedInput(byte[] buffer,int off,int len,boolean decodeNestedMessageAsGroup);\\nCodedInput(InputStream input,boolean decodeNestedMessageAsGroup);\\nCodedInput(InputStream input,byte[] buffer,boolean decodeNestedMessageAsGroup);\\nCodedInput(InputStream input,byte[] buffer,int offset,int limit,boolean decodeNestedMessageAsGroup);\\nsetSizeLimit(int limit);\\nresetSizeCounter();\\nreset();\\npushLimit(int byteLimit);\\nrecomputeBufferSizeAfterLimit();\\npopLimit(int oldLimit);\\ngetBytesUntilLimit();\\nisCurrentFieldPacked();\\nisAtEnd();\\ngetTotalBytesRead();\\nrefillBuffer(boolean mustSucceed);\\nreadRawByte();\\nreadRawBytes(int size);\\nskipRawBytes(int size);\\nreadFieldNumber(Schema schema);\\ncheckIfPackedField();\\nreadByteArray();\\nhandleUnknownField(int fieldNumber,Schema schema);\\ntransferByteRangeTo(Output output,boolean utf8String,int fieldNumber,boolean repeated);\\ngetLastTag();\\nreadByteBuffer();\\nnewInstance(InputStream input);\\n\", \"repo_level\" : \"\" }", "class_name": "CodedInput", "code": "private void checkIfPackedField() throws IOException {\n if (packedLimit == 0 && WireFormat.getTagWireType(lastTag) == WIRETYPE_LENGTH_DELIMITED) {\n final int length=readRawVarint32();\n if (length < 0) throw ProtobufException.negativeSize();\n this.packedLimit=getTotalBytesRead() + length;\n }\n}\n", "docstring": "/** \n * Check if this field have been packed into a length-delimited field. If so, update internal state to reflect that packed fields are being read.\n * @throws IOException\n */\n", "end_lineno": "1229", "file_content": "//========================================================================\n//Copyright 2007-2009 David Yu dyuproject@gmail.com\n//------------------------------------------------------------------------\n//Licensed under the Apache License, Version 2.0 (the \"License\");\n//you may not use this file except in compliance with the License.\n//You may obtain a copy of the License at \n//http://www.apache.org/licenses/LICENSE-2.0\n//Unless required by applicable law or agreed to in writing, software\n//distributed under the License is distributed on an \"AS IS\" BASIS,\n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//See the License for the specific language governing permissions and\n//limitations under the License.\n//========================================================================\n\n// Protocol Buffers - Google's data interchange format\n// Copyright 2008 Google Inc. All rights reserved.\n// http://code.google.com/p/protobuf/\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\npackage io.protostuff;\n\nimport java.io.DataInput;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport io.protostuff.StringSerializer.STRING;\n\nimport static io.protostuff.WireFormat.TAG_TYPE_BITS;\nimport static io.protostuff.WireFormat.TAG_TYPE_MASK;\nimport static io.protostuff.WireFormat.WIRETYPE_END_GROUP;\nimport static io.protostuff.WireFormat.WIRETYPE_LENGTH_DELIMITED;\nimport static io.protostuff.WireFormat.WIRETYPE_TAIL_DELIMITER;\n\n/**\n * Reads and decodes protocol message fields.\n *

          \n * This class contains two kinds of methods: methods that read specific protocol message constructs and field types\n * (e.g. {@link #readTag()} and {@link #readInt32()}) and methods that read low-level values (e.g.\n * {@link #readRawVarint32()} and {@link #readRawBytes}). If you are reading encoded protocol messages, you should use\n * the former methods, but if you are reading some other format of your own design, use the latter.\n *\n * @author kenton@google.com Kenton Varda\n * @author David Yu\n */\npublic final class CodedInput implements Input\n{\n /**\n * Create a new CodedInput wrapping the given InputStream.\n */\n public static CodedInput newInstance(final InputStream input)\n {\n return new CodedInput(input, false);\n }\n\n /**\n * Create a new CodedInput wrapping the given byte array.\n */\n public static CodedInput newInstance(final byte[] buf)\n {\n return newInstance(buf, 0, buf.length);\n }\n\n /**\n * Create a new CodedInput wrapping the given byte array slice.\n */\n public static CodedInput newInstance(final byte[] buf, final int off,\n final int len)\n {\n return new CodedInput(buf, off, len, false);\n }\n\n // -----------------------------------------------------------------\n\n /**\n * Attempt to read a field tag, returning zero if we have reached EOF. Protocol message parsers use this to read\n * tags, since a protocol message may legally end wherever a tag occurs, and zero is not a valid tag number.\n */\n public int readTag() throws IOException\n {\n if (isAtEnd())\n {\n lastTag = 0;\n return 0;\n }\n\n final int tag = readRawVarint32();\n if (tag >>> TAG_TYPE_BITS == 0)\n {\n // If we actually read zero, that's not a valid tag.\n throw ProtobufException.invalidTag();\n }\n lastTag = tag;\n return tag;\n }\n\n /**\n * Verifies that the last call to readTag() returned the given tag value. This is used to verify that a nested group\n * ended with the correct end tag.\n *\n * @throws ProtobufException\n * {@code value} does not match the last tag.\n */\n public void checkLastTagWas(final int value)\n throws ProtobufException\n {\n if (lastTag != value)\n {\n throw ProtobufException.invalidEndTag();\n }\n }\n\n /**\n * Reads and discards a single field, given its tag value.\n *\n * @return {@code false} if the tag is an endgroup tag, in which case nothing is skipped. Otherwise, returns\n * {@code true}.\n */\n public boolean skipField(final int tag) throws IOException\n {\n switch (WireFormat.getTagWireType(tag))\n {\n case WireFormat.WIRETYPE_VARINT:\n readInt32();\n return true;\n case WireFormat.WIRETYPE_FIXED64:\n readRawLittleEndian64();\n return true;\n case WireFormat.WIRETYPE_LENGTH_DELIMITED:\n skipRawBytes(readRawVarint32());\n return true;\n case WireFormat.WIRETYPE_START_GROUP:\n skipMessage();\n checkLastTagWas(WireFormat.makeTag(WireFormat.getTagFieldNumber(tag),\n WireFormat.WIRETYPE_END_GROUP));\n return true;\n case WireFormat.WIRETYPE_END_GROUP:\n return false;\n case WireFormat.WIRETYPE_FIXED32:\n readRawLittleEndian32();\n return true;\n default:\n throw ProtobufException.invalidWireType();\n }\n }\n\n /**\n * Reads and discards an entire message. This will read either until EOF or until an endgroup tag, whichever comes\n * first.\n */\n public void skipMessage() throws IOException\n {\n while (true)\n {\n final int tag = readTag();\n if (tag == 0 || !skipField(tag))\n {\n return;\n }\n }\n }\n\n // -----------------------------------------------------------------\n\n /**\n * Read a {@code double} field value from the stream.\n */\n @Override\n public double readDouble() throws IOException\n {\n checkIfPackedField();\n return Double.longBitsToDouble(readRawLittleEndian64());\n }\n\n /**\n * Read a {@code float} field value from the stream.\n */\n @Override\n public float readFloat() throws IOException\n {\n checkIfPackedField();\n return Float.intBitsToFloat(readRawLittleEndian32());\n }\n\n /**\n * Read a {@code uint64} field value from the stream.\n */\n @Override\n public long readUInt64() throws IOException\n {\n checkIfPackedField();\n return readRawVarint64();\n }\n\n /**\n * Read an {@code int64} field value from the stream.\n */\n @Override\n public long readInt64() throws IOException\n {\n checkIfPackedField();\n return readRawVarint64();\n }\n\n /**\n * Read an {@code int32} field value from the stream.\n */\n @Override\n public int readInt32() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32();\n }\n\n /**\n * Read a {@code fixed64} field value from the stream.\n */\n @Override\n public long readFixed64() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian64();\n }\n\n /**\n * Read a {@code fixed32} field value from the stream.\n */\n @Override\n public int readFixed32() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian32();\n }\n\n /**\n * Read a {@code bool} field value from the stream.\n */\n @Override\n public boolean readBool() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32() != 0;\n }\n\n /**\n * Read a {@code string} field value from the stream.\n */\n @Override\n public String readString() throws IOException\n {\n final int size = readRawVarint32();\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer, so\n // just copy directly from it.\n final String result = STRING.deser(buffer, bufferPos, size);\n bufferPos += size;\n return result;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n return STRING.deser(readRawBytes(size));\n }\n }\n\n /**\n * Read a {@code string} field value from the stream into a ByteBuffer.\n */\n @Override\n public void readBytes(final ByteBuffer bb) throws IOException\n {\n final int size = readRawVarint32();\n\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer, so\n // just copy directly from it.\n bb.limit(size);\n bb.put(buffer, bufferPos, size);\n bufferPos += size;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n bb.put(readRawBytes(size));\n }\n }\n\n @Override\n public T mergeObject(T value, final Schema schema) throws IOException\n {\n if (decodeNestedMessageAsGroup)\n return mergeObjectEncodedAsGroup(value, schema);\n\n final int length = readRawVarint32();\n // if (recursionDepth >= recursionLimit) {\n // throw ProtobufException.recursionLimitExceeded();\n // }\n final int oldLimit = pushLimit(length);\n // ++recursionDepth;\n\n if (value == null)\n {\n value = schema.newMessage();\n }\n schema.mergeFrom(this, value);\n if (!schema.isInitialized(value))\n {\n throw new UninitializedMessageException(value, schema);\n }\n checkLastTagWas(0);\n // --recursionDepth;\n popLimit(oldLimit);\n return value;\n }\n\n /**\n * Reads a message field value from the stream (using the {@code group} encoding).\n */\n private T mergeObjectEncodedAsGroup(T value, final Schema schema) throws IOException\n {\n // if (recursionDepth >= recursionLimit) {\n // throw ProtobufException.recursionLimitExceeded();\n // }\n // ++recursionDepth;\n\n if (value == null)\n {\n value = schema.newMessage();\n }\n schema.mergeFrom(this, value);\n if (!schema.isInitialized(value))\n {\n throw new UninitializedMessageException(value, schema);\n }\n // handling is in #readFieldNumber\n checkLastTagWas(0);\n // --recursionDepth;\n return value;\n }\n\n /*\n * @ Reads a {@code group} field value from the stream and merges it into the given {@link UnknownFieldSet}.\n * \n * @deprecated UnknownFieldSet.Builder now implements MessageLite.Builder, so you can just call {@link #readGroup}.\n */\n /*\n * @Deprecated public void readUnknownGroup(final int fieldNumber, final MessageLite.Builder builder) throws\n * IOException { // We know that UnknownFieldSet will ignore any ExtensionRegistry so it // is safe to pass null\n * here. (We can't call // ExtensionRegistry.getEmptyRegistry() because that would make this // class depend on\n * ExtensionRegistry, which is not part of the lite // library.) readGroup(fieldNumber, builder, null); }\n */\n\n /**\n * Read a {@code bytes} field value from the stream.\n */\n @Override\n public ByteString readBytes() throws IOException\n {\n final int size = readRawVarint32();\n if (size == 0)\n {\n return ByteString.EMPTY;\n }\n\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer, so\n // just copy directly from it.\n final ByteString result = ByteString.copyFrom(buffer, bufferPos, size);\n bufferPos += size;\n return result;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n // return ByteString.copyFrom(readRawBytes(size));\n return ByteString.wrap(readRawBytes(size));\n }\n }\n\n /**\n * Read a {@code uint32} field value from the stream.\n */\n @Override\n public int readUInt32() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32();\n }\n\n /**\n * Read an enum field value from the stream. Caller is responsible for converting the numeric value to an actual\n * enum.\n */\n @Override\n public int readEnum() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32();\n }\n\n /**\n * Read an {@code sfixed32} field value from the stream.\n */\n @Override\n public int readSFixed32() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian32();\n }\n\n /**\n * Read an {@code sfixed64} field value from the stream.\n */\n @Override\n public long readSFixed64() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian64();\n }\n\n /**\n * Read an {@code sint32} field value from the stream.\n */\n @Override\n public int readSInt32() throws IOException\n {\n checkIfPackedField();\n return decodeZigZag32(readRawVarint32());\n }\n\n /**\n * Read an {@code sint64} field value from the stream.\n */\n @Override\n public long readSInt64() throws IOException\n {\n checkIfPackedField();\n return decodeZigZag64(readRawVarint64());\n }\n\n // =================================================================\n\n /**\n * Read a raw Varint from the stream. If larger than 32 bits, discard the upper bits.\n */\n public int readRawVarint32() throws IOException\n {\n byte tmp = readRawByte();\n if (tmp >= 0)\n {\n return tmp;\n }\n int result = tmp & 0x7f;\n if ((tmp = readRawByte()) >= 0)\n {\n result |= tmp << 7;\n }\n else\n {\n result |= (tmp & 0x7f) << 7;\n if ((tmp = readRawByte()) >= 0)\n {\n result |= tmp << 14;\n }\n else\n {\n result |= (tmp & 0x7f) << 14;\n if ((tmp = readRawByte()) >= 0)\n {\n result |= tmp << 21;\n }\n else\n {\n result |= (tmp & 0x7f) << 21;\n result |= (tmp = readRawByte()) << 28;\n if (tmp < 0)\n {\n // Discard upper 32 bits.\n for (int i = 0; i < 5; i++)\n {\n if (readRawByte() >= 0)\n {\n return result;\n }\n }\n throw ProtobufException.malformedVarint();\n }\n }\n }\n }\n return result;\n }\n\n /**\n * Reads a varint from the input one byte at a time, so that it does not read any bytes after the end of the varint.\n * If you simply wrapped the stream in a CodedInput and used {@link #readRawVarint32(InputStream)} then you would\n * probably end up reading past the end of the varint since CodedInput buffers its input.\n */\n static int readRawVarint32(final InputStream input) throws IOException\n {\n final int firstByte = input.read();\n if (firstByte == -1)\n {\n throw ProtobufException.truncatedMessage();\n }\n\n if ((firstByte & 0x80) == 0)\n {\n return firstByte;\n }\n return readRawVarint32(input, firstByte);\n }\n\n /**\n * Reads a varint from the input one byte at a time, so that it does not read any bytes after the end of the varint.\n * If you simply wrapped the stream in a CodedInput and used {@link #readRawVarint32(InputStream)} then you would\n * probably end up reading past the end of the varint since CodedInput buffers its input.\n */\n static int readRawVarint32(final InputStream input, final int firstByte) throws IOException\n {\n int result = firstByte & 0x7f;\n int offset = 7;\n for (; offset < 32; offset += 7)\n {\n final int b = input.read();\n if (b == -1)\n {\n throw ProtobufException.truncatedMessage();\n }\n result |= (b & 0x7f) << offset;\n if ((b & 0x80) == 0)\n {\n return result;\n }\n }\n // Keep reading up to 64 bits.\n for (; offset < 64; offset += 7)\n {\n final int b = input.read();\n if (b == -1)\n {\n throw ProtobufException.truncatedMessage();\n }\n if ((b & 0x80) == 0)\n {\n return result;\n }\n }\n throw ProtobufException.malformedVarint();\n }\n\n /**\n * Reads a varint from the input one byte at a time from a {@link DataInput}, so that it does not read any bytes\n * after the end of the varint.\n */\n static int readRawVarint32(final DataInput input, final byte firstByte) throws IOException\n {\n int result = firstByte & 0x7f;\n int offset = 7;\n for (; offset < 32; offset += 7)\n {\n final byte b = input.readByte();\n result |= (b & 0x7f) << offset;\n if ((b & 0x80) == 0)\n {\n return result;\n }\n }\n // Keep reading up to 64 bits.\n for (; offset < 64; offset += 7)\n {\n final byte b = input.readByte();\n if ((b & 0x80) == 0)\n {\n return result;\n }\n }\n throw ProtobufException.malformedVarint();\n }\n\n /**\n * Read a raw Varint from the stream.\n */\n public long readRawVarint64() throws IOException\n {\n int shift = 0;\n long result = 0;\n while (shift < 64)\n {\n final byte b = readRawByte();\n result |= (long) (b & 0x7F) << shift;\n if ((b & 0x80) == 0)\n {\n return result;\n }\n shift += 7;\n }\n throw ProtobufException.malformedVarint();\n }\n\n /**\n * Read a 32-bit little-endian integer from the stream.\n */\n public int readRawLittleEndian32() throws IOException\n {\n final byte b1 = readRawByte();\n final byte b2 = readRawByte();\n final byte b3 = readRawByte();\n final byte b4 = readRawByte();\n return (((int) b1 & 0xff)) |\n (((int) b2 & 0xff) << 8) |\n (((int) b3 & 0xff) << 16) |\n (((int) b4 & 0xff) << 24);\n }\n\n /**\n * Read a 64-bit little-endian integer from the stream.\n */\n public long readRawLittleEndian64() throws IOException\n {\n final byte b1 = readRawByte();\n final byte b2 = readRawByte();\n final byte b3 = readRawByte();\n final byte b4 = readRawByte();\n final byte b5 = readRawByte();\n final byte b6 = readRawByte();\n final byte b7 = readRawByte();\n final byte b8 = readRawByte();\n return (((long) b1 & 0xff)) |\n (((long) b2 & 0xff) << 8) |\n (((long) b3 & 0xff) << 16) |\n (((long) b4 & 0xff) << 24) |\n (((long) b5 & 0xff) << 32) |\n (((long) b6 & 0xff) << 40) |\n (((long) b7 & 0xff) << 48) |\n (((long) b8 & 0xff) << 56);\n }\n\n /**\n * Decode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers into values that can be efficiently encoded\n * with varint. (Otherwise, negative values must be sign-extended to 64 bits to be varint encoded, thus always\n * taking 10 bytes on the wire.)\n *\n * @param n\n * An unsigned 32-bit integer, stored in a signed int because Java has no explicit unsigned support.\n * @return A signed 32-bit integer.\n */\n public static int decodeZigZag32(final int n)\n {\n return (n >>> 1) ^ -(n & 1);\n }\n\n /**\n * Decode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers into values that can be efficiently encoded\n * with varint. (Otherwise, negative values must be sign-extended to 64 bits to be varint encoded, thus always\n * taking 10 bytes on the wire.)\n *\n * @param n\n * An unsigned 64-bit integer, stored in a signed int because Java has no explicit unsigned support.\n * @return A signed 64-bit integer.\n */\n public static long decodeZigZag64(final long n)\n {\n return (n >>> 1) ^ -(n & 1);\n }\n\n // -----------------------------------------------------------------\n\n private final byte[] buffer;\n private int bufferSize;\n private int bufferSizeAfterLimit;\n private int bufferPos;\n private final InputStream input;\n private int lastTag;\n private int packedLimit = 0;\n\n /**\n * The total number of bytes read before the current buffer. The total bytes read up to the current position can be\n * computed as {@code totalBytesRetired + bufferPos}. This value may be negative if reading started in the middle of\n * the current buffer (e.g. if the constructor that takes a byte array and an offset was used).\n */\n private int totalBytesRetired;\n\n /**\n * The absolute position of the end of the current message.\n */\n private int currentLimit = Integer.MAX_VALUE;\n\n // ** See setRecursionLimit() */\n // private int recursionDepth;\n // private int recursionLimit = DEFAULT_RECURSION_LIMIT;\n\n /**\n * If true, the nested messages are group-encoded\n */\n public final boolean decodeNestedMessageAsGroup;\n\n /**\n * See setSizeLimit()\n */\n private int sizeLimit = DEFAULT_SIZE_LIMIT;\n\n // static final int DEFAULT_RECURSION_LIMIT = 64;\n static final int DEFAULT_SIZE_LIMIT = 64 << 20; // 64MB\n static final int DEFAULT_BUFFER_SIZE = 4096;\n\n public CodedInput(final byte[] buffer, final int off, final int len,\n boolean decodeNestedMessageAsGroup)\n {\n this.buffer = buffer;\n bufferSize = off + len;\n bufferPos = off;\n totalBytesRetired = -off;\n input = null;\n this.decodeNestedMessageAsGroup = decodeNestedMessageAsGroup;\n }\n\n public CodedInput(final InputStream input, boolean decodeNestedMessageAsGroup)\n {\n this(input, new byte[DEFAULT_BUFFER_SIZE], 0, 0, decodeNestedMessageAsGroup);\n }\n\n public CodedInput(final InputStream input, byte[] buffer,\n boolean decodeNestedMessageAsGroup)\n {\n this(input, buffer, 0, 0, decodeNestedMessageAsGroup);\n }\n\n public CodedInput(final InputStream input, byte[] buffer, int offset, int limit,\n boolean decodeNestedMessageAsGroup)\n {\n this.buffer = buffer;\n bufferSize = limit;\n bufferPos = offset;\n totalBytesRetired = -offset;\n this.input = input;\n this.decodeNestedMessageAsGroup = decodeNestedMessageAsGroup;\n }\n\n /*\n * Set the maximum message recursion depth. In order to prevent malicious messages from causing stack overflows,\n * {@code CodedInput} limits how deeply messages may be nested. The default limit is 64.\n * \n * @return the old limit.\n * \n * public int setRecursionLimit(final int limit) { if (limit < 0) { throw new IllegalArgumentException(\n * \"Recursion limit cannot be negative: \" + limit); } final int oldLimit = recursionLimit; recursionLimit = limit;\n * return oldLimit; }\n */\n\n /**\n * Set the maximum message size. In order to prevent malicious messages from exhausting memory or causing integer\n * overflows, {@code CodedInput} limits how large a message may be. The default limit is 64MB. You should set this\n * limit as small as you can without harming your app's functionality. Note that size limits only apply when reading\n * from an {@code InputStream}, not when constructed around a raw byte array.\n *

          \n * If you want to read several messages from a single CodedInput, you could call {@link #resetSizeCounter()} after\n * each one to avoid hitting the size limit.\n *\n * @return the old limit.\n */\n public int setSizeLimit(final int limit)\n {\n if (limit < 0)\n {\n throw new IllegalArgumentException(\n \"Size limit cannot be negative: \" + limit);\n }\n final int oldLimit = sizeLimit;\n sizeLimit = limit;\n return oldLimit;\n }\n\n /**\n * Resets the current size counter to zero (see {@link #setSizeLimit(int)}). The field {@code totalBytesRetired}\n * will be negative if the initial position was not zero.\n */\n public void resetSizeCounter()\n {\n totalBytesRetired = -bufferPos;\n }\n\n /**\n * Resets the buffer position and limit to re-use this CodedInput object.\n */\n public void reset()\n {\n this.bufferSize = 0;\n this.bufferPos = 0;\n this.bufferSizeAfterLimit = 0;\n this.currentLimit = Integer.MAX_VALUE;\n this.lastTag = 0;\n this.packedLimit = 0;\n this.sizeLimit = DEFAULT_SIZE_LIMIT;\n resetSizeCounter();\n }\n\n /**\n * Note that {@code pushLimit()} does NOT affect how many bytes the {@code CodedInputStream} reads from an\n * underlying {@code InputStream} when refreshing its buffer. If you need to prevent reading past a certain point in\n * the underlying {@code InputStream} (e.g. because you expect it to contain more data after the end of the message\n * which you need to handle differently) then you must place a wrapper around your {@code InputStream} which limits\n * the amount of data that can be read from it.\n *\n * @return the old limit.\n */\n public int pushLimit(int byteLimit) throws ProtobufException\n {\n if (byteLimit < 0)\n {\n throw ProtobufException.negativeSize();\n }\n byteLimit += totalBytesRetired + bufferPos;\n final int oldLimit = currentLimit;\n if (byteLimit > oldLimit)\n {\n throw ProtobufException.truncatedMessage();\n }\n currentLimit = byteLimit;\n\n recomputeBufferSizeAfterLimit();\n\n return oldLimit;\n }\n\n private void recomputeBufferSizeAfterLimit()\n {\n bufferSize += bufferSizeAfterLimit;\n final int bufferEnd = totalBytesRetired + bufferSize;\n if (bufferEnd > currentLimit)\n {\n // Limit is in current buffer.\n bufferSizeAfterLimit = bufferEnd - currentLimit;\n bufferSize -= bufferSizeAfterLimit;\n }\n else\n {\n bufferSizeAfterLimit = 0;\n }\n }\n\n /**\n * Discards the current limit, returning to the previous limit.\n *\n * @param oldLimit\n * The old limit, as returned by {@code pushLimit}.\n */\n public void popLimit(final int oldLimit)\n {\n currentLimit = oldLimit;\n recomputeBufferSizeAfterLimit();\n }\n\n /**\n * Returns the number of bytes to be read before the current limit. If no limit is set, returns -1.\n */\n public int getBytesUntilLimit()\n {\n if (currentLimit == Integer.MAX_VALUE)\n {\n return -1;\n }\n\n final int currentAbsolutePosition = totalBytesRetired + bufferPos;\n return currentLimit - currentAbsolutePosition;\n }\n\n /**\n * Return true if currently reading packed field\n */\n public boolean isCurrentFieldPacked()\n {\n return packedLimit != 0 && packedLimit != getTotalBytesRead();\n }\n\n /**\n * Returns true if the stream has reached the end of the input. This is the case if either the end of the underlying\n * input source has been reached or if the stream has reached a limit created using {@link #pushLimit(int)}.\n */\n public boolean isAtEnd() throws IOException\n {\n return bufferPos == bufferSize && !refillBuffer(false);\n }\n\n /**\n * The total bytes read up to the current position. Calling {@link #resetSizeCounter()} resets this value to zero.\n */\n public int getTotalBytesRead()\n {\n return totalBytesRetired + bufferPos;\n }\n\n /**\n * Called with {@code this.buffer} is empty to read more bytes from the input. If {@code mustSucceed} is true,\n * refillBuffer() guarantees that either there will be at least one byte in the buffer when it returns or it will\n * throw an exception. If {@code mustSucceed} is false, refillBuffer() returns false if no more bytes were\n * available.\n */\n private boolean refillBuffer(final boolean mustSucceed) throws IOException\n {\n if (bufferPos < bufferSize)\n {\n throw new IllegalStateException(\n \"refillBuffer() called when buffer wasn't empty.\");\n }\n\n if (totalBytesRetired + bufferSize == currentLimit)\n {\n // Oops, we hit a limit.\n if (mustSucceed)\n {\n throw ProtobufException.truncatedMessage();\n }\n else\n {\n return false;\n }\n }\n\n totalBytesRetired += bufferSize;\n\n bufferPos = 0;\n bufferSize = (input == null) ? -1 : input.read(buffer);\n if (bufferSize == 0 || bufferSize < -1)\n {\n throw new IllegalStateException(\n \"InputStream#read(byte[]) returned invalid result: \" + bufferSize +\n \"\\nThe InputStream implementation is buggy.\");\n }\n if (bufferSize == -1)\n {\n bufferSize = 0;\n if (mustSucceed)\n {\n throw ProtobufException.truncatedMessage();\n }\n else\n {\n return false;\n }\n }\n else\n {\n recomputeBufferSizeAfterLimit();\n final int totalBytesRead =\n totalBytesRetired + bufferSize + bufferSizeAfterLimit;\n if (totalBytesRead > sizeLimit || totalBytesRead < 0)\n {\n throw ProtobufException.sizeLimitExceeded();\n }\n return true;\n }\n }\n\n /**\n * Read one byte from the input.\n *\n * @throws ProtobufException\n * The end of the stream or the current limit was reached.\n */\n public byte readRawByte() throws IOException\n {\n if (bufferPos == bufferSize)\n {\n refillBuffer(true);\n }\n return buffer[bufferPos++];\n }\n\n /**\n * Read a fixed size of bytes from the input.\n *\n * @throws ProtobufException\n * The end of the stream or the current limit was reached.\n */\n public byte[] readRawBytes(final int size) throws IOException\n {\n if (size < 0)\n {\n throw ProtobufException.negativeSize();\n }\n\n if (totalBytesRetired + bufferPos + size > currentLimit)\n {\n // Read to the end of the stream anyway.\n skipRawBytes(currentLimit - totalBytesRetired - bufferPos);\n // Then fail.\n throw ProtobufException.truncatedMessage();\n }\n\n if (size <= bufferSize - bufferPos)\n {\n // We have all the bytes we need already.\n final byte[] bytes = new byte[size];\n System.arraycopy(buffer, bufferPos, bytes, 0, size);\n bufferPos += size;\n return bytes;\n }\n else if (size < buffer.length)\n {\n // Reading more bytes than are in the buffer, but not an excessive number\n // of bytes. We can safely allocate the resulting array ahead of time.\n\n // First copy what we have.\n final byte[] bytes = new byte[size];\n int pos = bufferSize - bufferPos;\n System.arraycopy(buffer, bufferPos, bytes, 0, pos);\n bufferPos = bufferSize;\n\n // We want to use refillBuffer() and then copy from the buffer into our\n // byte array rather than reading directly into our byte array because\n // the input may be unbuffered.\n refillBuffer(true);\n\n while (size - pos > bufferSize)\n {\n System.arraycopy(buffer, 0, bytes, pos, bufferSize);\n pos += bufferSize;\n bufferPos = bufferSize;\n refillBuffer(true);\n }\n\n System.arraycopy(buffer, 0, bytes, pos, size - pos);\n bufferPos = size - pos;\n\n return bytes;\n }\n else\n {\n // The size is very large. For security reasons, we can't allocate the\n // entire byte array yet. The size comes directly from the input, so a\n // maliciously-crafted message could provide a bogus very large size in\n // order to trick the app into allocating a lot of memory. We avoid this\n // by allocating and reading only a small chunk at a time, so that the\n // malicious message must actually *be* extremely large to cause\n // problems. Meanwhile, we limit the allowed size of a message elsewhere.\n\n // Remember the buffer markers since we'll have to copy the bytes out of\n // it later.\n final int originalBufferPos = bufferPos;\n final int originalBufferSize = bufferSize;\n\n // Mark the current buffer consumed.\n totalBytesRetired += bufferSize;\n bufferPos = 0;\n bufferSize = 0;\n\n // Read all the rest of the bytes we need.\n int sizeLeft = size - (originalBufferSize - originalBufferPos);\n final List chunks = new ArrayList();\n\n while (sizeLeft > 0)\n {\n final byte[] chunk = new byte[Math.min(sizeLeft, buffer.length)];\n int pos = 0;\n while (pos < chunk.length)\n {\n final int n = (input == null) ? -1 :\n input.read(chunk, pos, chunk.length - pos);\n if (n == -1)\n {\n throw ProtobufException.truncatedMessage();\n }\n totalBytesRetired += n;\n pos += n;\n }\n sizeLeft -= chunk.length;\n chunks.add(chunk);\n }\n\n // OK, got everything. Now concatenate it all into one buffer.\n final byte[] bytes = new byte[size];\n\n // Start by copying the leftover bytes from this.buffer.\n int pos = originalBufferSize - originalBufferPos;\n System.arraycopy(buffer, originalBufferPos, bytes, 0, pos);\n\n // And now all the chunks.\n for (final byte[] chunk : chunks)\n {\n System.arraycopy(chunk, 0, bytes, pos, chunk.length);\n pos += chunk.length;\n }\n\n // Done.\n return bytes;\n }\n }\n\n /**\n * Reads and discards {@code size} bytes.\n *\n * @throws ProtobufException\n * The end of the stream or the current limit was reached.\n */\n public void skipRawBytes(final int size) throws IOException\n {\n if (size < 0)\n {\n throw ProtobufException.negativeSize();\n }\n\n if (totalBytesRetired + bufferPos + size > currentLimit)\n {\n // Read to the end of the stream anyway.\n skipRawBytes(currentLimit - totalBytesRetired - bufferPos);\n // Then fail.\n throw ProtobufException.truncatedMessage();\n }\n\n if (size <= bufferSize - bufferPos)\n {\n // We have all the bytes we need already.\n bufferPos += size;\n }\n else\n {\n // Skipping more bytes than are in the buffer. First skip what we have.\n int pos = bufferSize - bufferPos;\n bufferPos = bufferSize;\n\n // Keep refilling the buffer until we get to the point we wanted to skip\n // to. This has the side effect of ensuring the limits are updated\n // correctly.\n refillBuffer(true);\n while (size - pos > bufferSize)\n {\n pos += bufferSize;\n bufferPos = bufferSize;\n refillBuffer(true);\n }\n\n bufferPos = size - pos;\n }\n }\n\n // START EXTRA\n @Override\n public int readFieldNumber(Schema schema) throws IOException\n {\n if (isAtEnd())\n {\n lastTag = 0;\n return 0;\n }\n\n // are we reading packed field?\n if (isCurrentFieldPacked())\n {\n if (packedLimit < getTotalBytesRead())\n throw ProtobufException.misreportedSize();\n\n // Return field number while reading packed field\n return lastTag >>> TAG_TYPE_BITS;\n }\n\n packedLimit = 0;\n final int tag = readRawVarint32();\n final int fieldNumber = tag >>> TAG_TYPE_BITS;\n if (fieldNumber == 0)\n {\n if (decodeNestedMessageAsGroup && WIRETYPE_TAIL_DELIMITER == (tag & TAG_TYPE_MASK))\n {\n // protostuff's tail delimiter for streaming\n // 2 options: length-delimited or tail-delimited.\n lastTag = 0;\n return 0;\n }\n // If we actually read zero, that's not a valid tag.\n throw ProtobufException.invalidTag();\n }\n if (decodeNestedMessageAsGroup && WIRETYPE_END_GROUP == (tag & TAG_TYPE_MASK))\n {\n lastTag = 0;\n return 0;\n }\n\n lastTag = tag;\n return fieldNumber;\n }\n\n /**\n * Check if this field have been packed into a length-delimited field. If so, update internal state to reflect that\n * packed fields are being read.\n *\n * @throws IOException\n */\n private void checkIfPackedField() throws IOException\n {\n // Do we have the start of a packed field?\n if (packedLimit == 0 && WireFormat.getTagWireType(lastTag) == WIRETYPE_LENGTH_DELIMITED)\n {\n final int length = readRawVarint32();\n if (length < 0)\n throw ProtobufException.negativeSize();\n\n this.packedLimit = getTotalBytesRead() + length;\n }\n }\n\n @Override\n public byte[] readByteArray() throws IOException\n {\n final int size = readRawVarint32();\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer, so\n // just copy directly from it.\n final byte[] copy = new byte[size];\n System.arraycopy(buffer, bufferPos, copy, 0, size);\n bufferPos += size;\n return copy;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n return readRawBytes(size);\n }\n }\n\n @Override\n public void handleUnknownField(int fieldNumber, Schema schema) throws IOException\n {\n skipField(lastTag);\n }\n\n @Override\n public void transferByteRangeTo(Output output, boolean utf8String, int fieldNumber,\n boolean repeated) throws IOException\n {\n final int size = readRawVarint32();\n if (size <= (bufferSize - bufferPos) && size > 0)\n {\n // Fast path: We already have the bytes in a contiguous buffer\n output.writeByteRange(utf8String, fieldNumber, buffer, bufferPos, size, repeated);\n bufferPos += size;\n }\n else\n {\n // Slow path: Build a byte array first then copy it.\n output.writeByteRange(utf8String, fieldNumber, readRawBytes(size), 0, size, repeated);\n }\n }\n\n /**\n * Returns the last tag.\n */\n public int getLastTag()\n {\n return lastTag;\n }\n\n /**\n * Reads a byte array/ByteBuffer value.\n */\n @Override\n public ByteBuffer readByteBuffer() throws IOException\n {\n return ByteBuffer.wrap(readByteArray());\n }\n\n // END EXTRA\n}\n", "file_name": "CodedInput.java", "human_label": "Check if the field should be packed,if so,read the field and update the internal state. It will throw an exception when the process of reading is wrong.", "level": "class_runnable", "lineno": "1212", "name": "checkIfPackedField", "oracle_context": "{ \"apis\" : \"[getTagWireType, readRawVarint32, negativeSize, getTotalBytesRead]\", \"classes\" : \"[]\", \"vars\" : \"[packedLimit, lastTag]\" }", "package": "io.protostuff", "project": "protostuff-master" }, { "_id": "636767a81a6d9265ec0185fc", "all_context": "{ \"class_level\" : \"import static io.protostuff.WireFormat.TAG_TYPE_BITS;\\nimport static io.protostuff.WireFormat.TAG_TYPE_MASK;\\nimport static io.protostuff.WireFormat.WIRETYPE_END_GROUP;\\nimport static io.protostuff.WireFormat.WIRETYPE_FIXED32;\\nimport static io.protostuff.WireFormat.WIRETYPE_FIXED64;\\nimport static io.protostuff.WireFormat.WIRETYPE_LENGTH_DELIMITED;\\nimport static io.protostuff.WireFormat.WIRETYPE_START_GROUP;\\nimport static io.protostuff.WireFormat.WIRETYPE_TAIL_DELIMITER;\\nimport static io.protostuff.WireFormat.WIRETYPE_VARINT;\\nimport static io.protostuff.WireFormat.getTagFieldNumber;\\nimport static io.protostuff.WireFormat.getTagWireType;\\nimport static io.protostuff.WireFormat.makeTag;\\nimport java.io.IOException;\\nimport java.nio.ByteBuffer;\\nimport io.protostuff.StringSerializer.STRING;\\nByteBuffer buffer;\\nint lastTag;\\nint packedLimit;\\nboolean decodeNestedMessageAsGroup;\\nByteBufferInput(ByteBuffer buffer,boolean protostuffMessage);\\ncurrentOffset();\\ncurrentLimit();\\nisCurrentFieldPacked();\\ngetLastTag();\\nreadTag();\\ncheckLastTagWas(int value);\\nskipField(int tag);\\nskipMessage();\\nhandleUnknownField(int fieldNumber,Schema schema);\\nreadFieldNumber(Schema schema);\\ncheckIfPackedField();\\nreadDouble();\\nreadFloat();\\nreadUInt64();\\nreadInt64();\\nreadInt32();\\nreadFixed64();\\nreadFixed32();\\nreadBool();\\nreadUInt32();\\nreadEnum();\\nreadSFixed32();\\nreadSFixed64();\\nreadSInt32();\\nreadSInt64();\\nreadString();\\nreadBytes();\\nreadBytes(ByteBuffer bb);\\nreadByteArray();\\nmergeObject(T value,Schema schema);\\nmergeObjectEncodedAsGroup(T value,Schema schema);\\nreadRawVarint32();\\nreadRawVarint64();\\nreadRawLittleEndian32();\\nreadRawLittleEndian64();\\ntransferByteRangeTo(Output output,boolean utf8String,int fieldNumber,boolean repeated);\\nreadByteBuffer();\\nreset(int offset,int len);\\n\", \"repo_level\" : \"\" }", "class_name": "ByteBufferInput", "code": "public int readTag() throws IOException {\n if (!buffer.hasRemaining()) {\n lastTag=0;\n return 0;\n }\n final int tag=readRawVarint32();\n if (tag >>> TAG_TYPE_BITS == 0) {\n throw ProtobufException.invalidTag();\n }\n lastTag=tag;\n return tag;\n}\n", "docstring": "/** \n * Attempt to read a field tag, returning zero if we have reached EOF. Protocol message parsers use this to read tags, since a protocol message may legally end wherever a tag occurs, and zero is not a valid tag number.\n */\n", "end_lineno": "133", "file_content": "//========================================================================\n//Copyright 2007-2010 David Yu dyuproject@gmail.com\n//------------------------------------------------------------------------\n//Licensed under the Apache License, Version 2.0 (the \"License\");\n//you may not use this file except in compliance with the License.\n//You may obtain a copy of the License at\n//http://www.apache.org/licenses/LICENSE-2.0\n//Unless required by applicable law or agreed to in writing, software\n//distributed under the License is distributed on an \"AS IS\" BASIS,\n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//See the License for the specific language governing permissions and\n//limitations under the License.\n//========================================================================\n\npackage io.protostuff;\n\nimport static io.protostuff.WireFormat.TAG_TYPE_BITS;\nimport static io.protostuff.WireFormat.TAG_TYPE_MASK;\nimport static io.protostuff.WireFormat.WIRETYPE_END_GROUP;\nimport static io.protostuff.WireFormat.WIRETYPE_FIXED32;\nimport static io.protostuff.WireFormat.WIRETYPE_FIXED64;\nimport static io.protostuff.WireFormat.WIRETYPE_LENGTH_DELIMITED;\nimport static io.protostuff.WireFormat.WIRETYPE_START_GROUP;\nimport static io.protostuff.WireFormat.WIRETYPE_TAIL_DELIMITER;\nimport static io.protostuff.WireFormat.WIRETYPE_VARINT;\nimport static io.protostuff.WireFormat.getTagFieldNumber;\nimport static io.protostuff.WireFormat.getTagWireType;\nimport static io.protostuff.WireFormat.makeTag;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\n\nimport io.protostuff.StringSerializer.STRING;\n\n/**\n * Reads and decodes protocol buffer message fields from an internal byte array buffer. This object is re-usable via\n * doing a reset on the byte array position and length. This is used internally by {@link IOUtil} where it catches\n * {@link ArrayIndexOutOfBoundsException} when a message is truncated.\n * \n * @author David Yu\n * @created Jun 22, 2010\n */\npublic final class ByteBufferInput implements Input\n{\n\n private final ByteBuffer buffer;\n // private final byte[] buffer;\n private int lastTag = 0;\n // private int offset, limit, lastTag = 0;\n private int packedLimit = 0;\n\n /**\n * If true, the nested messages are group-encoded\n */\n public final boolean decodeNestedMessageAsGroup;\n\n /**\n * An input for a ByteBuffer\n * \n * @param buffer\n * the buffer to read from, it will be sliced\n * @param protostuffMessage\n * if we are parsing a protostuff (true) or protobuf (false) message\n */\n public ByteBufferInput(ByteBuffer buffer, boolean protostuffMessage)\n {\n this.buffer = buffer.slice();\n this.decodeNestedMessageAsGroup = protostuffMessage;\n }\n\n /**\n * Resets the offset and the limit of the internal buffer.\n */\n public ByteBufferInput reset(int offset, int len)\n {\n buffer.rewind();\n\n return this;\n }\n\n /**\n * Returns the current offset (the position).\n */\n public int currentOffset()\n {\n return buffer.position();\n }\n\n /**\n * Returns the current limit (the end index).\n */\n public int currentLimit()\n {\n return buffer.limit();\n }\n\n /**\n * Return true if currently reading packed field\n */\n public boolean isCurrentFieldPacked()\n {\n return packedLimit != 0 && packedLimit != buffer.position();\n }\n\n /**\n * Returns the last tag.\n */\n public int getLastTag()\n {\n return lastTag;\n }\n\n /**\n * Attempt to read a field tag, returning zero if we have reached EOF. Protocol message parsers use this to read\n * tags, since a protocol message may legally end wherever a tag occurs, and zero is not a valid tag number.\n */\n public int readTag() throws IOException\n {\n if (!buffer.hasRemaining())\n {\n lastTag = 0;\n return 0;\n }\n\n final int tag = readRawVarint32();\n if (tag >>> TAG_TYPE_BITS == 0)\n {\n // If we actually read zero, that's not a valid tag.\n throw ProtobufException.invalidTag();\n }\n lastTag = tag;\n return tag;\n }\n\n /**\n * Verifies that the last call to readTag() returned the given tag value. This is used to verify that a nested group\n * ended with the correct end tag.\n * \n * @throws ProtobufException\n * {@code value} does not match the last tag.\n */\n public void checkLastTagWas(final int value) throws ProtobufException\n {\n if (lastTag != value)\n {\n throw ProtobufException.invalidEndTag();\n }\n }\n\n /**\n * Reads and discards a single field, given its tag value.\n * \n * @return {@code false} if the tag is an endgroup tag, in which case nothing is skipped. Otherwise, returns\n * {@code true}.\n */\n public boolean skipField(final int tag) throws IOException\n {\n switch (getTagWireType(tag))\n {\n case WIRETYPE_VARINT:\n readInt32();\n return true;\n case WIRETYPE_FIXED64:\n readRawLittleEndian64();\n return true;\n case WIRETYPE_LENGTH_DELIMITED:\n final int size = readRawVarint32();\n if (size < 0)\n throw ProtobufException.negativeSize();\n buffer.position(buffer.position() + size);\n // offset += size;\n return true;\n case WIRETYPE_START_GROUP:\n skipMessage();\n checkLastTagWas(makeTag(getTagFieldNumber(tag), WIRETYPE_END_GROUP));\n return true;\n case WIRETYPE_END_GROUP:\n return false;\n case WIRETYPE_FIXED32:\n readRawLittleEndian32();\n return true;\n default:\n throw ProtobufException.invalidWireType();\n }\n }\n\n /**\n * Reads and discards an entire message. This will read either until EOF or until an endgroup tag, whichever comes\n * first.\n */\n public void skipMessage() throws IOException\n {\n while (true)\n {\n final int tag = readTag();\n if (tag == 0 || !skipField(tag))\n {\n return;\n }\n }\n }\n\n @Override\n public void handleUnknownField(int fieldNumber, Schema schema) throws IOException\n {\n skipField(lastTag);\n }\n\n @Override\n public int readFieldNumber(Schema schema) throws IOException\n {\n if (!buffer.hasRemaining())\n {\n lastTag = 0;\n return 0;\n }\n\n // are we reading packed field?\n if (isCurrentFieldPacked())\n {\n if (packedLimit < buffer.position())\n throw ProtobufException.misreportedSize();\n\n // Return field number while reading packed field\n return lastTag >>> TAG_TYPE_BITS;\n }\n\n packedLimit = 0;\n final int tag = readRawVarint32();\n final int fieldNumber = tag >>> TAG_TYPE_BITS;\n if (fieldNumber == 0)\n {\n if (decodeNestedMessageAsGroup &&\n WIRETYPE_TAIL_DELIMITER == (tag & TAG_TYPE_MASK))\n {\n // protostuff's tail delimiter for streaming\n // 2 options: length-delimited or tail-delimited.\n lastTag = 0;\n return 0;\n }\n // If we actually read zero, that's not a valid tag.\n throw ProtobufException.invalidTag();\n }\n if (decodeNestedMessageAsGroup && WIRETYPE_END_GROUP == (tag & TAG_TYPE_MASK))\n {\n lastTag = 0;\n return 0;\n }\n\n lastTag = tag;\n return fieldNumber;\n }\n\n /**\n * Check if this field have been packed into a length-delimited field. If so, update internal state to reflect that\n * packed fields are being read.\n * \n * @throws IOException\n */\n private void checkIfPackedField() throws IOException\n {\n // Do we have the start of a packed field?\n if (packedLimit == 0 && getTagWireType(lastTag) == WIRETYPE_LENGTH_DELIMITED)\n {\n final int length = readRawVarint32();\n if (length < 0)\n throw ProtobufException.negativeSize();\n\n if (buffer.position() + length > buffer.limit())\n throw ProtobufException.misreportedSize();\n\n this.packedLimit = buffer.position() + length;\n }\n }\n\n /**\n * Read a {@code double} field value from the internal buffer.\n */\n @Override\n public double readDouble() throws IOException\n {\n checkIfPackedField();\n return Double.longBitsToDouble(readRawLittleEndian64());\n }\n\n /**\n * Read a {@code float} field value from the internal buffer.\n */\n @Override\n public float readFloat() throws IOException\n {\n checkIfPackedField();\n return Float.intBitsToFloat(readRawLittleEndian32());\n }\n\n /**\n * Read a {@code uint64} field value from the internal buffer.\n */\n @Override\n public long readUInt64() throws IOException\n {\n checkIfPackedField();\n return readRawVarint64();\n }\n\n /**\n * Read an {@code int64} field value from the internal buffer.\n */\n @Override\n public long readInt64() throws IOException\n {\n checkIfPackedField();\n return readRawVarint64();\n }\n\n /**\n * Read an {@code int32} field value from the internal buffer.\n */\n @Override\n public int readInt32() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32();\n }\n\n /**\n * Read a {@code fixed64} field value from the internal buffer.\n */\n @Override\n public long readFixed64() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian64();\n }\n\n /**\n * Read a {@code fixed32} field value from the internal buffer.\n */\n @Override\n public int readFixed32() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian32();\n }\n\n /**\n * Read a {@code bool} field value from the internal buffer.\n */\n @Override\n public boolean readBool() throws IOException\n {\n checkIfPackedField();\n return buffer.get() != 0;\n }\n\n /**\n * Read a {@code uint32} field value from the internal buffer.\n */\n @Override\n public int readUInt32() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32();\n }\n\n /**\n * Read an enum field value from the internal buffer. Caller is responsible for converting the numeric value to an\n * actual enum.\n */\n @Override\n public int readEnum() throws IOException\n {\n checkIfPackedField();\n return readRawVarint32();\n }\n\n /**\n * Read an {@code sfixed32} field value from the internal buffer.\n */\n @Override\n public int readSFixed32() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian32();\n }\n\n /**\n * Read an {@code sfixed64} field value from the internal buffer.\n */\n @Override\n public long readSFixed64() throws IOException\n {\n checkIfPackedField();\n return readRawLittleEndian64();\n }\n\n /**\n * Read an {@code sint32} field value from the internal buffer.\n */\n @Override\n public int readSInt32() throws IOException\n {\n checkIfPackedField();\n final int n = readRawVarint32();\n return (n >>> 1) ^ -(n & 1);\n }\n\n /**\n * Read an {@code sint64} field value from the internal buffer.\n */\n @Override\n public long readSInt64() throws IOException\n {\n checkIfPackedField();\n final long n = readRawVarint64();\n return (n >>> 1) ^ -(n & 1);\n }\n\n @Override\n public String readString() throws IOException\n {\n final int length = readRawVarint32();\n if (length < 0)\n throw ProtobufException.negativeSize();\n\n if (buffer.remaining() < length)\n throw ProtobufException.misreportedSize();\n\n // if(offset + length > limit)\n\n if (buffer.hasArray())\n {\n final int currPosition = buffer.position();\n buffer.position(buffer.position() + length);\n return STRING.deser(buffer.array(),\n buffer.arrayOffset() + currPosition,\n length);\n }\n else\n {\n byte[] tmp = new byte[length];\n buffer.get(tmp);\n return STRING.deser(tmp);\n }\n\n // final int offset = this.offset;\n\n // this.offset += length;\n\n // return STRING.deser(buffer, offset, length);\n }\n\n @Override\n public ByteString readBytes() throws IOException\n {\n return ByteString.wrap(readByteArray());\n }\n\n @Override\n public void readBytes(final ByteBuffer bb) throws IOException\n {\n final int length = readRawVarint32();\n if (length < 0)\n throw ProtobufException.negativeSize();\n\n if (buffer.remaining() < length)\n // if(offset + length > limit)\n throw ProtobufException.misreportedSize();\n\n bb.put(buffer);\n }\n\n @Override\n public byte[] readByteArray() throws IOException\n {\n final int length = readRawVarint32();\n if (length < 0)\n throw ProtobufException.negativeSize();\n\n if (buffer.remaining() < length)\n // if(offset + length > limit)\n throw ProtobufException.misreportedSize();\n\n final byte[] copy = new byte[length];\n buffer.get(copy);\n return copy;\n }\n\n @Override\n public T mergeObject(T value, final Schema schema) throws IOException\n {\n if (decodeNestedMessageAsGroup)\n return mergeObjectEncodedAsGroup(value, schema);\n\n final int length = readRawVarint32();\n if (length < 0)\n throw ProtobufException.negativeSize();\n\n if (buffer.remaining() < length)\n throw ProtobufException.misreportedSize();\n\n ByteBuffer dup = buffer.slice();\n dup.limit(length);\n\n // save old limit\n // final int oldLimit = this.limit;\n\n // this.limit = offset + length;\n\n if (value == null)\n value = schema.newMessage();\n ByteBufferInput nestedInput = new ByteBufferInput(dup, decodeNestedMessageAsGroup);\n schema.mergeFrom(nestedInput, value);\n if (!schema.isInitialized(value))\n throw new UninitializedMessageException(value, schema);\n nestedInput.checkLastTagWas(0);\n // checkLastTagWas(0);\n\n // restore old limit\n // this.limit = oldLimit;\n\n buffer.position(buffer.position() + length);\n return value;\n }\n\n private T mergeObjectEncodedAsGroup(T value, final Schema schema) throws IOException\n {\n if (value == null)\n value = schema.newMessage();\n schema.mergeFrom(this, value);\n if (!schema.isInitialized(value))\n throw new UninitializedMessageException(value, schema);\n // handling is in #readFieldNumber\n checkLastTagWas(0);\n return value;\n }\n\n /**\n * Reads a var int 32 from the internal byte buffer.\n */\n public int readRawVarint32() throws IOException\n {\n byte tmp = buffer.get();\n if (tmp >= 0)\n {\n return tmp;\n }\n int result = tmp & 0x7f;\n if ((tmp = buffer.get()) >= 0)\n {\n result |= tmp << 7;\n }\n else\n {\n result |= (tmp & 0x7f) << 7;\n if ((tmp = buffer.get()) >= 0)\n {\n result |= tmp << 14;\n }\n else\n {\n result |= (tmp & 0x7f) << 14;\n if ((tmp = buffer.get()) >= 0)\n {\n result |= tmp << 21;\n }\n else\n {\n result |= (tmp & 0x7f) << 21;\n result |= (tmp = buffer.get()) << 28;\n if (tmp < 0)\n {\n // Discard upper 32 bits.\n for (int i = 0; i < 5; i++)\n {\n if (buffer.get() >= 0)\n {\n return result;\n }\n }\n throw ProtobufException.malformedVarint();\n }\n }\n }\n }\n return result;\n }\n\n /**\n * Reads a var int 64 from the internal byte buffer.\n */\n public long readRawVarint64() throws IOException\n {\n // final byte[] buffer = this.buffer;\n // int offset = this.offset;\n\n int shift = 0;\n long result = 0;\n while (shift < 64)\n {\n final byte b = buffer.get();\n result |= (long) (b & 0x7F) << shift;\n if ((b & 0x80) == 0)\n {\n // this.offset = offset;\n return result;\n }\n shift += 7;\n }\n throw ProtobufException.malformedVarint();\n }\n\n /**\n * Read a 32-bit little-endian integer from the internal buffer.\n */\n public int readRawLittleEndian32() throws IOException\n {\n // final byte[] buffer = this.buffer;\n // int offset = this.offset;\n\n final byte[] bs = new byte[4];\n buffer.get(bs);\n\n // final byte b1 = buffer[offset++];\n // final byte b2 = buffer[offset++];\n // final byte b3 = buffer[offset++];\n // final byte b4 = buffer[offset++];\n //\n // this.offset = offset;\n\n return (((int) bs[0] & 0xff)) |\n (((int) bs[1] & 0xff) << 8) |\n (((int) bs[2] & 0xff) << 16) |\n (((int) bs[3] & 0xff) << 24);\n }\n\n /**\n * Read a 64-bit little-endian integer from the internal byte buffer.\n */\n public long readRawLittleEndian64() throws IOException\n {\n // final byte[] buffer = this.buffer;\n // int offset = this.offset;\n\n final byte[] bs = new byte[8];\n buffer.get(bs);\n\n // final byte b1 = buffer[offset++];\n // final byte b2 = buffer[offset++];\n // final byte b3 = buffer[offset++];\n // final byte b4 = buffer[offset++];\n // final byte b5 = buffer[offset++];\n // final byte b6 = buffer[offset++];\n // final byte b7 = buffer[offset++];\n // final byte b8 = buffer[offset++];\n //\n // this.offset = offset;\n\n return (((long) bs[0] & 0xff)) |\n (((long) bs[1] & 0xff) << 8) |\n (((long) bs[2] & 0xff) << 16) |\n (((long) bs[3] & 0xff) << 24) |\n (((long) bs[4] & 0xff) << 32) |\n (((long) bs[5] & 0xff) << 40) |\n (((long) bs[6] & 0xff) << 48) |\n (((long) bs[7] & 0xff) << 56);\n }\n\n @Override\n public void transferByteRangeTo(Output output, boolean utf8String, int fieldNumber,\n boolean repeated) throws IOException\n {\n final int length = readRawVarint32();\n if (length < 0)\n throw ProtobufException.negativeSize();\n\n if (utf8String)\n {\n // if it is a UTF string, we have to call the writeByteRange.\n\n if (buffer.hasArray())\n {\n output.writeByteRange(true, fieldNumber, buffer.array(),\n buffer.arrayOffset() + buffer.position(), length, repeated);\n buffer.position(buffer.position() + length);\n }\n else\n {\n byte[] bytes = new byte[length];\n buffer.get(bytes);\n output.writeByteRange(true, fieldNumber, bytes, 0, bytes.length, repeated);\n }\n }\n else\n {\n // Do the potentially vastly more efficient potential splice call.\n if (buffer.remaining() < length)\n throw ProtobufException.misreportedSize();\n\n ByteBuffer dup = buffer.slice();\n dup.limit(length);\n\n output.writeBytes(fieldNumber, dup, repeated);\n\n buffer.position(buffer.position() + length);\n }\n\n // output.writeByteRange(utf8String, fieldNumber, buffer, offset, length, repeated);\n //\n // offset += length;\n }\n\n /**\n * Reads a byte array/ByteBuffer value.\n */\n @Override\n public ByteBuffer readByteBuffer() throws IOException\n {\n return ByteBuffer.wrap(readByteArray());\n }\n}\n", "file_name": "ByteBufferInput.java", "human_label": "Return a field tag, and if reach the EOF the tag will be zero.It will throw an exception when the tag is equal to zero after logical shift right TAG_TYPE_BITS.", "level": "class_runnable", "lineno": "113", "name": "readTag", "oracle_context": "{ \"apis\" : \"[hasRemaining, readRawVarint32, invalidTag]\", \"classes\" : \"[]\", \"vars\" : \"[buffer, lastTag]\" }", "package": "io.protostuff", "project": "protostuff-master" }, { "_id": "636766a81a6d9265ec017595", "all_context": "{ \"class_level\" : \"byte[] data;\\nint length;\\nByteVector(int initialCapacity);\\nput11(int byteValue1,int byteValue2);\\nputShort(int shortValue);\\nput12(int byteValue,int shortValue);\\nputInt(int intValue);\\nput122(int byteValue,int shortValue1,int shortValue2);\\nputLong(long longValue);\\nputUTF8(String stringValue);\\nencodeUtf8(String stringValue,int offset,int maxByteLength);\\nputByteArray(byte[] byteArrayValue,int byteOffset,int byteLength);\\nenlarge(int size);\\nputByte(int byteValue);\\n\", \"repo_level\" : \"\" }", "class_name": "ByteVector", "code": "final ByteVector put11(final int byteValue1,final int byteValue2){\n int currentLength=length;\n if (currentLength + 2 > data.length) {\n enlarge(2);\n }\n byte[] currentData=data;\n currentData[currentLength++]=(byte)byteValue1;\n currentData[currentLength++]=(byte)byteValue2;\n length=currentLength;\n return this;\n}\n", "docstring": "/** \n * Puts two bytes into this byte vector. The byte vector is automatically enlarged if necessary.\n * @param byteValue1 a byte.\n * @param byteValue2 another byte.\n * @return this byte vector.\n */\n", "end_lineno": "96", "file_content": "// ASM: a very small and fast Java bytecode manipulation framework\n// Copyright (c) 2000-2011 INRIA, France Telecom\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the copyright holders nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n// THE POSSIBILITY OF SUCH DAMAGE.\npackage com.alibaba.fastjson2.internal.asm;\n\n/**\n * A dynamically extensible vector of bytes. This class is roughly equivalent to a DataOutputStream\n * on top of a ByteArrayOutputStream, but is more efficient.\n *\n * @author Eric Bruneton\n */\npublic class ByteVector {\n /**\n * The content of this vector. Only the first {@link #length} bytes contain real data.\n */\n byte[] data;\n\n /**\n * The actual number of bytes in this vector.\n */\n int length;\n//\n// /**\n// * Constructs a new {@link ByteVector} with a default initial capacity.\n// */\n// public ByteVector() {\n// data = new byte[64];\n// }\n\n /**\n * Constructs a new {@link ByteVector} with the given initial capacity.\n *\n * @param initialCapacity the initial capacity of the byte vector to be constructed.\n */\n public ByteVector(final int initialCapacity) {\n data = new byte[initialCapacity];\n }\n\n /**\n * Puts a byte into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param byteValue a byte.\n * @return this byte vector.\n */\n public ByteVector putByte(final int byteValue) {\n int currentLength = length;\n if (currentLength + 1 > data.length) {\n enlarge(1);\n }\n data[currentLength++] = (byte) byteValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts two bytes into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param byteValue1 a byte.\n * @param byteValue2 another byte.\n * @return this byte vector.\n */\n final ByteVector put11(final int byteValue1, final int byteValue2) {\n int currentLength = length;\n if (currentLength + 2 > data.length) {\n enlarge(2);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue1;\n currentData[currentLength++] = (byte) byteValue2;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a short into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param shortValue a short.\n * @return this byte vector.\n */\n public ByteVector putShort(final int shortValue) {\n int currentLength = length;\n if (currentLength + 2 > data.length) {\n enlarge(2);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a byte and a short into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteValue a byte.\n * @param shortValue a short.\n * @return this byte vector.\n */\n final ByteVector put12(final int byteValue, final int shortValue) {\n int currentLength = length;\n if (currentLength + 3 > data.length) {\n enlarge(3);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue;\n currentData[currentLength++] = (byte) (shortValue >>> 8);\n currentData[currentLength++] = (byte) shortValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an int into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param intValue an int.\n * @return this byte vector.\n */\n public ByteVector putInt(final int intValue) {\n int currentLength = length;\n if (currentLength + 4 > data.length) {\n enlarge(4);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts one byte and two shorts into this byte vector. The byte vector is automatically enlarged\n * if necessary.\n *\n * @param byteValue a byte.\n * @param shortValue1 a short.\n * @param shortValue2 another short.\n * @return this byte vector.\n */\n final ByteVector put122(final int byteValue, final int shortValue1, final int shortValue2) {\n int currentLength = length;\n if (currentLength + 5 > data.length) {\n enlarge(5);\n }\n byte[] currentData = data;\n currentData[currentLength++] = (byte) byteValue;\n currentData[currentLength++] = (byte) (shortValue1 >>> 8);\n currentData[currentLength++] = (byte) shortValue1;\n currentData[currentLength++] = (byte) (shortValue2 >>> 8);\n currentData[currentLength++] = (byte) shortValue2;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts a long into this byte vector. The byte vector is automatically enlarged if necessary.\n *\n * @param longValue a long.\n * @return this byte vector.\n */\n public ByteVector putLong(final long longValue) {\n int currentLength = length;\n if (currentLength + 8 > data.length) {\n enlarge(8);\n }\n byte[] currentData = data;\n int intValue = (int) (longValue >>> 32);\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n intValue = (int) longValue;\n currentData[currentLength++] = (byte) (intValue >>> 24);\n currentData[currentLength++] = (byte) (intValue >>> 16);\n currentData[currentLength++] = (byte) (intValue >>> 8);\n currentData[currentLength++] = (byte) intValue;\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param stringValue a String whose UTF8 encoded length must be less than 65536.\n * @return this byte vector.\n */\n // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility).\n public ByteVector putUTF8(final String stringValue) {\n int charLength = stringValue.length();\n if (charLength > 65535) {\n throw new IllegalArgumentException(\"UTF8 string too large\");\n }\n int currentLength = length;\n if (currentLength + 2 + charLength > data.length) {\n enlarge(2 + charLength);\n }\n byte[] currentData = data;\n // Optimistic algorithm: instead of computing the byte length and then serializing the string\n // (which requires two loops), we assume the byte length is equal to char length (which is the\n // most frequent case), and we start serializing the string right away. During the\n // serialization, if we find that this assumption is wrong, we continue with the general method.\n currentData[currentLength++] = (byte) (charLength >>> 8);\n currentData[currentLength++] = (byte) charLength;\n for (int i = 0; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= '\\u0001' && charValue <= '\\u007F') {\n currentData[currentLength++] = (byte) charValue;\n } else {\n length = currentLength;\n return encodeUtf8(stringValue, i, 65535);\n }\n }\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an UTF8 string into this byte vector. The byte vector is automatically enlarged if\n * necessary. The string length is encoded in two bytes before the encoded characters, if there is\n * space for that (i.e. if this.length - offset - 2 >= 0).\n *\n * @param stringValue the String to encode.\n * @param offset the index of the first character to encode. The previous characters are supposed\n * to have already been encoded, using only one byte per character.\n * @param maxByteLength the maximum byte length of the encoded string, including the already\n * encoded characters.\n * @return this byte vector.\n */\n final ByteVector encodeUtf8(final String stringValue, final int offset, final int maxByteLength) {\n int charLength = stringValue.length();\n int byteLength = offset;\n for (int i = offset; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= 0x0001 && charValue <= 0x007F) {\n byteLength++;\n } else if (charValue <= 0x07FF) {\n byteLength += 2;\n } else {\n byteLength += 3;\n }\n }\n if (byteLength > maxByteLength) {\n throw new IllegalArgumentException(\"UTF8 string too large\");\n }\n // Compute where 'byteLength' must be stored in 'data', and store it at this location.\n int byteLengthOffset = length - offset - 2;\n if (byteLengthOffset >= 0) {\n data[byteLengthOffset] = (byte) (byteLength >>> 8);\n data[byteLengthOffset + 1] = (byte) byteLength;\n }\n if (length + byteLength - offset > data.length) {\n enlarge(byteLength - offset);\n }\n int currentLength = length;\n for (int i = offset; i < charLength; ++i) {\n char charValue = stringValue.charAt(i);\n if (charValue >= 0x0001 && charValue <= 0x007F) {\n data[currentLength++] = (byte) charValue;\n } else if (charValue <= 0x07FF) {\n data[currentLength++] = (byte) (0xC0 | charValue >> 6 & 0x1F);\n data[currentLength++] = (byte) (0x80 | charValue & 0x3F);\n } else {\n data[currentLength++] = (byte) (0xE0 | charValue >> 12 & 0xF);\n data[currentLength++] = (byte) (0x80 | charValue >> 6 & 0x3F);\n data[currentLength++] = (byte) (0x80 | charValue & 0x3F);\n }\n }\n length = currentLength;\n return this;\n }\n\n /**\n * Puts an array of bytes into this byte vector. The byte vector is automatically enlarged if\n * necessary.\n *\n * @param byteArrayValue an array of bytes. May be {@literal null} to put {@code byteLength} null\n * bytes into this byte vector.\n * @param byteOffset index of the first byte of byteArrayValue that must be copied.\n * @param byteLength number of bytes of byteArrayValue that must be copied.\n * @return this byte vector.\n */\n public ByteVector putByteArray(\n final byte[] byteArrayValue, final int byteOffset, final int byteLength) {\n if (length + byteLength > data.length) {\n enlarge(byteLength);\n }\n if (byteArrayValue != null) {\n System.arraycopy(byteArrayValue, byteOffset, data, length, byteLength);\n }\n length += byteLength;\n return this;\n }\n\n /**\n * Enlarges this byte vector so that it can receive 'size' more bytes.\n *\n * @param size number of additional bytes that this byte vector should be able to receive.\n */\n private void enlarge(final int size) {\n int doubleCapacity = 2 * data.length;\n int minimalCapacity = length + size;\n byte[] newData = new byte[doubleCapacity > minimalCapacity ? doubleCapacity : minimalCapacity];\n System.arraycopy(data, 0, newData, 0, length);\n data = newData;\n }\n}\n", "file_name": "ByteVector.java", "human_label": "Put two bytes into a byte vector called data.The vector will be enlarged if necessary.And return the ByteVector object.", "level": "class_runnable", "lineno": "79", "name": "put11", "oracle_context": "{ \"apis\" : \"[enlarge, ByteVector]\", \"classes\" : \"[byte[], data]\", \"vars\" : \"[length, data]\" }", "package": "com.alibaba.fastjson2.internal.asm", "project": "fastjson2-main" }, { "_id": "636766ae1a6d9265ec0175d8", "all_context": "{ \"class_level\" : \"import java.util.List;\\nimport java.util.Map;\\nimport java.util.concurrent.ConcurrentHashMap;\\nimport java.util.logging.Logger;\\nimport javax.enterprise.context.RequestScoped;\\nimport javax.inject.Inject;\\nimport javax.ws.rs.container.ContainerResponseContext;\\nimport javax.ws.rs.container.ResourceInfo;\\nimport javax.ws.rs.core.HttpHeaders;\\nimport javax.ws.rs.core.UriInfo;\\nimport org.demoiselle.jee.crud.AbstractDAO;\\nimport org.demoiselle.jee.crud.CrudUtilHelper;\\nimport org.demoiselle.jee.crud.DemoiselleRequestContext;\\nimport org.demoiselle.jee.crud.ReservedHTTPHeaders;\\nimport org.demoiselle.jee.crud.ReservedKeyWords;\\nimport org.demoiselle.jee.crud.Search;\\nUriInfo uriInfo;\\nResourceInfo resourceInfo;\\nDemoiselleRequestContext drc;\\nPaginationHelperMessage message;\\nPaginationHelperConfig paginationConfig;\\nLogger logger;\\nPaginationHelper();\\nPaginationHelper(ResourceInfo resourceInfo,UriInfo uriInfo,PaginationHelperConfig paginationConfig,DemoiselleRequestContext drc,PaginationHelperMessage message);\\nfillObjects(ResourceInfo resourceInfo,UriInfo uriInfo);\\nisPaginationEnabled();\\nisRequestPagination();\\ncheckAndFillRangeValues();\\ngetDefaultNumberPagination();\\nhasSearchAnnotation();\\nisPartialContentResponse();\\nlogInvalidRangeParameters(String range);\\nbuildContentRange();\\nbuildAcceptRange();\\nbuildHeaders(ResourceInfo resourceInfo,UriInfo uriInfo);\\nbuildLinkHeader();\\nisFirstPage();\\nbuildAcceptRangeWithResponse(ContainerResponseContext response);\\nexecute(ResourceInfo resourceInfo,UriInfo uriInfo);\\n\", \"repo_level\" : \"public interface AbstractDAO {abstract EntityManager getEntityManager();\\npublic T persist(T entity);\\npublic T mergeHalf(I id,T entity);\\npublic T mergeFull(T entity);\\npublic void remove(I id);\\npublic T find(I id);\\npublic Result find();\\nprotected void configureCriteriaQuery(CriteriaBuilder criteriaBuilder,CriteriaQuery criteriaQuery);\\nprotected void configureOrder(CriteriaBuilder criteriaBuilder,CriteriaQuery criteriaQuery,Root root);\\nprotected Predicate[] buildPredicates(CriteriaBuilder criteriaBuilder,CriteriaQuery criteriaQuery,Root root);\\nprotected Boolean isEnumFilter(String key,String value,TreeNodeField tnf);\\nprotected Boolean isUUIDFilter(String key,String value,TreeNodeField tnf);\\nprotected Integer convertEnumToInt(String key,String value,TreeNodeField tnf);\\nprotected Boolean isLikeFilter(String value);\\nprotected Predicate buildLikePredicate(CriteriaBuilder criteriaBuilder,CriteriaQuery criteriaQuery,From root,String key,String value);\\nprotected Integer getMaxResult();\\npublic Long count();\\nprotected Predicate[] extractPredicates(MultivaluedMap queryParameters,CriteriaBuilder criteriaBuilder,Root root);\\npublic PaginationHelperConfig getPaginationConfig();\\npublic DemoiselleRequestContext getDrc();\\npublic Class getEntityClass();\\n }\\npublic interface CrudUtilHelper {static Class getTargetClass(Class targetClass);\\nstatic void checkIfExistField(Class targetClass,String field);\\nstatic List getAllFields(List fields,Class type);\\nstatic Field getField(Class targetClass,String name);\\nstatic List extractFields(String fields);\\nstatic TreeNodeField> extractFieldsFromSearchAnnotation(ResourceInfo resourceInfo);\\nstatic void fillLeafTreeNodeField(TreeNodeField tnf,String field,Set value);\\nstatic void validateFields(TreeNodeField tnf,ResourceInfo resourceInfo,CrudMessage crudMessage);\\nstatic String getMethodAnnotatedWithID(Class targetClass);\\n }\\npublic interface DemoiselleRequestContext { Integer getLimit();\\n void setLimit(Integer limit);\\n Integer getOffset();\\n void setOffset(Integer offset);\\n Long getCount();\\n void setCount(Long count);\\n Class getEntityClass();\\n void setEntityClass(Class entityClass);\\n TreeNodeField> getFilters();\\n void setFilters(TreeNodeField filters);\\n List getSorts();\\n void setSorts(List sorts);\\n TreeNodeField> getFields();\\n void setFields(TreeNodeField fields);\\n Boolean isPaginationEnabled();\\n void setPaginationEnabled(Boolean isPaginationEnabled);\\n }\\n\" }", "class_name": "PaginationHelper", "code": "private String buildContentRange(){\n Integer limit=drc.getLimit() == null ? getDefaultNumberPagination() - 1 : drc.getLimit();\n Integer offset=drc.getOffset() == null ? 0 : drc.getOffset();\n Long count=drc.getCount() == null ? 0 : drc.getCount();\n return offset + \"-\" + (limit.equals(0) ? count - 1 : limit)+ \"/\"+ count;\n}\n", "docstring": "/** \n * Build the 'Content-Range' HTTP Header value.\n * @return 'Content-Range' value\n */\n", "end_lineno": "235", "file_content": "/*\n * Demoiselle Framework\n *\n * License: GNU Lesser General Public License (LGPL), version 3 or later.\n * See the lgpl.txt file in the root directory or .\n */\npackage org.demoiselle.jee.crud.pagination;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.logging.Logger;\n\nimport javax.enterprise.context.RequestScoped;\nimport javax.inject.Inject;\nimport javax.ws.rs.container.ContainerResponseContext;\nimport javax.ws.rs.container.ResourceInfo;\nimport javax.ws.rs.core.HttpHeaders;\nimport javax.ws.rs.core.UriInfo;\n\nimport org.demoiselle.jee.crud.AbstractDAO;\nimport org.demoiselle.jee.crud.CrudUtilHelper;\nimport org.demoiselle.jee.crud.DemoiselleRequestContext;\nimport org.demoiselle.jee.crud.ReservedHTTPHeaders;\nimport org.demoiselle.jee.crud.ReservedKeyWords;\nimport org.demoiselle.jee.crud.Search;\n\n/**\n * Class responsible for managing the 'range' parameter comes from Url Query\n * String.\n *\n * Ex:\n *\n * Given a request\n *

          \n * GET @{literal http://localhost:8080/api/users?range=0-10}\n * 
          \n *\n * This class will processing the request above and parse the range parameters\n * to {@link DemoiselleRequestContext} object.\n *\n * This object will be use on {@link AbstractDAO} class to execute the\n * pagination on database.\n *\n */\n@RequestScoped\npublic class PaginationHelper {\n\n private UriInfo uriInfo;\n\n private ResourceInfo resourceInfo;\n\n @Inject\n private DemoiselleRequestContext drc;\n\n @Inject\n private PaginationHelperMessage message;\n\n @Inject\n private PaginationHelperConfig paginationConfig;\n\n private static final Logger logger = Logger.getLogger(PaginationHelper.class.getName());\n\n public PaginationHelper() {\n }\n\n public PaginationHelper(ResourceInfo resourceInfo, UriInfo uriInfo, PaginationHelperConfig paginationConfig, DemoiselleRequestContext drc, PaginationHelperMessage message) {\n this.resourceInfo = resourceInfo;\n this.uriInfo = uriInfo;\n this.paginationConfig = paginationConfig;\n this.drc = drc;\n this.message = message;\n }\n\n /**\n * Open the request query string to extract values from 'range' parameter\n * and fill the {@link DemoiselleRequestContext#setOffset(Integer)} and\n * {@link DemoiselleRequestContext#setLimit(Integer)}\n *\n * @param resourceInfo ResourceInfo\n * @param uriInfo UriInfo\n */\n public void execute(ResourceInfo resourceInfo, UriInfo uriInfo) {\n fillObjects(resourceInfo, uriInfo);\n\n drc.setPaginationEnabled(isPaginationEnabled());\n\n if (drc.isPaginationEnabled()) {\n\n if (isRequestPagination()) {\n checkAndFillRangeValues();\n }\n\n if (hasSearchAnnotation() && !isRequestPagination()) {\n drc.setLimit(getDefaultNumberPagination() - 1);\n drc.setOffset(new Integer(0));\n }\n }\n\n if (hasSearchAnnotation() && isRequestPagination()) {\n Search searchAnnotation = resourceInfo.getResourceMethod().getAnnotation(Search.class);\n // Pagination @Search.withPagination is disabled but the request parameter has 'range' parameter\n if (searchAnnotation.withPagination() == Boolean.FALSE) {\n throw new IllegalArgumentException(message.paginationIsNotEnabled());\n }\n }\n }\n\n private void fillObjects(ResourceInfo resourceInfo, UriInfo uriInfo) {\n this.resourceInfo = resourceInfo == null ? this.resourceInfo : resourceInfo;\n this.uriInfo = uriInfo == null ? this.uriInfo : uriInfo;\n }\n\n /**\n * Check the pagination is enabled\n *\n * @return pagination enabled/disabled\n */\n private Boolean isPaginationEnabled() {\n if (paginationConfig.getIsGlobalEnabled() == Boolean.FALSE) {\n return Boolean.FALSE;\n }\n\n if (hasSearchAnnotation()) {\n Search searchAnnotation = resourceInfo.getResourceMethod().getAnnotation(Search.class);\n return searchAnnotation.withPagination();\n }\n\n return paginationConfig.getIsGlobalEnabled();\n }\n\n /**\n * Check if the actual request has the 'range' parameter on query string\n *\n * @return is request pagination or not\n */\n private Boolean isRequestPagination() {\n // Verify if contains 'range' in url\n if (uriInfo.getQueryParameters().containsKey(ReservedKeyWords.DEFAULT_RANGE_KEY.getKey())) {\n return Boolean.TRUE;\n }\n return Boolean.FALSE;\n }\n\n /**\n * Check if the value of 'range' parameter is valid using the rules:\n *\n * - Value formatted like offset-limit (range=0-10); - The 'offset' and\n * 'limit' should be a integer; - The 'offset' should be less than or equals\n * 'limit';\n *\n *\n * @throws IllegalArgumentException The format is invalid\n */\n private void checkAndFillRangeValues() throws IllegalArgumentException {\n List rangeList = uriInfo.getQueryParameters().get(ReservedKeyWords.DEFAULT_RANGE_KEY.getKey());\n if (!rangeList.isEmpty()) {\n String range[] = rangeList.get(0).split(\"-\");\n if (range.length == 2) {\n String offset = range[0];\n String limit = range[1];\n\n try {\n drc.setOffset(new Integer(offset));\n drc.setLimit(new Integer(limit));\n\n if (drc.getOffset() > drc.getLimit()) {\n logInvalidRangeParameters(rangeList.get(0));\n throw new IllegalArgumentException(this.message.invalidRangeParameters());\n }\n\n if (((drc.getLimit() - drc.getOffset()) + 1) > getDefaultNumberPagination()) {\n logger.warning(message.defaultPaginationNumberExceed(getDefaultNumberPagination()) + \", [\" + drc.toString() + \"]\");\n throw new IllegalArgumentException(message.defaultPaginationNumberExceed(getDefaultNumberPagination()));\n }\n\n } catch (NumberFormatException nfe) {\n logInvalidRangeParameters(rangeList.get(0));\n throw new IllegalArgumentException(message.invalidRangeParameters());\n }\n } else {\n logInvalidRangeParameters(rangeList.get(0));\n throw new IllegalArgumentException(message.invalidRangeParameters());\n }\n }\n\n }\n\n /**\n * Get default pagination number, if the target method is annotated with\n * Search annotation the default annotation will be\n * {@link Search#quantityPerPage()} otherwise the default pagination will be\n * {@link PaginationHelperConfig#getDefaultPagination()} value;\n *\n * @return Number per page\n */\n private Integer getDefaultNumberPagination() {\n if (hasSearchAnnotation()) {\n Search searchAnnotation = resourceInfo.getResourceMethod().getAnnotation(Search.class);\n return searchAnnotation.quantityPerPage();\n }\n\n return paginationConfig.getDefaultPagination();\n }\n\n private Boolean hasSearchAnnotation() {\n return resourceInfo.getResourceMethod().isAnnotationPresent(Search.class);\n }\n\n /**\n * Check if the actual response is a Partial Content (HTTP 206 code)\n *\n * @return is partial content or not\n */\n public Boolean isPartialContentResponse() {\n Integer limit = drc.getLimit() == null ? 0 : drc.getLimit();\n Long count = drc.getCount() == null ? 0 : drc.getCount();\n return !((limit + 1) >= count);\n }\n\n private void logInvalidRangeParameters(String range) {\n logger.warning(message.invalidRangeParameters() + \", [params: \" + range + \"]\");\n }\n\n /**\n * Build the 'Content-Range' HTTP Header value.\n *\n * @return 'Content-Range' value\n */\n private String buildContentRange() {\n Integer limit = drc.getLimit() == null ? getDefaultNumberPagination() - 1 : drc.getLimit();\n Integer offset = drc.getOffset() == null ? 0 : drc.getOffset();\n Long count = drc.getCount() == null ? 0 : drc.getCount();\n return offset + \"-\" + (limit.equals(0) ? count - 1 : limit) + \"/\" + count;\n }\n\n /**\n * Build the 'Accept-Range' HTTP Header value.\n *\n * @return 'Accept-Range' value\n */\n public String buildAcceptRange() {\n String resource = \"\";\n\n if (drc.getEntityClass() != null) {\n resource = drc.getEntityClass().getSimpleName().toLowerCase();\n } else {\n if (resourceInfo != null && resourceInfo.getResourceClass() != null) {\n Class targetClass = CrudUtilHelper.getTargetClass(resourceInfo.getResourceClass());\n if (targetClass != null) {\n resource = targetClass.getSimpleName().toLowerCase();\n }\n }\n }\n\n if (!resource.isEmpty()) {\n return resource + \" \" + getDefaultNumberPagination();\n }\n\n return null;\n }\n\n /**\n * Set the 'Content-Range', 'Accept-Range', 'Link' and\n * 'Access-Control-Expose-Headers' HTTP headers;\n *\n * @param resourceInfo ResourceInfo\n * @param uriInfo UriInfo\n *\n * @return A map with HTTP headers\n */\n public Map buildHeaders(ResourceInfo resourceInfo, UriInfo uriInfo) {\n fillObjects(resourceInfo, uriInfo);\n Map headers = new ConcurrentHashMap<>();\n\n if (drc.isPaginationEnabled()) {\n headers.putIfAbsent(ReservedHTTPHeaders.HTTP_HEADER_CONTENT_RANGE.getKey(), buildContentRange());\n headers.putIfAbsent(ReservedHTTPHeaders.HTTP_HEADER_ACCEPT_RANGE.getKey(), buildAcceptRange());\n String linkHeader = buildLinkHeader();\n\n if (!linkHeader.isEmpty()) {\n headers.putIfAbsent(HttpHeaders.LINK, linkHeader);\n }\n }\n\n return headers;\n }\n\n /**\n * Build the 'Link' HTTP header value\n *\n * @return 'Link' value\n */\n private String buildLinkHeader() {\n StringBuffer sb = new StringBuffer();\n String url = uriInfo.getRequestUri().toString();\n url = url.replaceFirst(\".range=([^&]*)\", \"\");\n\n if (drc.getOffset() == null) {\n drc.setOffset(new Integer(0));\n }\n\n if (drc.getLimit() == null) {\n drc.setLimit(getDefaultNumberPagination() - 1);\n }\n\n Integer offset = drc.getOffset() + 1;\n Integer limit = drc.getLimit() + 1;\n Integer quantityPerPage = (limit - offset) + 1;\n\n if (uriInfo.getQueryParameters().isEmpty()\n || (uriInfo.getQueryParameters().size() == 1 && uriInfo.getQueryParameters().containsKey(ReservedKeyWords.DEFAULT_RANGE_KEY.getKey()))) {\n url += \"?\" + ReservedKeyWords.DEFAULT_RANGE_KEY.getKey() + \"=\";\n } else {\n url += \"&\" + ReservedKeyWords.DEFAULT_RANGE_KEY.getKey() + \"=\";\n }\n\n if (!isFirstPage()) {\n Integer prevPageRangeInit = (drc.getOffset() - quantityPerPage) < 0 ? 0 : (drc.getOffset() - quantityPerPage);\n Integer firstRange2 = quantityPerPage - 1 < drc.getOffset() - 1 ? quantityPerPage - 1 : drc.getOffset() - 1;\n\n String firstPage = url + 0 + \"-\" + firstRange2;\n String prevPage = url + prevPageRangeInit + \"-\" + (drc.getOffset() - 1);\n\n sb.append(\"<\").append(firstPage).append(\">; rel=\\\"first\\\",\");\n sb.append(\"<\").append(prevPage).append(\">; rel=\\\"prev\\\",\");\n }\n\n if (isPartialContentResponse()) {\n String nextPage = url + (drc.getOffset() + quantityPerPage) + \"-\" + (2 * quantityPerPage + drc.getOffset() - 1);\n String lastPage = url + (drc.getCount() - quantityPerPage) + \"-\" + (drc.getCount() - 1);\n\n if (offset + quantityPerPage >= drc.getCount() - 1) {\n nextPage = lastPage;\n }\n\n sb.append(\"<\").append(nextPage).append(\">; rel=\\\"next\\\",\");\n sb.append(\"<\").append(lastPage).append(\">; rel=\\\"last\\\"\");\n }\n\n return sb.toString();\n }\n\n private Boolean isFirstPage() {\n return drc.getOffset().equals(0);\n }\n\n public void buildAcceptRangeWithResponse(ContainerResponseContext response) {\n if (response != null) {\n String acceptRangeHeader = buildAcceptRange();\n if (acceptRangeHeader != null) {\n response.getHeaders().putSingle(ReservedHTTPHeaders.HTTP_HEADER_ACCEPT_RANGE.getKey(), acceptRangeHeader);\n }\n }\n\n }\n\n}\n", "file_name": "PaginationHelper.java", "human_label": "Return the string that contains the content range from offset to limit(when limit is zero,the upper bound will be count-1) and count.", "level": "class_runnable", "lineno": "225", "name": "buildContentRange", "oracle_context": "{ \"apis\" : \"[getLimit, getDefaultNumberPagination, getOffset, getCount, equals]\", \"classes\" : \"[Integer, Long]\", \"vars\" : \"[drc]\" }", "package": "org.demoiselle.jee.crud.pagination", "project": "framework-master" }, { "_id": "636767e11a6d9265ec018790", "all_context": "{ \"class_level\" : \"import lombok.extern.slf4j.Slf4j;\\nimport org.apache.skywalking.apm.network.language.profile.v3.ThreadSnapshot;\\nimport org.apache.skywalking.apm.network.language.profile.v3.ThreadStack;\\nimport org.apache.skywalking.oap.server.core.profiling.trace.ProfileThreadSnapshotRecord;\\nimport org.apache.skywalking.oap.server.core.query.type.ProfileAnalyzeTimeRange;\\nimport org.apache.skywalking.oap.server.core.storage.StorageModule;\\nimport org.apache.skywalking.oap.server.core.storage.profiling.trace.IProfileThreadSnapshotQueryDAO;\\nimport org.apache.skywalking.oap.server.library.module.ModuleManager;\\nimport java.io.File;\\nimport java.io.FileInputStream;\\nimport java.io.IOException;\\nimport java.io.OutputStream;\\nimport java.io.BufferedOutputStream;\\nimport java.io.FileOutputStream;\\nimport java.util.ArrayList;\\nimport java.util.List;\\nint QUERY_PROFILE_SNAPSHOT_RETRY_COUNT;\\nint QUERY_PROFILE_WRITE_PROCESS_LOG;\\nquerySnapshot(String segmentId,IProfileThreadSnapshotQueryDAO threadSnapshotQueryDAO,SequenceRange sequenceRange);\\nparseFromFileWithTimeRange(File file,List timeRanges);\\ndump(ProfiledBasicInfo basicInfo,ModuleManager manager);\\n\", \"repo_level\" : \"public interface ProfileThreadSnapshotRecord {public String id();\\npublic ProfileThreadSnapshotRecord storage2Entity(Convert2Entity converter);\\npublic void entity2Storage(ProfileThreadSnapshotRecord storageData,Convert2Storage converter);\\n }\\npublic interface ProfileAnalyzeTimeRange { }\\npublic interface StorageModule {public Class[] services();\\n }\\npublic interface IProfileThreadSnapshotQueryDAO { List queryProfiledSegments(String taskId);\\n int queryMinSequence(String segmentId,long start,long end);\\n int queryMaxSequence(String segmentId,long start,long end);\\n List queryRecords(String segmentId,int minSequence,int maxSequence);\\n SegmentRecord getProfiledSegment(String segmentId);\\n }\\npublic interface ModuleManager {public void init(ApplicationConfiguration applicationConfiguration);\\npublic boolean has(String moduleName);\\npublic ModuleProviderHolder find(String moduleName);\\n }\\n\" }", "class_name": "ProfileSnapshotDumper", "code": "public static List parseFromFileWithTimeRange(File file,List timeRanges) throws IOException {\n try (final FileInputStream fileInputStream=new FileInputStream(file)){\n ThreadSnapshot snapshot;\n final ArrayList data=new ArrayList<>();\n while ((snapshot=ThreadSnapshot.parseDelimitedFrom(fileInputStream)) != null) {\n ThreadSnapshot finalSnapshot=snapshot;\n if (timeRanges.stream().filter(t -> finalSnapshot.getTime() >= t.getStart() && finalSnapshot.getTime() <= t.getEnd()).findFirst().isPresent()) {\n data.add(snapshot);\n }\n }\n return data;\n }\n }\n", "docstring": "/** \n * load thread snapshots in appointing time range\n */\n", "end_lineno": "111", "file_content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\npackage org.apache.skywalking.oap.server.tool.profile.exporter;\n\nimport lombok.extern.slf4j.Slf4j;\nimport org.apache.skywalking.apm.network.language.profile.v3.ThreadSnapshot;\nimport org.apache.skywalking.apm.network.language.profile.v3.ThreadStack;\nimport org.apache.skywalking.oap.server.core.profiling.trace.ProfileThreadSnapshotRecord;\nimport org.apache.skywalking.oap.server.core.query.type.ProfileAnalyzeTimeRange;\nimport org.apache.skywalking.oap.server.core.storage.StorageModule;\nimport org.apache.skywalking.oap.server.core.storage.profiling.trace.IProfileThreadSnapshotQueryDAO;\nimport org.apache.skywalking.oap.server.library.module.ModuleManager;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.BufferedOutputStream;\nimport java.io.FileOutputStream;\nimport java.util.ArrayList;\nimport java.util.List;\n\n@Slf4j\npublic class ProfileSnapshotDumper {\n\n public static final int QUERY_PROFILE_SNAPSHOT_RETRY_COUNT = 3;\n public static final int QUERY_PROFILE_WRITE_PROCESS_LOG = 3;\n\n /**\n * dump snapshots to file\n */\n public static File dump(ProfiledBasicInfo basicInfo, ModuleManager manager) throws IOException {\n IProfileThreadSnapshotQueryDAO snapshotQueryDAO = manager.find(StorageModule.NAME).provider().getService(IProfileThreadSnapshotQueryDAO.class);\n List sequenceRanges = basicInfo.buildSequenceRanges();\n int rangeCount = sequenceRanges.size();\n\n String segmentId = basicInfo.getSegmentId();\n File snapshotFile = new File(basicInfo.getConfig().getAnalyzeResultDist() + File.separator + \"snapshot.data\");\n\n // reading data and write to file\n try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(snapshotFile))) {\n for (int i = 0; i < rangeCount; i++) {\n List records = querySnapshot(segmentId, snapshotQueryDAO, sequenceRanges.get(i));\n for (ProfileThreadSnapshotRecord record : records) {\n // transform to proto data and save it\n ThreadSnapshot.newBuilder()\n .setStack(ThreadStack.parseFrom(record.getStackBinary()))\n .setSequence(record.getSequence())\n .setTime(record.getDumpTime())\n .build()\n .writeDelimitedTo(outputStream);\n }\n\n // print process log if need\n if ((i > 0 && i % QUERY_PROFILE_WRITE_PROCESS_LOG == 0) || i == rangeCount - 1) {\n log.info(\"Dump snapshots process:[{}/{}]:{}%\", i + 1, rangeCount, (int) ((double) (i + 1) / rangeCount * 100));\n }\n }\n }\n\n return snapshotFile;\n }\n\n /**\n * query snapshots with retry mechanism\n */\n private static List querySnapshot(String segmentId, IProfileThreadSnapshotQueryDAO threadSnapshotQueryDAO, ProfiledBasicInfo.SequenceRange sequenceRange) throws IOException {\n for (int i = 1; i <= QUERY_PROFILE_SNAPSHOT_RETRY_COUNT; i++) {\n try {\n return threadSnapshotQueryDAO.queryRecords(segmentId, sequenceRange.getMin(), sequenceRange.getMax());\n } catch (IOException e) {\n if (i == QUERY_PROFILE_SNAPSHOT_RETRY_COUNT) {\n throw e;\n }\n }\n }\n return null;\n }\n\n /**\n * load thread snapshots in appointing time range\n */\n public static List parseFromFileWithTimeRange(File file, List timeRanges) throws IOException {\n try (final FileInputStream fileInputStream = new FileInputStream(file)) {\n ThreadSnapshot snapshot;\n final ArrayList data = new ArrayList<>();\n while ((snapshot = ThreadSnapshot.parseDelimitedFrom(fileInputStream)) != null) {\n ThreadSnapshot finalSnapshot = snapshot;\n if (timeRanges.stream().filter(t -> finalSnapshot.getTime() >= t.getStart() && finalSnapshot.getTime() <= t.getEnd()).findFirst().isPresent()) {\n data.add(snapshot);\n }\n }\n return data;\n }\n }\n}\n", "file_name": "ProfileSnapshotDumper.java", "human_label": "Load the thread snapshots from the given file in the specified time range,and return the list of those thread snapshots.", "level": "project_runnable", "lineno": "96", "name": "parseFromFileWithTimeRange", "oracle_context": "{ \"apis\" : \"[parseDelimitedFrom, isPresent, findFirst, filter, stream, getTime, getStart, getEnd, add]\", \"classes\" : \"[ThreadSnapshot, ArrayList]\", \"vars\" : \"[]\" }", "package": "org.apache.skywalking.oap.server.tool.profile.exporter", "project": "skywalking-master" } ] }